Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple RESTFUL client/server example in Python?

Tags:

python

django

Is there an online resource that shows how to write a simple (but robust) RESTFUL server/client (preferably with authentication), written in Python?

The objective is to be able to write my own lightweight RESTFUL services without being encumbered by an entire web framework. Having said that, if there is a way to do this (i.e. write RESFUL services) in a lightweight manner using Django, I'd be equally interested.

Actually, coming to thing of it, I may even PREFER a Django based solution (provided its lightweight enough - i.e. does not bring the whole framework into play), since I will be able to take advantage of only the components I need, in order to implement better security/access to the services.

like image 560
morpheous Avatar asked Sep 05 '10 09:09

morpheous


2 Answers

Well, first of all you can use django-piston, as @Tudorizer already mentioned.

But then again, as I see it (and I might be wrong!), REST is more of a set of design guidelines, rather than a concrete API. What it essentially says is that the interaction with your service should not be based on 'things you can do' (typical RPC-style methods), but rather 'things, you can act on in predictable ways, organized in a certain way' (the 'resource' entity and http verbs).

That being said, you don't need anything extra to write REST-style services using django.

Consider the following:

# urlconf
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
    url(r'^tickets$', 'myapp.views.tickets', name='tickets'),
    url(r'^ticket/(?P<id>\d+)$', 'myapp.views.tickets', name='ticket'),
    url(r'^ticket$', 'myapp.views.tickets', name='ticket'),
)

# views
def tickets(request):
    tickets = Ticket.objects.all()
    return render_to_response('tickets.html', {'tickets':tickets})

def ticket(request, id=None):
    if id is not None:
        ticket = get_object_or_404(Ticket, id=id)
    if request.method == 'POST':
        # create or update ticket here
    else:
        # just render the ticket (GET)
    ...

... and so on.

What matters is how your service is exposed to its user, not the library/toolkit/framework it uses.

like image 184
shylent Avatar answered Oct 18 '22 01:10

shylent


This one looks promising. http://parand.com/say/index.php/2009/04/30/django-piston-rest-framework-for-django/ I've used it before and it's pretty nifty. Having said that, it doesn't seem maintained recently.

like image 2
Tudor Avatar answered Oct 18 '22 01:10

Tudor