Using decorators to validate input data on django rest viewsets working example
Recently,
I stumbled upon a Real Python Podcast episode 192
where they were talking about decorators.
I always liked more control over stuff and used decorators rarely,
but this episode made me look at them differently.
I wanted a clear picture of fields somewhere near with methods,
so that when somebody asked me what to send to the endpoint,
I could just point them to the method.
So why I decided to describe parameters with tuple of a type and required string?
Because I wanted to validate types for not only the required fields
but also for the optional ones.
Let’s see how this decorator is implemented.
At first, we define a decorator function that takes expected_params as a parameter.
We loop over expected_params and check if the parameter is present in the request,
if it is, we check if it has the expected type, if not, we return a response with an error message.
If the parameter is not present in the request, but it is required,
we return a response with an error message.
After that,
we loop over all the parameters in the request
and add them to the parsed_params even if they are not present in expected_params.
This way, we do not lose any data that was sent to the endpoint.
Finally, we pass the parsed_params to the original view function.
So if I send for example “type” as an integer, this is what the response looks like