REST scaffolding

Use the urls.rest() function to quickly create a REST interface for a specific model.

Example app.urls.py file:

from api.urls import rest
from django.contrib.auth.models import User
from .models import List, Task

# Add a REST endpoint for todo lists, which can represent the
# relationship between a list, its creator and the tasks in that list.
urlpatterns = rest(
    List,
    fields=(
        'name',
        'created',
        'updated',
        'icon'
    ),
    relations=(
        'creator',
        'tasks'
    )
)

# Add a REST endpoint for tasks, which can represent the relationship
# back to the parent list.
urlpatterns += rest(
    Task,
    fields=(
        'name',
        'created',
        'updated',
        'completed'
    ),
    relations=(
        'list'
    )
)

# Add a REST endpoint for a user, which can represent the relationship
# between the user and their tasks.
urlpatterns += rest(
    User,
    fields=(
        'first_name',
        'last_name',
        'date_joined',
        'last_login'
    ),
    readonly_fields=(
        'date_joined',
        'last_login'
    ),
    pk_field='username',
    relations={
        'lists',
    }
)

API reference

urls.rest(resource, **kwargs)[source]

Creates model list and detail resources, and API endpoints to interact with them.

Parameters:
  • resource (django.db.models.Model, ModelResource) – The Django model to create a REST interface for, or the resource to use when creating the endpoints.
  • fields (list, tuple) – (optional) A list of field names to include in resource objects.
  • exclude (list, tuple) – (optional) A list of field names to exclude from resource objects.
  • readonly_fields (list, tuple) – (optional) Names of fields that are not updateable via the API.
  • prepopulated_fields (dict) – (optional) A dictionary of fields with lamba expressions for setting model properties (lke setting the current user as the creator of an object).
  • form_class (django.forms.ModelForm) – (optional) Overrides the factory-generated model form
  • queryset (lambda, func) – (optional) A replacement for the default queryset
  • order_by (list, tuple) – (optional) A list of field names to order the objects by.
  • pk_field (str) – (optional) The primary key field name.
  • paginate_by (int) – (optional) The number of items to return in a paginated list. (Defaults to the value of settings.API_DEFAULT_RPP.)
  • relations (list, tuple) – (optional) A list of many-to-many or many-to-one relationships that need to be represented in the API.
  • authenticators (list, tuple) – (optional) Override the default authenticators for this endpoint. (Defaults to the value of settings.API_DEFAULT_AUTHENTICATORS.)
  • authorisers (list, tuple) – (optional) Override the default authorisers for this endpoint. (Defaults to the value of settings.API_DEFAULT_AUTHORISERS.)
:param resource_kwargs
[optional] Add to the default keyword argument dict that is passed to the resource.