Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass filter and sort parameters in query string HTTP request and parse with Flask

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=???

like image 961
sborpo Avatar asked Oct 16 '22 19:10

sborpo


1 Answers

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.
like image 50
Andrii Litvinov Avatar answered Oct 21 '22 01:10

Andrii Litvinov