2

I need my API to serve explicit error codes for UI applications, that will look similar to i.e. GitHub API:

HTTP/1.1 422 Unprocessable Entity
Content-Length: 149

{
  "message": "Validation Failed",
  "errors": [
    {
      "resource": "Issue",
      "field": "title",
      "code": "missing_field"
    }
  ]
}

What is the best way to implement it in DRF? Is there any package to handle this?

1 Answer 1

2

this is how i do it, if it suits your needs:

from rest_framework.response import Response
from rest_framework import status

if serializer.is_valid():
            ..... # Do my logic here
            return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
return Response({
    'status' : 'Bad request',
    'message': 'Account could not be created with received data.',
    'errors' : serializer.errors # for example
}, status=status.HTTP_400_BAD_REQUEST)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.