Released: txrestapi 0.1
written by Ian McCracken
at Monday, September 6, 2010
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:
I'm pretty fond of it already. Code is on GitHub, package is available from pypi — and, of course, via@GET('^/path/to/api/method$') def on_api_method(self, request): ...
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 otherAPIResource
objects.
Then make assorted requests tofrom 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()
http://localhost:8090/someid
and watch them get routed to your callbacks.
January 19, 2011 at 5:20 PM
Very nice!
I'd like to see an example of returning a Resource, perhaps as a follow-on post?
Also, you should really add this to the 'tx' project on Launchpad: https://launchpad.net/tx
July 27, 2015 at 5:27 PM
Thank you.