Paramclasses Academy - Blog

Tutorials Details

←
Post 20 of 29
→

Django REST Framework (DRF) Fundamentals: Building REST APIs, Serializers, API Views, and JSON Responses

Django REST Framework (DRF) Fundamentals: Building REST APIs, Serializers, API Views, and JSON Responses

October 21, 2026

Introduction

Django REST Framework (DRF) is a powerful toolkit for building Web APIs using Django. It allows developers to expose database data through API endpoints so that websites, mobile applications, and other services can communicate with a Django backend.

A REST API enables applications to exchange data using HTTP methods such as GET, POST, PUT, PATCH, and DELETE. Data is commonly transferred in JSON format, which is easy for most programming languages to process.

In this module, you will learn the fundamentals of Django REST Framework, install and configure DRF, create serializers, build API views, and test endpoints using a browser or an API client.

What You Will Learn

  • What an API and REST API are.

  • What Django REST Framework does.

  • How to install and configure DRF.

  • How to create API serializers.

  • How to return JSON responses.

  • How to build API views using @api_view.

  • How to handle GET and POST requests.

  • How to create, retrieve, update, and delete records through an API.

  • How to configure API URLs.

  • How to test APIs using the DRF Browsable API and Postman.

1. What Is an API?

An API (Application Programming Interface) allows two software applications to communicate with each other.

For example, suppose you build a student management application. A mobile application may need to retrieve student records stored in your Django database. Instead of accessing the database directly, the mobile application can send a request to a Django API.

The Django backend processes the request and returns the requested data.

Example API endpoint:

GET /api/students/

Example JSON response:

[
    {
        "id": 1,
        "name": "Rahul Sharma",
        "email": "rahul@example.com",
        "course": "Python"
    },
    {
        "id": 2,
        "name": "Priya Verma",
        "email": "priya@example.com",
        "course": "Django"
    }
]

This JSON data can be used by a website, Android application, or another service.

2. What Is Django REST Framework?

Django REST Framework (DRF) is a third-party Django package designed to simplify API development.

Django already provides HTTP responses, URL routing, database models, and other backend features. DRF adds API-specific functionality, including serializers, request parsing, response rendering, authentication support, and permission controls.

Important DRF components:

  • Serializer: Converts model instances and other complex data into JSON-compatible data and validates incoming data.

  • API View: Handles incoming API requests and returns API responses.

  • Request: Provides access to parsed incoming data.

  • Response: Creates an API response that DRF can render into formats such as JSON.

  • URL routing: Connects API endpoints to their views.

  • Authentication and permissions: Help control who can access an API and what they can do.

3. Installing Django REST Framework

First, activate your project's virtual environment.

Windows:

venv\Scripts\activate

Install Django REST Framework:

pip install djangorestframework

If your virtual environment has a different name, replace venv with that folder's name.

4. Configuring DRF in settings.py

Open your Django project's settings.py file and add rest_framework to INSTALLED_APPS.

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    "rest_framework",
    "students",
]

Here, students represents your application name. Replace it if your app uses a different name.

Important: Adding rest_framework installs DRF's Django integration. It does not automatically create your API endpoints; you must define the serializers, views, and URLs.

5. Creating a Student Model

For this tutorial, we will use a Student Management System.

Open students/models.py.

from django.db import models


class Student(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    course = models.CharField(max_length=100)

    def __str__(self):
        return self.name

Run the database migrations:

python manage.py makemigrations
python manage.py migrate

Explanation:

  • name stores the student's name.

  • email stores a unique email address.

  • course stores the course name.

  • __str__() returns a readable representation of a student.

If your project already has a compatible Student model, you can reuse it instead of creating another model.

6. Creating a Serializer

A serializer converts model data into Python data types that can be rendered as JSON. It also validates incoming data before creating or updating objects.

Create a file named students/serializers.py.

from rest_framework import serializers
from .models import Student


class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ["id", "name", "email", "course"]
        read_only_fields = ["id"]

Explanation:

  • ModelSerializer automatically generates fields and common validation based on the model.

  • model = Student connects the serializer to the Student model.

  • fields defines which fields are exposed through the API.

  • read_only_fields prevents clients from setting the ID directly.

Important: Only expose fields that API clients are allowed to access. Do not include passwords, secret tokens, or private information unnecessarily.

7. Creating Your First API View

DRF provides the @api_view decorator for creating function-based API views.

Open students/views.py.

from rest_framework.decorators import api_view
from rest_framework.response import Response


@api_view(["GET"])
def hello_api(request):
    data = {
        "message": "Welcome to Django REST Framework",
        "status": "success"
    }

    return Response(data)

Explanation:

  • @api_view(["GET"]) allows GET requests to this endpoint.

  • request contains information about the incoming API request.

  • Response(data) returns data through DRF's response system.

  • DRF renders the response according to the requested or configured response format.

8. Configuring API URLs

Create or update students/urls.py.

from django.urls import path
from .views import hello_api

urlpatterns = [
    path("hello/", hello_api, name="hello_api"),
]

Now include the application URLs in the project's main urls.py file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("api/", include("students.urls")),
]

Start the development server:

python manage.py runserver

Open this URL in your browser:

http://127.0.0.1:8000/api/hello/

Expected response:

{
    "message": "Welcome to Django REST Framework",
    "status": "success"
}

You may also see DRF's Browsable API, which provides a web interface for exploring and testing API endpoints.

9. Creating a Student List API

Now create an endpoint that returns all student records.

Update students/views.py.

from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Student
from .serializers import StudentSerializer


@api_view(["GET"])
def student_list_api(request):
    students = Student.objects.all().order_by("id")
    serializer = StudentSerializer(students, many=True)

    return Response(serializer.data)

Explanation:

  • Student.objects.all() retrieves student records.

  • order_by("id") orders the results by ID.

  • many=True tells the serializer to process multiple objects.

  • serializer.data contains the serialized data returned by the API.

Add the endpoint to students/urls.py.

from django.urls import path
from .views import hello_api, student_list_api

urlpatterns = [
    path("hello/", hello_api, name="hello_api"),
    path("students/", student_list_api, name="student_list_api"),
]

Open:

http://127.0.0.1:8000/api/students/

If students exist in the database, the endpoint returns their records as JSON. If no records exist, it returns an empty list.

10. Creating a Student Through a POST Request

A POST request is commonly used to create a new resource.

Add the following view to students/views.py.

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Student
from .serializers import StudentSerializer


@api_view(["POST"])
def student_create_api(request):
    serializer = StudentSerializer(data=request.data)

    if serializer.is_valid():
        student = serializer.save()

        return Response(
            StudentSerializer(student).data,
            status=status.HTTP_201_CREATED
        )

    return Response(
        serializer.errors,
        status=status.HTTP_400_BAD_REQUEST
    )

Add the URL:

path(
    "students/create/",
    student_create_api,
    name="student_create_api"
),

Send a POST request to:

http://127.0.0.1:8000/api/students/create/

Example JSON request body:

{
    "name": "Amit Kumar",
    "email": "amit@example.com",
    "course": "Django"
}

How it works:

  1. The client sends student data.

  2. request.data provides the parsed request data.

  3. The serializer validates the values.

  4. serializer.save() creates the database record.

  5. The API returns the created student with HTTP status 201 Created.

  6. If validation fails, the API returns errors with HTTP status 400 Bad Request.

For a POST request, use an API client such as Postman or the DRF Browsable API. Configure the request body as JSON when using a client that requires explicit content-type settings.

11. Understanding HTTP Methods

REST APIs use HTTP methods to express the operation requested by a client.

HTTP Method Common Purpose Example
GET Retrieve data /api/students/
POST Create a resource /api/students/create/
PUT Replace or fully update a resource /api/students/1/
PATCH Partially update a resource /api/students/1/
DELETE Delete a resource /api/students/1/

Important: HTTP methods have different meanings. A GET request should not perform destructive operations such as deleting records.

12. Understanding HTTP Status Codes

Status codes tell the client whether a request succeeded or failed.

Status Code Meaning
200 OK Request succeeded
201 Created A resource was created successfully
204 No Content Request succeeded with no response body
400 Bad Request Request data is invalid
401 Unauthorized Authentication is missing or invalid
403 Forbidden Access is not permitted
404 Not Found The requested resource does not exist
500 Internal Server Error An unexpected server error occurred

Note: The exact status code depends on the operation and how the API is configured.

13. Testing APIs Using Postman

Postman is a tool for sending HTTP requests and inspecting responses.

To test the student creation API:

  1. Open Postman.

  2. Create a new HTTP request.

  3. Select POST.

  4. Enter http://127.0.0.1:8000/api/students/create/.

  5. Open Body.

  6. Select raw and choose JSON.

  7. Enter the student JSON data.

  8. Click Send.

  9. Check the response body and status code.

To retrieve all students, use GET with:

http://127.0.0.1:8000/api/students/

Testing tip: Try submitting an invalid email or reusing an existing email. The serializer should reject invalid data and return a validation error.

14. Common Errors and Solutions

Error 1: ModuleNotFoundError: No module named 'rest_framework'

Solution: Activate the correct virtual environment and run:

pip install djangorestframework

Confirm that rest_framework is present in INSTALLED_APPS.

Error 2: No module named 'students'

Solution: Check the app name and ensure that the app exists and is correctly configured.

Error 3: TemplateDoesNotExist

Solution: Check the template directory and the TEMPLATES setting. This can occur if you customize a view to use a template that does not exist.

Error 4: 405 Method Not Allowed

Solution: Check whether the API view allows the HTTP method you are sending. For example, a view decorated with @api_view(["GET"]) will not accept POST requests.

Error 5: 400 Bad Request

Solution: Inspect the response body for serializer validation errors. Verify required fields, email formatting, and uniqueness constraints.

Error 6: IntegrityError for duplicate email

Solution: Because the model defines email as unique, duplicate email addresses cannot be saved. Handle the validation error and ask the client to provide a different email address.

15. API Security Best Practices

When building real-world APIs, follow these practices:

  • Validate input: Use serializers to validate incoming data.

  • Protect private endpoints: Configure authentication and permissions where required.

  • Restrict access: Do not allow every user to modify or delete every record.

  • Expose only necessary fields: Avoid returning confidential information.

  • Use HTTPS in production: Encrypt data exchanged between clients and servers.

  • Handle errors safely: Return useful validation messages without exposing internal tracebacks.

  • Control request volume: Consider throttling for endpoints that need protection against excessive requests.

  • Test authorization: Verify that users cannot access another user's private data by changing an object ID.

Important: The example API endpoints in this module are introductory examples. Before deploying them publicly, review authentication, permissions, rate limits, and access to sensitive records.

16. Frequently Asked Questions (FAQs)

Q1. What is Django REST Framework?

Django REST Framework is a toolkit that simplifies the development of Web APIs using Django.

Q2. What is a serializer?

A serializer converts complex data, such as Django model instances, into JSON-compatible data and validates incoming data.

Q3. What is the difference between Django's JsonResponse and DRF's Response?

JsonResponse is a Django response class for JSON data. DRF's Response works with DRF's rendering system and supports configured content negotiation.

Q4. What does many=True mean?

It tells a serializer to process multiple objects instead of a single object.

Q5. What is request.data?

It provides access to parsed request data, including supported JSON and form submissions.

Q6. Can a REST API be used by mobile applications?

Yes. Mobile applications can send HTTP requests to an API and process its JSON responses.

Q7. Is a REST API automatically secure?

No. Authentication, permissions, validation, HTTPS, and appropriate data-access rules must be configured according to the application's requirements.

17. Django REST Framework Interview Questions and Answers

Q1. What is DRF used for?

Answer: DRF is used to build Web APIs with Django, including endpoints for retrieving, creating, updating, and deleting data.

Q2. What is the difference between a model and a serializer?

Answer: A model defines the database structure and data behavior. A serializer converts data to and from API-compatible representations and validates incoming values.

Q3. Why do we use @api_view?

Answer: It converts a function into a DRF API view and allows specific HTTP methods to be declared.

Q4. Why do we use Response?

Answer: It creates an API response that DRF can render into the appropriate format.

Q5. What does serializer.is_valid() do?

Answer: It validates the submitted data against serializer fields and validation rules.

Q6. What is the difference between HTTP 200 and 201?

Answer: HTTP 200 indicates a successful request. HTTP 201 indicates that a resource has been created.

Q7. What is the purpose of serializer.save()?

Answer: It saves the validated data by creating or updating an object, depending on how the serializer was initialized.

18. Practical Assignment

Create a Student Management REST API using Django REST Framework.

Requirements:

  1. Create a Student model containing name, email, and course.

  2. Create a StudentSerializer using ModelSerializer.

  3. Create a GET endpoint to retrieve all students.

  4. Create a POST endpoint to add a student.

  5. Return JSON responses from the API.

  6. Use suitable HTTP status codes.

  7. Test valid and invalid requests using Postman or the DRF Browsable API.

  8. Test duplicate email validation.

  9. Add an endpoint that returns a welcome message.

  10. Document the available API endpoints and their HTTP methods.

Expected Result:

You should have a working Django REST API that retrieves student records and creates new records through validated JSON requests.

Conclusion

In this module, you learned the fundamentals of Django REST Framework, including API configuration, serializers, function-based API views, JSON responses, HTTP methods, status codes, and API testing.

These concepts form the foundation for building APIs used by websites, mobile applications, dashboards, and other backend services.

In the next module, you will learn about Django REST Framework CRUD APIs, including retrieving a single object, updating records with PUT and PATCH, deleting records, and organizing API endpoints for a complete application.

←
Post 20 of 29
→