Reputation: 1339
I am creating a WebAPI where a get method needs to accept, among others, parameters for Paging, Sorting and Filtering. Since sorting and filtering can be lists of key - value pairs and filtering has operators as well (gt, lt, equals, contains...), and we know that sending objects in the body is not recommended for get methods, how is this scenario handled for APIs?
Upvotes: 2
Views: 4025
Reputation: 4461
Simply pass them as Query String
.
It's best practice for behaviours like paging, sorting and filtering because it can be bookmarked by users and reused.
You can see your answer in many famous websites, for example in SO look at the filter param below:
https://stackoverflow.com/questions?sort=Newest&filters=NoAnswers,NoAcceptedAnswer,Bounty
@AdrianoRepetti has a lot of helpfull complementarities in comments that I added to answer with permission:
There are a few different approaches:
For example for Sorting:
http://www.example.com/api/orders?sort=field1,field2
or http://www.example.com/api/order?sort=field1&sort=field2
Now let's make it better: you will also need the sort order, it could be nicely expressed as:
http://www.example.com/api/orders?sort=created_at+asc,delivered_at+desc.
Filters could possibly more more complicate. A simple scenario:
http://www.example.com/api/order?filter=status%3dpending (note %3d to escape =, the API will see status=pending
for the filter parameter). Do you need more ANDed filters? just concatenate or repeat them (like for sorting). Instead of %3d you could have other characters if you support other operators. If things get more complicate then you'll need your own mini language to express your filters (remember to encode the URI components client side!!!)
Sooner or later you will need to make your query more complicate and then too long to fit in the query string (for example when you will need an IN
operator). It's perfectly acceptable (and widely used) to have POST
instead of GET
for such queries (see OpenData
, for example). You could come up with some more complicate scheme for your filters but a simple JSON
object (or hem hem GraphQL
) is often a better and easier choice
Upvotes: 3