Django Rest Framework is a powerful and flexible toolkit for building Web APIs in Django. It provides a set of tools and libraries for quickly building RESTful APIs and handling common tasks such as serialization, authentication, and request handling.
- Rapid API development
- Built-in serialization and deserialization
- Authentication and permission handling
- Support for various data formats (JSON, XML, etc.)
- Powerful and flexible request handling
- Robust documentation and community support
You can install Django Rest Framework using pip, the Python package manager, by running the following command:
pip install djangorestframework
Example:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def hello_world(request):
return Response({'message': 'Hello, World!'})
Example:
from rest_framework import serializers
class MySerializer(serializers.Serializer):
name = serializers.CharField(max_length=100)
age = serializers.IntegerField()
You can handle GET and POST requests in Django Rest Framework by defining view functions or classes and using the appropriate decorators or mixins.
Example:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET', 'POST'])
def my_view(request):
if request.method == 'GET':
# Handle GET request
return Response(...)
elif request.method == 'POST':
# Handle POST request
return Response(...)
Example:
from django.urls import path
from .views import my_view
urlpatterns = [
path('my-url/', my_view),
]
Model serialization in Django Rest Framework is handled by creating serializers that inherit from the `serializers.ModelSerializer` class.
Example:
from rest_framework import serializers
from .models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'
Model deserialization in Django Rest Framework is handled by validating and saving data using serializers.
Example:
from rest_framework import serializers
from .models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'
# In a view or viewset
serializer = MyModelSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
Authentication in Django Rest Framework can be handled by including authentication classes in the `DEFAULT_AUTHENTICATION_CLASSES` setting.
Example:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework
.authentication.TokenAuthentication',
],
}
Permissions in Django Rest Framework can be handled by including permission classes in the `permission_classes` attribute of views or viewsets.
Example:
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
class MyViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated]
# ...
Pagination in Django Rest Framework is handled by including pagination classes in the `DEFAULT_PAGINATION_CLASS` setting.
Example:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
Filtering in Django Rest Framework is handled by using filter backends and including them in the `filter_backends` attribute of views or viewsets.
Example:
from rest_framework import filters
class MyViewSet(viewsets.ModelViewSet):
filter_backends = [filters.SearchFilter]
search_fields = ['name', 'description']
# ...
Ordering in Django Rest Framework is handled by including ordering fields in the `ordering_fields` attribute of views or viewsets.
Example:
from rest_framework import filters
class MyViewSet(viewsets.ModelViewSet):
filter_backends = [filters.OrderingFilter]
ordering_fields = ['name', 'date']
# ...
Nested resources in Django Rest Framework can be handled by using routers and nested serializers to define the relationships between models.
Example:
from rest_framework import serializers, viewsets, routers
class ChildSerializer(serializers.ModelSerializer):
class Meta:
model = Child
fields = '__all__'
class ParentSerializer(serializers.ModelSerializer):
children = ChildSerializer(many=True)
class Meta:
model = Parent
fields = '__all__'
class ParentViewSet(viewsets.ModelViewSet):
queryset = Parent.objects.all()
serializer_class = ParentSerializer
router = routers.SimpleRouter()
router.register(r'parents', ParentViewSet)
Token-based authentication in Django Rest Framework can be handled by using the `TokenAuthentication` class and including it in the `DEFAULT_AUTHENTICATION_CLASSES` setting.
Example:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
JWT-based authentication in Django Rest Framework can be handled by using the `JWTAuthentication` class and including it in the `DEFAULT_AUTHENTICATION_CLASSES` setting.
Example:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
File uploads in Django Rest Framework can be handled by using the `FileField` or `ImageField` serializer fields.
Example:
from rest_framework import serializers
class MySerializer(serializers.Serializer):
file = serializers.FileField()
# In a view or viewset
serializer = MySerializer(data=request.data)
if serializer.is_valid():
file = serializer.validated_data['file']
# Handle the uploaded file
Example:
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
}
Example:
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day',
},
}