11. REST

11.1. RESTful Views

Code Listing 11.20. RESTful Views
import json
from django.http import JsonResponse, HttpResponse
from django.views import View
from contact.models import Contact


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 = {'contacts': list(Contact.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:
            contact, created = Contact.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/')),
]

11.2. python -m json.tool

11.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',
    ],
}

11.4. django-rest-swagger

Alternatywa:

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