3

Django REST Framework API ignores any unknown parameters. This has led to several issues. For example, when a model filter was missing, a client received all records rather than the single one they were expecting. How can I force DRF to return 400 Bad Request whenever an API call includes an unknown parameter?

(An unknown parameter is one which is not in [SerializerClass].Meta.fields if this is a list, or not in [SerializerClass].Meta.model fields if it is __all__.)

1 Answer 1

1

One of the easy and basic solution may be this,

# serializer.py

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = '__all__'


# views.py
def foo_view(request):
    serializer = FooSerializer(data=request.data)
    if set(request.data.keys()) - set(serializer.fields.keys()):
        raise Exception

Note: Assuming request.data is a dict object


Disclaimer: I'm not sure about the cases while we use source argument in serializer

Sign up to request clarification or add additional context in comments.

2 Comments

That looks like an expensive operation for every single API endpoint, but yeah, it should work.
Yeah, It's expensive. I wouldn't recommend this solution since it's not covered in many cases.

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.