Hi I am trying to validate incoming query params for a basic GET request. The amount of query params will be large so I need to think of a nice way to validate each of the parameters. I am using DRF and in this case I do not use a django model. It is starting to get weird and I am sure others have solved this problem so if some kind soul can point me to a better solution please do. I am certain this problem can be handled in a Django way.
What I have so far is the code below and it is working but perhaps someone has done something similar. In this example I have a GET endpoint that can accept params “foo”, “bar”, “baz”. They also happen to be required. I also do not use these params to query a database, rather I use them to interact with another third party API.
class SimpleView(views.APIView):
required_param_fields = ("foo", "bar", "baz")
def get(self, request: Request, *args, **kwargs) -> Response:
self.validate_param_fields(request)
# do some stuff and then return response
def validate_param_fields(self, request: Request):
missing_params = [
param
for param in self.required_param_fields
if param not in request.query_params
]
if missing_params:
return Response(
{
"error": f"Missing required query params: {', '.join(missing_params)}"
},
status=status.HTTP_400_BAD_REQUEST,
)
for param in self.required_param_fields:
validator = getattr(self, f"validate_{param}")
validator(request.query_params[param])
def validate_foo(self, value):
# validation logic here, raise ValidationError is something is wrong
def validate_bar(self, value):
# validation logic here, raise ValidationError is something is wrong
def validate_baz(self, value):
# validation logic here, raise ValidationError is something is wrong