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]
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@spyne.io is also at your service.
Best,
Burak