[Twisted-Python] How to design REST API with Twisted?

Wang Yan snailcoder at 163.com
Tue Nov 3 20:15:16 MST 2015


I'm planning to design some REST APIs with Twisted in Python. For example, I want to use the HTTP method "GET" to fetch a single user's information:

GET http://myhost:8000/api/v1.0/users/[user_id]

I know I should inherit the twisted.web.resource.Resource and implement "getChild" by myself. 
The question is, should I implement a class for each segment of the URI? If so, I have to implement class API, class V1, class Users and Class User. In other words, if there're 10 segments in the URI, do I have to implement 10 classes to represent those resources?






At 2015-10-25 20:13:58, "Burak Arslan" <burak.arslan at arskom.com.tr> wrote:
Hey!


On 10/25/15 13:04, Wang Yan wrote:

Hi,


I'm confused about how to design REST APIs with Twisted, especially when my app have to interact with MySQL. 


Is there any basic design patterns for this kind of situation?

I do Spyne, and I think it's fa-bu-lous for building any web API on top of twisted.

It's a bit different from what you to with stock Twisted though. More specifically, there's no NOT_DONE_YET. The client hangs as long as you keep returning `Deferred`s. Once you return a non-deferred (and hopefully something that's compatible with your designated return type) that object is serialized using the `out_protocol` you pass to your `Application` and the resulting byte stream is written to the outgoing stream of your transport of choice. In case of a HTTP-based api, it's passed to the `transport.write()` function of a `twisted.web.Resource` instance, along with the outgoing headers that you set.

As for the MySQL part, I use SQLAlchemy exclusively from inside a function called by deferToThread. Spyne integrates with SQLAlchemy as well, so you can return directly what SQLA returns, be it objects or rows.

Here's a simple example: https://github.com/arskom/spyne/blob/master/examples/twisted/resource.py

There's a boilerplate generator here: http://spyne.io/

I hope you find it useful. Any questions, people at spyne.io is also at your service.

Best,
Burak
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://twistedmatrix.com/pipermail/twisted-python/attachments/20151104/ccc9151b/attachment.html>


More information about the Twisted-Python mailing list