8.1. REST

8.1.1. RESTful Views

import json
from django.http import JsonResponse, HttpResponse
from django.views import View
from contact.models import Person


class ContactAPI(View):
    http_method_names = ['get', 'post', 'options']

    def options(self, request, *args, **kwargs):
        response = HttpResponse(status=200)
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = ', '.join(self.http_method_names).upper()
        response['Access-Control-Allow-Headers'] = 'Content-Type'
        return response

    def get(self, *args, **kwargs):
        result = {'people': list(Person.objects.all().values())}
        return JsonResponse(status=200, data=result, safe=False)

    def post(self, request, *args, **kwargs):
        data = json.loads(request.body, encoding='utf-8')
        try:
            person, created = Person.objects.update_or_create(**data)

            if created:
                return JsonResponse(status=201, data={'status': 'Created'}, safe=False)
            else:
                return JsonResponse(status=200, data={'status': 'Updated'}, safe=False)

        except Exception:
            return JsonResponse(status=400, data={'status': 'Bad Request'}, safe=False)
urlpatterns += [
    url(r'^api/v1/auth/', include(('rest_framework.urls', 'rest_framework'), namespace='rest_framework')),
    url(r'^api/v1/', get_schema_view(title='habitatOS API v1', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])),
    url(r'^api/$', RedirectView.as_view(permanent=False, url='/api/v1/')),
]

8.1.2. python -m json.tool

8.1.3. django-rest-framework

$ pip install django-rest-swagger
admin.py:
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],

    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
}

8.1.4. django-rest-swagger

Alternatywa:

admin.py:
SWAGGER_SETTINGS = {
    'DOC_EXPANSION': 'list',
    'OPERATIONS_SORTER': 'alpha',
    'api_version': '1.0',
}