Skip to content
Nov 18 / Nizam Sayeed

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

    This is an acceptable approach, but shortcircuits a large part of the functionality. A better approach is something like https://github.com/toastdriven/django-tastypie/blob/66832f1f619c49fa861e47d8dbc21475e3ded79d/tastypie/resources.py#L1173, where you pass the correct “HttpResponse“ subclass to “create_response“. This helps return your data in the correct serialization format & follows the typical request-response flow.

    • Anonymous

      Daniel,

      Thanks for the clarification! Since I didn’t see this documented, I had to figure a way to do this on my own. Now I know the correct way to return responses. Thanks again!