Skip to content

RESTful and DRF Getting Started

Django REST framework (DRF) is a Web API development framework built on top of Django, designed specifically for frontend-backend separation architectures. This article starts with the RESTful design specification, introduces DRF’s core features and configuration, and walks you through a complete five-step example to get you up and running quickly.

Frontend-Backend Separation and RESTful

Two Web Application Modes

In the traditional tightly-coupled mode, the server renders and returns complete HTML pages. Frontend and backend are tightly coupled, making it difficult to reuse interfaces.

In the frontend-backend separation mode, the backend only provides data (JSON/XML), while frontend frameworks (React, Vue, etc.) or mobile clients handle rendering. The two sides communicate through APIs, allowing the same backend interface to serve web, iOS, Android, mini-programs, and other clients simultaneously.

RESTful Design Specification

REST (Representational State Transfer) was proposed by Roy Fielding in his doctoral dissertation in 2000 and is currently the most mainstream API interface design style. Its core idea is: treat all backend data as resources, use URLs to declare resource locations, and use HTTP methods to declare operations on resources.

URL Naming Rules

  • Only nouns (plural) appear in URLs; no verbs.
  • Use / to separate resource hierarchies; no trailing /.
  • Paths containing verbs like /getStudents or /deleteOrder are forbidden.
# Correct
GET  /api/students          # Get student list
POST /api/students          # Create a student
GET  /api/students/5        # Get student with id=5
PUT  /api/students/5        # Full update
PATCH /api/students/5       # Partial update
DELETE /api/students/5      # Delete

HTTP Method Semantics

MethodOperationNotes
GETQueryIdempotent; does not modify state
POSTCreateNon-idempotent; returns 201
PUTFull updateIdempotent; full resource required
PATCHPartial updateIdempotent; submit changed fields only
DELETEDeleteIdempotent; returns 204 No Content

Common Status Codes

Status CodeMeaning
200OK — Request succeeded
201Created — Resource created successfully
204No Content — Delete succeeded, no body
400Bad Request — Invalid request parameters
401Unauthorized — Not authenticated
403Forbidden — Authenticated but no permission
404Not Found — Resource does not exist
500Internal Server Error — Server-side error

Versioning

It is recommended to include the API version number in the URL:

/api/v1/students/
/api/v2/students/

Error Response Format

Return JSON uniformly on error, using detail or error as the error key:

{
    "detail": "Authentication credentials were not provided."
}

Introduction to Django REST Framework

DRF is a professional REST API framework built on top of Django. Its main features include:

  • Serializers: Convert between model objects and JSON, with built-in data validation.
  • View class hierarchy: From APIViewGenericAPIViewMixinViewSet, progressively reducing boilerplate code.
  • Authentication, Permissions & Throttling: Built-in Session and Token authentication, plus fine-grained permission control and rate limiting.
  • Filtering, Ordering & Pagination: Seamless integration with django-filter.
  • Visual API documentation: Automatically renders an interactive documentation page when the API is accessed in a browser.

Official documentation: https://www.django-rest-framework.org/

Installation and Configuration

Requirements: Python 3.8+, Django 3.2+

pip install djangorestframework

Register it in INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    ...
    'rest_framework',
]

Optional global configuration (placed in settings.py):

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',  # Visual interface for development
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',  # Open by default; tighten in production as needed
    ],
}

Five-Step Quick Start

The following uses a student management API to demonstrate the most concise DRF development path, completing full CRUD in five steps.

### Define the Model In `students/models.py`: ```python from django.db import models class Student(models.Model): name = models.CharField(max_length=100, verbose_name="Name") sex = models.BooleanField(default=True, verbose_name="Gender") age = models.IntegerField(verbose_name="Age") class_null = models.CharField(max_length=5, verbose_name="Class Number") description = models.TextField(max_length=1000, verbose_name="Bio") class Meta: db_table = "tb_student" verbose_name = "Student" verbose_name_plural = verbose_name ``` Run migrations: ```bash python manage.py makemigrations python manage.py migrate ``` ### Create the Serializer In `students/serializers.py`: ```python from rest_framework import serializers from .models import Student class StudentModelSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" ``` ### Write the View In `students/views.py`: ```python from rest_framework.viewsets import ModelViewSet from .models import Student from .serializers import StudentModelSerializer class StudentViewSet(ModelViewSet): queryset = Student.objects.all() serializer_class = StudentModelSerializer ``` `ModelViewSet` automatically provides list, create, retrieve, update, and delete endpoints — no need to write any HTTP methods manually. ### Configure Routing In `students/urls.py`: ```python from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register('students', views.StudentViewSet) urlpatterns = router.urls ``` Include it in the project's main `urls.py`: ```python from django.urls import path, include urlpatterns = [ path('api/', include('students.urls')), ] ``` ### Start and Test ```bash python manage.py runserver ``` Visit `http://127.0.0.1:8000/api/students/`. DRF will render an interactive API documentation page. The automatically generated endpoints are: | Path | Method | Function | | :---------------------------- | :------------- | :------------- | | `/api/students/` | GET | Get list | | `/api/students/` | POST | Create | | `/api/students/{id}/` | GET | Get detail | | `/api/students/{id}/` | PUT / PATCH | Update | | `/api/students/{id}/` | DELETE | Delete |

Serialization and Deserialization Concepts

The most essential conversion processes in API development:

Serialization: Convert server-side model objects to JSON strings and return them to the frontend.

Student object  →  Serializer  →  Python dict  →  JSON string  →  HTTP response

Deserialization: Validate and convert JSON data submitted by the frontend into model objects and save them to the database.

HTTP request  →  JSON string  →  Python dict  →  Serializer validation  →  Model object  →  Database

The serializer (Serializer / ModelSerializer) handles both directions. See Serializers for details.

Last updated on