REST and TG

TurboGears has used a tree of controller objects to do URL dispatch since 1.0. Which is nice and easy to understand, and makes getting started very quick. But, it wasn’t always apparent how you should use it to do RESTful dispatch, since the HTTP verbs all ended up going to the same controller method.

You could dispatch within that method, but that never felt totally clean to me. And I’ve been thinking and talking about better ways to do this. The good news is that Rick Copland just “made it happen” after a conversation in atlanta last week.

Using his trick you can write code like this:

class Root(controllers.RootController):

    class person(RestMethod):
        @expose('json')
        def get(self, **kw):
            #...do stuff...
            return dict(method='GET', args=kw)

        @expose('json')
        def post(self, **kw):
             #...do stuff...
            return dict(method='POST', args=kw)

        # NOT exposed
        def delete(self, **kw):
            return dict(method='DELETE', args=kw)

And then HTTP GET and POST verbs will be routed to their respective methods. This makes working with RESTFul api’s easier. And on that front I’m very much looking forward to Dojo 1.2 which has all of kinds of restful json data store goodness.

Hopefully Rick’s recipe can find it’s way into the 1.x core code somewhere so that it’s even easier to do. But for now a couple dozen lines of code gives you everything you need for RESTful goodness.