Yuval Adam
Yuval Adam

Reputation: 165182

Using django-tastypie for a non-RESTful API

Suppose you need to write a simple non-RESTful API, and want to do it using django-tastypie, how would you do so?

Tastypie only provides Resources that are tightly coupled to a data model.

Is there a way to use tastypie's other utilities for APIs (such as authentication, serlialization, etc.) but use it for "simple" APIs? Of course this could be written as a simple view, but then you'd be missing out on the other stuff tastypie gives you.

A simple example would be an API that receives a string and reverses it.

Upvotes: 1

Views: 234

Answers (1)

cpf
cpf

Reputation: 439

This is the purpose of prepend_urls - you can add custom endpoints to your existing methods. Out-of-the-box they work just like plain views, but you now have the ability to call all the functions you need from your Resource - and return either plain HttpResponses or piggyback on existing Tastypie functions to return rich objects.

For instance, if I had a User resource and wanted to provide an endpoint to determine if a user is currently authenticated by returning 1 or 0, I'd do this:

def prepend_urls(self):
    return [
        #...
        url(r"^(?P<resource_name>%s)/is_authenticated?$" % (self._meta.resource_name), self.wrap_view('is_authenticated')),
        #...
    ]
# ...other methods in your Resource...
def is_authenticated(self, request, **kwargs):
    if self._meta.authentication.is_authenticated(request):
        return HttpResponse("1")
    else:
        return HttpResponse("0")

Or, if I actually wanted to return the actual user resource for the authenticated user, I could (for example) replace return HttpResponse("1") with return self.get_detail(request, id=request.user.id) - effectively simulating a call to /user/?id=[authenticated user's ID].

Upvotes: 1

Related Questions