
Validation of requests in Django refers to the process of checking the data submitted through incoming requests to your web application or API, ensuring that it meets the required specifications and is free from errors, inconsistencies, or malicious input.
Django Rest Framework provides various ways to validation of requests coming into your API. Some of the most common methods are:
Serializers
Serializers are used to convert complex data types, such as models, into Python data types that can be easily rendered into JSON or other content types. They also provide built-in validation, such as field-level validation, serializer-levelValidation, and object-levelValidation.
For example, in the serializers.py
file, you can define a serializer for a model, and then use it to validate incoming data in your API view:
from rest_framework import serializers
from myapp.models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'name', 'description', 'created_at')
def validate_name(self, value):
if len(value) < 3:
raise serializers.ValidationError("Name must be at least 3 characters long.")
return value
Validators in Validation
DRF also provides a set of built-in validators that can be used to validate individual fields in a request. These validators are available in the rest_framework.validators
module.
from rest_framework import serializers, validators
class MySerializer(serializers.Serializer):
name = serializers.CharField(max_length=100, validators=[validators.MinLengthValidator(3)])
email = serializers.EmailField(validators=[validators.EmailValidator()])
Request object
In DRF, the incoming request object is also available to the view function. You can access request data and perform your own customValidation:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['POST'])
def my_view(request):
name = request.data.get('name')
if len(name) < 3:
return Response({'error': 'Name must be at least 3 characters long.'}, status=400)
# Process the valid data
These are some of the most common ways to validate requests in Django Rest Framework. By using these validation techniques, you can ensure that the data sent to your API is valid and fits your application’s requirements.
GitHub Link :