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
/getStudentsor/deleteOrderare 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 # DeleteHTTP Method Semantics
| Method | Operation | Notes |
|---|---|---|
| GET | Query | Idempotent; does not modify state |
| POST | Create | Non-idempotent; returns 201 |
| PUT | Full update | Idempotent; full resource required |
| PATCH | Partial update | Idempotent; submit changed fields only |
| DELETE | Delete | Idempotent; returns 204 No Content |
Common Status Codes
| Status Code | Meaning |
|---|---|
| 200 | OK — Request succeeded |
| 201 | Created — Resource created successfully |
| 204 | No Content — Delete succeeded, no body |
| 400 | Bad Request — Invalid request parameters |
| 401 | Unauthorized — Not authenticated |
| 403 | Forbidden — Authenticated but no permission |
| 404 | Not Found — Resource does not exist |
| 500 | Internal 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
APIView→GenericAPIView→Mixin→ViewSet, 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 djangorestframeworkRegister 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.
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 responseDeserialization: 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 → DatabaseThe serializer (Serializer / ModelSerializer) handles both directions. See Serializers for details.