The document discusses developing REST APIs with Python and Django Rest Framework (DRF). It explains the basics of REST, why it is used, and how to build a REST API with DRF including serializers, views, URLs, permissions, versioning, documentation, and testing. DRF allows building web APIs with Django that are highly configurable and have little boilerplate code. It also supports non-ORM data sources.
10. Serializers
from rest_framework import serializers
from .models import Book, Author
class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Book
fields = ('name', 'price', 'category', 'url')
class AuthorSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Author
fields = ('name', 'creations', 'url')
11. Views
from rest_framework import viewsets, permissions
from .models import Book, Author
from .serializers import BookSerializer, AuthorSerializer
class BookViewSet(viewsets.ModelViewSet):
""" API endpoint that allows books in the library to be viewed or edited """
queryset = Book.objects.all()
serializer_class = BookSerializer
class AuthorViewSet(viewsets.ModelViewSet):
""" API endpoint that allows Authors details to be viewed or edited """
queryset = Author.objects.all()
serializer_class = AuthorSerializer
permission_classes = (permissions.IsAuthenticated,)
12. Urls
from django.conf.urls import patterns, include, url
from django.contrib import admin
from rest_framework import routers
from book import views
router = routers.DefaultRouter()
router.register(r'book', views.BookViewSet)
router.register(r'authors', views.AuthorViewSet)
admin.autodiscover()
urlpatterns = patterns( '',
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
# Django admin
url(r'^admin/', include(admin.site.urls)),
)
19. CSRF Protection
Ensure that the 'safe' HTTP operations, such as GET,
HEAD and OPTIONS can’t be used to alter any server-side
state.
Ensure that any 'unsafe' HTTP operations, such as POST,
PUT, PATCH and DELETE, always require a valid CSRF
token.