Auto-documenting REST API filtering with every possible query params
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state.
— Roy Fielding, REST APIs must be hypertext driven
Django REST Framework has built-in support for documenting and often the API documentation is generated by default. It is mostly well-documented payloads sending and getting response type data.
But it doesn’t always document your query_params
by default, in this situation, when the frontend developer or someone who going to user API, they gets confused which query_params
to send for which purpose, how will the query_params
looks like.
in this article, i am gonna demonstrate how you can implement well-documented filtering with various query_params
even you can use your own custom query_params documented.
What I build here now?
Let’s say I have a table named `BookingInfo`, i want to show the user his all upcoming booking, new booking, history, and history of last 1 years only.
models.py
BookingInfo models
This is how we do filter in DRF
If we do filter the above way, the API will not be well-documented, and other developer may be confused about what query_params your API expecting
In this situation, we take help of django-filter
library and it comes with lots of features, so you have to learn it very well to get the best benefit. the library plays very well with django-rest-framework.
install it using pip install django-filter
and it in your INSTALLED_APP
array
So to make the more interactive in the browser, we do usually do it this way.
If we do that way, it can’t solve our above problem like upcomming booking
new booking etc. even though it will give you facility to play interactively on browser
then what how can we filter to make our above business case?
Here you go for final views.py
If we implement it that way, we can play with our API interactively on the browser without any third-party tools.
Note: I apologize if do any mistakes here, i have written the article for future reference so that i can remind it again how i did it before. it’s completely personal