Modern front ends and mobile apps talk to the back end through APIs that send and receive JSON. In the Python world, Django REST Framework (DRF) is the most common way to build those APIs on top of Django.
Step 1: install and register
Install with pip install djangorestframework and add "rest_framework" to INSTALLED_APPS.
Step 2: a serializer
A serializer converts model objects to JSON and validates incoming JSON:
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = ["id", "title", "duration_months"]
Think of it as the API version of a ModelForm.
Step 3: a view
class CourseList(generics.ListCreateAPIView):
queryset = Course.objects.all()
serializer_class = CourseSerializer
This one class handles GET (list all courses) and POST (create a course). RetrieveUpdateDestroyAPIView handles a single item: read, update and delete.
Step 4: a URL
Map the view in urls.py, for example path("api/courses/", CourseList.as_view()). Run the server and open the URL in the browser: DRF shows a browsable page where you can test GET and POST without any extra tools.
Status codes matter
DRF returns 200 for a successful read, 201 when something is created, 400 when the data fails validation and 404 when an item does not exist. Front-end developers rely on these codes, so do not override them without a good reason.
Before you call it done
- Permissions: decide who may create or delete.
IsAuthenticatedOrReadOnlyis a sensible starting point. - Pagination: turn it on so a list endpoint never returns thousands of rows at once.
- Tests: DRF’s
APITestCaselets you test each endpoint in a few lines.
Background reading: what is a REST API and APIs and JSON for freshers.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
