Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return 422 status code in ModelViewSet

For interoperability with EmberData it seems I need to reply with 422 (Unprocessable Entity) instead of 400 (Bad Request) whenever validation errors occur. I have two questions:

  • How can I specify the response status code when using a ModelViewSet?
  • Why is the 422 not listed in the list of possible return codes?

And bonus:

  • Why is EmberData expecting 422? This is not part of the JSONAPi spec, as far as I can see.
like image 658
blueFast Avatar asked Jan 05 '16 10:01

blueFast


People also ask

How do you increase validation error in DRF?

The easiest way to change the error style through all the view in your application is to always use serializer. is_valid(raise_exception=True) , and then implement a custom exception handler that defines how the error response is created.

What is status code in Django?

The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.

How do I increase error in Django REST framework?

The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above. By default this exception results in a response with the HTTP status code "400 Bad Request".


1 Answers

422 is part of the WebDAV DRF which error codes aren't in DRF. This doesn't stop you to use it. They are just a human readable version of the number itself.

One option would be to override rest_framework.exceptions.ValidationError.status_code and set it to 422.

Edit - Changing the default error code:

# At the top of a views.py file, by the ends of import add:
from rest_framework.exceptions import ValidationError
ValidationError.status_code = 422
like image 90
Linovia Avatar answered Oct 26 '22 00:10

Linovia