Django Rest Framework

Standards

Put the API views (ViewSet etc) in an api.py file e.g. contact/api.py.

URLs to include namespace="api" e.g:

url(
    regex=r"^api/0.1/", view=include((router.urls, "api"), namespace="api")
),

Usage

Requirements:

# requirements/base.txt
djangorestframework

Tip

Find the version number in Requirements

In example/base.py for an app, settings/base.py for a project:

THIRD_PARTY_APPS = (
    'rest_framework',
    # http://www.django-rest-framework.org/api-guide/authentication#tokenauthentication
    'rest_framework.authtoken',

# http://www.django-rest-framework.org/api-guide/authentication#tokenauthentication
REST_FRAMEWORK = {
    'COERCE_DECIMAL_TO_STRING': True,
    # not sure if this is required or not
    # 'DATETIME_FORMAT': '%Y%m%dT%H%M%SZ',
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAdminUser',
    ),
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}

Add the following to urls.py (perhaps in your project folder):

from rest_framework.authtoken import views

url(regex=r'^token/$',
    view=views.obtain_auth_token,
    name='api.token.auth',
    ),

Note

You can change the regex to another URL if you want…

Create a token for each of the users who will use the API:

from rest_framework.authtoken.models import Token
Token.objects.create(user=...)

Tip

To auto-generate a token for every user, check out TokenAuthentication

MethodNotAllowed

To prevent use of a method, add the following to your viewsets.ModelViewSet:

from rest_framework.exceptions import MethodNotAllowed

def create(self, request, *args, **kwargs):
    raise MethodNotAllowed(
        "POST", detail="Method 'POST' not allowed"
    )

def perform_destroy(self, instance):
    raise MethodNotAllowed(
        "GET", detail="Method 'GET' not allowed"
    )

To test:

from http import HTTPStatus

assert HTTPStatus.METHOD_NOT_ALLOWED == response.status_code
error_detail = response.data["detail"]
# or
# error_detail = response.data["errors"]
assert "Method 'POST' not allowed" == str(error_detail)
# or
# assert "Method "GET" not allowed" == str(error_detail)

Testing

Sample

Test code using the api_client fixture from our api app:

import pytest

from django.urls import reverse
from http import HTTPStatus

from api.tests.fixture import api_client
from login.tests.factories import UserFactory

@pytest.mark.django_db
def test_something(api_client):
    response = api_client.get(reverse('docrecord.api.document'))
    assert HTTPStatus.OK == response.status_code, response.data

URL

For this router:

router.register(r"tasks", ExampleWorkTaskViewSet, basename="task")

We can test as follows:

# create returns 'HTTPStatus.CREATED'
.post(reverse("api:task-list"))

# get (retrieve)
.get(reverse("api:task-detail", args=[str(uuid.uuid4())]))

# update
.put(reverse("api:task-detail", args=[str(uuid.uuid4())]), data)

# delete - returns  'HTTPStatus.NO_CONTENT'
.delete(reverse("api:task-detail", args=[str(uuid.uuid4())]))

# list
.get(reverse("api:task-list"))