|
RestifyDjango
How to provide a REST API for an existing Django application using the Django REST interface
1. Design the interface Decide, which resources you want to make available and in what way. Resources are sources of specific information, each of which can be referred to using a global identifier (a URI). In order to manipulate these resources, components of the network (clients and servers) communicate via a standardized interface (e.g. HTTP) and exchange representations of these resources (the actual documents conveying the information). Wikipedia: REST Usually, this involves four steps:
Some resources may directly correspond to Django models, others may not involve model data at all (e.g. an index page for service discovery) or may correspond to more than one model (e.g. a "marriage" resource that corresponds to a "married_to" one-to-one relationship between two user models). For a good example of how to identify the resources of a complex application, see Restify DayTrader. 2. Create model-based resources For every model you want to be part of the API, create a Collection instance and add it to urlpatterns in urls.py: from django_restapi.model_resource import Collection
from django_restapi.responder import XMLResponder
from django_restapi_tests.polls.models import Poll, Choice
xml_poll_resource = Collection(
queryset = Poll.objects.all(),
permitted_methods = ('GET', 'POST', 'PUT', 'DELETE'),
responder = XMLResponder(paginate_by = 10)
)
urlpatterns = patterns('',
# ...
url(r'^xml/polls/(.*?)/?$', xml_poll_resource),
)3. Create non-model-based resources Subclass Resource, overwrite some or all of the create/read/update/delete methods and, in some cases, get_url, and add it to urlpatterns in urls.py: from django_restapi.resource import Resource
class MyResource(Resource):
def read(self, request):
# ...
def update(self, request):
# ...
urlpatterns = patterns('',
# ...
url(r'^my_resource/$', MyResource()),
)See an example. |
Sign in to add a comment
Hi All,
I found an error in example #3. The create/read/update/delete signatures need args and kwargs arguments to work.
class MyResource(Resource): def read(self, request, *args, **kwargs): # ... def update(self, request, *args, **kwargs): # ...Why in the examples do you need to clone the queryset? Can't you just filter it at return the results?
This is useful, but is there any way to get django to get data too and not just returning data?
Say I want to make a function that will request restful data from another django server and return it as restful data combined with other data.
I know I can use any http request library like urllib2, but urllib2 has no read timeout (socket timeout is a connect timeout). There's also twisted but that looks like killing a fly with a sledgehammer type situation.
any ideas about writing web services in Django for logging errors?? please help me out http://www.hkshambesh.com