Released: txrestapi 0.1

Sorry updates have been horribly infrequent; I both had a kid and moved to Austin (in that order) in the last few months. With that out of the way, to the code...

I got frustrated chaining twisted.web.resource.Resource classes to provide a complex REST API service, so I wrote a new package that lets you do it with regular expressions and decorators, like:

@GET('^/path/to/api/method$')
    def on_api_method(self, request):
       ...
I'm pretty fond of it already. Code is on GitHub, package is available from pypi — and, of course, via easy_install. Full docs are at both sites, quick example after the jump.

Some quick tips:
  • If you give your regular expressions named groups, those will be passed into the callback as keyword arguments (like Django).
  • You can use the ALL decorator to register a callback for all methods, instead of just GET or POST or PUT or DELETE.
  • You can use multiple decorators on the same callback to register the same callback for exactly those methods.
  • Callbacks are evaluated in order, top to bottom, so put the most specific at the top.
  • You can return Resource objects from a callback as well as strings, at which point normal twisted.web traversal takes over. You can also, of course, return other APIResource objects.
from txrestapi.resource import APIResource
from txrestapi.methods import GET, POST, PUT, DELETE, ALL

class MyAPI(APIResource):

    @GET('^/(?P<id>[a-zA-Z0-9]+)')
    def get_info(self, request, id):
        return "Requested information for id %s" % id

    @POST('^/(?P<id>[a-zA-Z0-9]+)')
    def set_info(self, request, id):
        return "Setting properties on id %s" % id

    @PUT('^/(?P<id>[a-zA-Z0-9]+)')
    def create_ob(self, request, id):
        return "Trying to create object with id %s" % id

    @DELETE('^/(?P<id>[a-zA-Z0-9]+)')
    def del_ob(self, request, id):
        return "Deleting object %s" % id

    @ALL('^/')
    def default(self, request):
        return "I match everything; clearly, you aren't asking for anything interesting."

from twisted.web.server import Site
from twisted.internet import reactor
site = Site(MyAPI(), timeout=None)
reactor.listenTCP(site, port=8090)
reactor.run()

Then make assorted requests to http://localhost:8090/someid and watch them get routed to your callbacks.

2 comments

Post a Comment