DRF Serialization

Posted under » Django on 29 Sep 2021

We're going to create a simple API to allow admin users to view and edit the polls questions.

First up we're going to define some serializers. Let's create a new module named /napi/serializers.py that we'll use for our data representations.

from polls.models import Question
from rest_framework import serializers

class QuestionSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Question
        fields = ['question_text',]

Notice that we're using hyperlinked relations in this case with HyperlinkedModelSerializer. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.

As usual, our codes go to views.py

from django.http import HttpResponse
from polls.models import Question
from rest_framework import viewsets
from rest_framework import permissions
from napi.serializers import QuestionSerializer

class QuestionViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    permission_classes = [permissions.IsAuthenticated]

def index(request):
    return HttpResponse("Hello, world. You're at the napi index.")

And the URLs.py

from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'quest', views.QuestionViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', views.index, name='index'),
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.

Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.

Finally, we're including default login and logout views for use with the browsable API.

...
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))

That's optional, but useful if your API requires authentication and you want to use the browsable API.

Using the browser, go to http://mysite/napi/quest/ and you will see something like

If your CSS is not there, you will have to recollect your static files.

Please read part 2 of DRF Serialization

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data