Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs in Django. It extends Django's capabilities, making it easier and faster to create robust and scalable RESTful services. DRF provides a rich set of features that abstract away much of the complexity involved in API development, allowing developers to focus on business logic.
Key features and concepts of DRF include:
- Serializers: These are central to DRF. They allow complex data types, such as Django models, to be converted to native Python datatypes that can then be easily rendered into JSON, XML, or other content types. Serializers also provide deserialization, enabling incoming data to be validated and converted back into complex types, saving them to a database. `ModelSerializer` is a powerful shortcut for creating serializers directly from Django models.
- Request & Response Objects: DRF introduces `Request` and `Response` objects that extend Django's standard `HttpRequest` and `HttpResponse` classes, providing more flexible request parsing and content negotiation.
- Class-based Views (CBVs) & ViewSets: DRF builds upon Django's CBVs, providing generic API views that handle common patterns (e.g., list, retrieve, create, update, delete). `ViewSets` take this a step further by combining the logic for a set of related views into a single class, significantly reducing boilerplate code for common CRUD operations.
- Routers: Used with `ViewSets`, routers automatically generate URL configurations, making it simple to map URLs to actions within a `ViewSet`.
- Authentication & Permissions: DRF offers flexible authentication schemes (e.g., Token, Session, Basic) and a robust permission system to control access to API endpoints, ensuring only authorized users can perform certain actions.
- Throttling: Allows control over the rate of requests that clients can make to the API, preventing abuse.
- Pagination: Provides various strategies (e.g., PageNumberPagination, LimitOffsetPagination) to paginate large result sets, improving API performance and usability.
- Renderer Negotiation: DRF supports multiple renderers (e.g., JSON, HTML, browsable API) allowing clients to request data in their preferred format.
- Built-in Browsable API: A significant feature that provides a user-friendly HTML interface for interacting with API endpoints directly in the browser, making development, testing, and debugging much easier.
DRF integrates seamlessly with Django, leveraging its ORM, admin panel, and other features. It is widely used for building backend services for single-page applications (SPAs), mobile applications, and other decoupled systems.
Example Code
First, install Django REST Framework:
pip install djangorestframework
1. Add 'rest_framework' to your INSTALLED_APPS in settings.py
myproject/settings.py
INSTALLED_APPS = [
... other apps
'rest_framework',
'myapp', Assuming your Django app is named 'myapp'
]
2. Define a simple Django model in myapp/models.py
myapp/models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
in_stock = models.BooleanField(default=True)
def __str__(self):
return self.name
Run migrations after defining the model:
python manage.py makemigrations
python manage.py migrate
3. Create a Serializer for the Product model in myapp/serializers.py
myapp/serializers.py
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'name', 'description', 'price', 'in_stock']
Alternatively, you can use fields = '__all__' to include all model fields
4. Create a ViewSet in myapp/views.py
myapp/views.py
from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
This ViewSet will automatically provide list, create, retrieve, update,
partial_update, and destroy actions for the Product model.
queryset = Product.objects.all()
serializer_class = ProductSerializer
5. Configure URLs using a DRF Router in myapp/urls.py
myapp/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ProductViewSet
Create a router and register our ViewSets with it.
router = DefaultRouter()
router.register(r'products', ProductViewSet, basename='product')
The API URLs are now determined automatically by the router.
urlpatterns = [
path('', include(router.urls)),
]
6. Include your app's URLs in the project's main urls.py
myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('myapp.urls')), All API endpoints will be under /api/
]
After running 'python manage.py runserver', you can access the API:
- http://127.0.0.1:8000/api/products/ (GET for list, POST for create)
- http://127.0.0.1:8000/api/products/1/ (GET for retrieve, PUT for update, PATCH for partial update, DELETE for destroy)
The browsable API will also be available directly in your web browser.








django-rest-framework