Low level RESTful web service API

http://en.wikipedia.org/wiki/Representational_State_Transfer#RESTful_web_services

This API was first introduced in this github issue

Tutorial

For this tutorial, create the myexample django application. You can see the result of everything we explain here in devilry/projects/dev/apps/restfulexample/.

A simple RESTful example

We will start with a creating a CRUD+s (create, read, update, delete and search) interface. restfulexample/restful.py:

from devilry.restful import RestfulManager, RestfulView, SerializableResult, restful_api

example_restful = RestfulManager()

@example_restful.register
@restful_api
class RestfulExample(RestfulView):

    def crud_create(self, request, id):
        # Create something here...
        return SerializableResult(dict(message="Successfully created something"))

    def crud_read(self, request, id):
        # A real application would probably get data from the database
        # using the given ``id`` here
        result = dict(data="Hello world", id=id)
        return SerializableResult(result)

    def crud_update(self, request):
        return SerializableResult('Updating')

    def crud_delete(self, request):
        return SerializableResult('Deleting')

    def crud_search(self, request):
        return SerializableResult(['Hello', 'Cruel', 'World'])

@example_restful is a RestfulManager where we register our RestfulExample. The RestfulManager is only used to simplify setting up URLs for big restful APIs.

Read, update and delete requires an identifier (id), because it makes no sense to manipulate an object that we can not identify. Each method returns a SerializableResult, whose first argument is a serializable python object. The default serializer is JSON, which means that our class returns JSON unless the HTTP request contains a HTTP Accept header specifying another content type.

Registering urls for RestfulExample

Since we use a RestfulManager, URL generation is very simple. restfulexample/urls.py looks like this:

from django.conf.urls.defaults import patterns
from restful import example_restful

urlpatterns = patterns('devilry.apps.restfulexample')
urlpatterns += example_restful

API

devilry.restful.restful_modelapi(cls)

ModelRestfulView is used in conjunction with the restful_modelapi-decorator to autogenerate a RESTful interface for a simplified class (see Simplified API).

The cls must have an inner class named Meta with the following attributes:

simplified
A Simplified API class. Required.
foreignkey_fields
A dictionary mapping foreign key fields to RESTful classes that contains the data for the foreign key field.

The decorator automatically decorates cls with restful_api().

The decorator adds the following attributes to cls:

_meta
Alias for the Meta class (above).
supports_*
Copied from _meta.simplified._meta.
SearchForm
A Django form that can be used to validate the keyword arguments sent to the search() method in Simplified API.
EditForm
A Django model form that can be used to validate and edit the model specified in Simplified API specified in _meta.simplfied._meta.model.
devilry.restful.restful_api(cls)

RestfulView and the restful_api()-decorator is use in conjunction to create a RESTful web service with a CRUD+S interface.

Adds the _meta attribute to the decorated class. The _meta attribute has the following attributes:

urlprefix
The url prefix used for the url created by RestfulView.create_rest_url(). This is always: cls.__name__.lower()
urlname
The name of the url created by RestfulView.create_rest_url(). This is the full python dot-path to cls with . replaced by -.
class devilry.restful.RestfulView(**kwargs)

Bases: django.views.generic.base.View

RestfulView and the restful_api()-decorator is use in conjunction to create a RESTful web service with a CRUD+S interface.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

classmethod create_rest_url()

Create a django.conf.urls.defaults.url-object for this view:

r'^{urlprefix}/(?P<id>[a-zA-Z0-9]+)?$

Where urlprefix is cls._meta.urlprefix documented in restful_api().

The name of the url is the cls._meta.urlname, documented in restful_api().

The view is wrapped by forbidden_if_not_authenticated().

delete(request, *args, **kwargs)

Maps HTTP DELETE requests to the crud_delete method, which subclasses can implement.

get(request, *args, **kwargs)

Maps HTTP POST requests to the crud_read and crud_search methods, which subclasses can implement. crud_read is called when id is in kwargs.

classmethod get_rest_url(*args, **kwargs)

Get the reverse url for this view. Shortcut for:

from django.core.urlresolvers import reverse
reverse(cls._meta.urlname, args=args, kwargs=kwargs)
post(request, *args, **kwargs)

Maps HTTP POST requests to the crud_create method, which subclasses can implement.

put(request, *args, **kwargs)

Maps HTTP PUT requests to the crud_update method, which subclasses can implement.

class devilry.restful.ModelRestfulView(**kwargs)

Bases: devilry.restful.restview.RestfulView

ModelRestfulView is used in conjunction with the restful_modelapi-decorator to autogenerate a RESTful interface for a simplified class (see Simplified API).

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

crud_create(request)

Maps to the create method of the simplified class.

crud_delete(request, id=None)

Maps to the delete method of the simplified class.

crud_read(request, id)

Maps to the read method of the simplified class.

Maps to the search method of the simplified class.

crud_update(request, id=None)

Maps to the update method of the simplified class.

extra_create_or_replace_responsedata(obj_id)

If this does not return None, the return-value is added to the extra_responsedata attribute of the data returned on create() or update().

Parameters:obj_id – The id of the object changed by the create or update call.
class devilry.restful.SerializableResult(result, httpresponsecls=<class 'django.http.HttpResponse'>, encoding='utf-8')

Bases: object

Stores Python objects for serialization with devilry.simplified.serializers.SerializerRegistry.

class devilry.restful.RestfulManager

Bases: object

The RestfulManager is used to simplify setting up URLs for (big) restful APIs.

Basically, you create a RestfulManager-object, lets call it myrestapi, in you restful api, and decorate all your devilry.restful.RestfulView classes with @myrestapi.register.

You can then add the urls by adding them to a django.conf.urls.defaults.patterns-object like so:

urlpatterns = patterns('devilry.apps.myexample')
urlpatterns += myrestapi

An alternative would be to not decorate your views using this class, and rather use devilry.restful.RestfulView.create_rest_url().

iter_restfulclasses()

Iterate over the registered RESTful API classes and yield each API class.

register(restapi)

Register the given restapi with the manager.

Parameters:restapi – A subclass of devilry.restful.RestfulView.

Table Of Contents

Previous topic

Simplified API

Next topic

devilry.rest — General purpose RESTful tools

This Page