Returning bad request (400) errors from list endpoints

1,502 views
Skip to first unread message

Rowan Seymour

unread,
Jan 27, 2016, 9:45:39 AM1/27/16
to Django REST framework
Hi all

We have some list endpoints where certain querystring parameter combinations should result in an error response. Currently I'm throwing a ValidationError from the get_queryset method but that renders as just a JSON list without the usual {"detail": ... }. Doesn't seem like it even should be a validation error, but not seeing any examples of how people usually handle this.

Thanks

-Rowan


Chris Foresman

unread,
Jan 27, 2016, 3:53:44 PM1/27/16
to Django REST framework
ValidationError will only get properly fed into the "details" key when raised inside a validator/serializer. If you want to validate query strings, you could create a serializer with all the validation you want and then pass it request.query_params.

class QuerySerializer(Serializer):
   field1
=  serializers.IntergerField()
   
...

params = QuerySerializer(request.query_params)
params.is_valid(raise_exception=True)



Rowan Seymour

unread,
Jan 28, 2016, 4:49:45 AM1/28/16
to django-res...@googlegroups.com
Hi Chris

Thanks for this suggestion tho I think I've now figured out a simpler way to do this - just define my own exception class and throw it from get_queryset, e.g.

class InvalidQueryError(APIException):
    status_code = status.HTTP_400_BAD_REQUEST

The default exception_handler then renders it like other exception types with {"detail":...}

-Rowan

--
You received this message because you are subscribed to a topic in the Google Groups "Django REST framework" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-rest-framework/IPfh25aZLIw/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Rowan Seymour | +260 964153686 | @rowanseymour
Reply all
Reply to author
Forward
0 new messages