I'm developing a REST api with Flask. One of my endpoints should support filtering and sorting. lets say i have these fields: category, color, severity.
Lets say i want to get all the items that category is 'a'or 'b' and the color is black and sort it by the severiy asc and color desc.
for the sorting i saw that prepending '+' or '-' is a way to set the order.
1.What is the best practice to decode the filter expression? assuming i want to use a query string method for passing parameters in get request (or the best option is to use a json-body parameters for this need)
2. What is the best way to parse it in flask framework?
my_ip/items?sort=+severity&sort=-color&filter=???
This article give some good suggestions on how to approach it: Pagination, Filtering, and Sorting
For example:
- Only sort keys specified:
sort=key1,key2,key3
key1
is the first key,key2
is the second key, etc.- Sort directions are defaulted by the server
- Some sort directions specified:
sort=key1:asc,key2,key3
- Any sort key without a corresponding direction is defaulted
key1
is the first key (ascending order),key2
is the second key (direction defaulted by the server), etc.- Equal number of sort keys and directions specified:
sort=key1:asc,key2:desc,key3:asc
- Each key is paired with the corresponding direction
key1
is the first key (ascending order),key2
is the second key (descending order), etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With