how to throw user friendly error message if validation fails for query params in django

I am writing an API in Django, and the URL is something like foo.com/api/places?city_id=123 So, here my query_param is city_id, and my API should accept integers only, if query_param is sent as city_id="xyz", then my API needs to send some user-friendly message instead of 500. May I know how to achieve that in Django, please?


Solution 1:

You can do this in two ways.

Method 1

You can send response with error code like this

if not request.query_params.get('city_id').isdigit():
    return Response({'message': 'Your message here'}, status=your_error_code_here)

Method 2

You can make a serializer for query param validation.

class ParamValidationSerializer(serializers.Serializer):
    city_id = serializers.IntegerField(error_messages={'invalid': 'Your message here'})