Interview question
How do you handle errors and use HTTP status codes correctly in DRF APIs? DRF APIs में errors कैसे handle करें और HTTP status codes सही तरीके से कैसे use करें?
Answer
DRF provides automatic error handling with ValidationError for invalid data and status codes (200, 201, 204, 400, 401, 403, 404, 500) for different scenarios. Custom exception handlers allow consistent error responses across your API.
// Standard HTTP Status Codes
// 200 OK - Successful GET
// 201 Created - Successful POST creating resource
// 204 No Content - Successful DELETE
// 400 Bad Request - Validation error, invalid input
// 401 Unauthorized - Authentication required
// 403 Forbidden - Authenticated but no permission
// 404 Not Found - Resource doesn't exist
// 500 Server Error - Unexpected server error
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
class BookAPIView(APIView):
def get(self, request, pk):
try:
book = Book.objects.get(pk=pk)
serializer = BookSerializer(book)
return Response(serializer.data, status=status.HTTP_200_OK)
except Book.DoesNotExist:
return Response(
{'detail': 'Book not found'},
status=status.HTTP_404_NOT_FOUND
)
def post(self, request):
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk):
try:
book = Book.objects.get(pk=pk)
book.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
except Book.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
// Validation Error Handling
from rest_framework.exceptions import ValidationError
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
def create(self, request, *args, **kwargs):
if 'title' not in request.data:
raise ValidationError({'title': 'This field is required'})
return super().create(request, *args, **kwargs)
// Custom Exception Handler
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
response = exception_handler(exc, context)
if response is not None:
response.data = {
'error': True,
'message': str(exc.detail),
'status_code': response.status_code,
}
return response
# settings.py
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'myapp.exception_handlers.custom_exception_handler',
}
// Consistent Error Response Format
from rest_framework.response import Response
from rest_framework import status
def error_response(message, status_code, errors=None):
data = {
'success': False,
'message': message,
'status_code': status_code,
}
if errors:
data['errors'] = errors
return Response(data, status=status_code)
// Usage
return error_response(
'Validation failed',
status.HTTP_400_BAD_REQUEST,
{'title': ['This field is required']}
)
// Custom Exception Class
from rest_framework.exceptions import APIException
class BookNotFound(APIException):
status_code = status.HTTP_404_NOT_FOUND
default_detail = 'Book not found'
class BookViewSet(viewsets.ModelViewSet):
def get_object(self):
try:
return Book.objects.get(pk=self.kwargs['pk'])
except Book.DoesNotExist:
raise BookNotFound()
// Throttling (Rate Limiting) Errors
from rest_framework.throttling import UserRateThrottle
class BookRateThrottle(UserRateThrottle):
scope = 'books'
# settings.py
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.UserRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'user': '1000/hour',
'books': '100/hour',
},
}
// 429 Too Many Requests - Auto-generated when rate limit exceededDRF automatic error handling provide करता है। सही status codes use करना important है। Custom exception handlers consistent responses देते हैं।
Was this answer clear?