Building REST APIs with Django REST Framework

Django Rest Framework is great for building REST APIs with Django and automates a lot of the tasks required for standing up APIs with Python.

We can install DRF with:

pip install djangorestframework

Be sure to include the rest_framework in your installed apps in settings.py or settings/base.py like so:

INSTALLED_APPS = (
...
'rest_framework',
)

We can also set permissions in the settings.py or settings/base.py file like so:

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}

Further documentation for specific desired permissions can be found on the documentation site here: http://www.django-rest-framework.org/

Next, we can implement our API with view logic like so:

from rest_framework.views import APIView
from rest_framework import permissions
from rest_framework.response import Response
class Api(APIView):
"""
Our API CBV
"""
# Set permissions for API endpoint
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    def get(self, request, format=None):
"""
GET API Method
"""
# View Logic Here
api_result = {"key_1":"val_1", "key_2":"val_2", ... }
return Response(api_result)

Our API Endpoint must be defined in the urls.py file:

import proj.app.views as views
urlpatterns = [
url(r'^endpoint/$', views.Api.as_view()),
]

Now, we can hit the API endpoint with GET requests and receive valid responses.

The API permissions can be tooled with to allow for various authentication arrangements for various types of requests. Further details can be found in the documentation here: http://www.django-rest-framework.org/api-guide/permissions/. It is important that we arrange proper permissions to ensure that we build secure APIs.

Have fun building APIs with DRF!