Django·Django from project to API

Build a REST API

Expose models through Django REST Framework with serializers and viewsets.

Intermediate 22 min read Lesson 10 of 300 Challenge included
What you will be able to do
  • Install djangorestframework and add it to INSTALLED_APPS.
  • Create serializers for input and output.
  • Use ModelViewSet and a router.
  • Add permission classes and pagination.

In plain English

DRF turns Django models into JSON endpoints. A serializer validates input and shapes output. A viewset maps CRUD actions to routes through a router. Add permissions and pagination before exposing the API.

api.pyPython
from rest_framework import serializers, viewsets, permissions
from rest_framework.routers import DefaultRouter
from .models import Course

class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = ('id', 'slug', 'title', 'created_at')

class CourseViewSet(viewsets.ModelViewSet):
    queryset = Course.objects.all().order_by('title')
    serializer_class = CourseSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

router = DefaultRouter()
router.register('courses', CourseViewSet)
Your turn

Add a read-only endpoint

Medium

Set the CourseViewSet permission to read-only for everyone.

PYTHON · starter
permission_classes = []
Check your understanding before moving on.
Knowledge checkQuestion 1

What does a ModelSerializer do?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 10 of 300 · 0% of course