Table Of Contents

RESTful URLs with TurboGearsΒΆ

One idea behind a RESTful API is to make use of URLs like http://mysite/id/verb, where id is a database identifier and verb is an action to take, like “show”.

So, examples can be:


To help you create such an API, you can define the following mixin class:

class content:

    def default(self, *vpath, **params):
        if len(vpath) == 1:
            identifier = vpath[0]
            action =
        elif len(vpath) == 2:
            identifier, verb = vpath
            verb = verb.replace('.', '_')
            action = getattr(self, verb, None)
            if not action:
                raise cherrypy.NotFound
            if not
                raise cherrypy.NotFound
            raise cherrypy.NotFound
        items = self.query(identifier)
        if items.count() == 0:
            raise cherrypy.NotFound
            return action(items[0], **params)

Using this class, you can implement your restful API as follows:

class Root(controllers.RootController, content):

    def show(self, thing):
        return dict(text=thing.text)

    def edit(self, thing):
        return dict(text=thing.text)

    def query(self, name):
        return model.something.byName(name=name)

See for information on why RESTful urls are useful.