Returning HTTP responses with django-tastypie

Here at MutualMind, we’ve built our REST developer API using the excellent django-tastypie framework. Once you understand the basic request/response cycle as mentioned in the documentation, it takes hardly any time get a full featured REST API up and running. However, the documentation is missing one piece of information: What is the proper way to return various HTTP responses?
Not to worry. After taking a deep dive into the framework’s code, I’ve discovered this well kept secret. There are two pieces to this puzzle. One is a class found in tastypie.exceptions called ImmediateHttpResponse. And the other is a set of HTTP response classes found in tastypie.http. These classes include (but are not limited to):
- HttpCreated: HTTP 201
- HttpBadRequest: HTTP 400
- HttpForbidden: HTTP 403
- HttpNotFound: HTTP 404
- HttpApplicationError: HTTP 500
So let’s see an example. Let’s say that you need to stop request processing and send a response back to the client saying that the resource it is trying to access is forbidden. First you would import the appropriate classes:
from tastypie.exceptions import ImmediateHttpResponse from tastypie.http import HttpForbidden
In your API code, you could then raise an ImmediateHttpResponse and pass in the HttpForbidden object to the constructor:
raise ImmediateHttpResponse(
HttpForbidden("Coleman?! There is no Coleman here.")
)
You can substitute the response class with any of the others found in tastypie.http. Have fun baking tasty APIs with django-tastypie.
UPDATE (Nov 25, 2011 @ 4:33AM) Daniel Lindley, the author of django-tastypie pointed me to an alternative way to return an HTTP response. Simply invoke the create_response function of your Resource or ModelResource class. Just pass in the HTTP response class to it using the response_class keyword argument like so:
return self.create_response(
request, bundle,
response_class = HttpForbidden
)
-
Anonymous
-
Anonymous