How to design REST url for resource collection, which filters resource by attribute not equal to a given value?
For example, to get the students in 8th grade, we use
GET /students?grade=8
How to do the same, if we need to get the students not in 8th grade? And how to design for less than (<
) , greater than (>
) etc ?
The recommended convention for URLs is to use alternate collection / resource path segments, relative to the API entry point.
URL parameters is the easiest way to add basic filtering to REST APIs. If you have an /items endpoint which are items for sale, you can filter via the property name such as GET /items?
Query parameters are passed after the URL string by appending a question mark followed by the parameter name , then equal to (“=”) sign and then the parameter value. Multiple parameters are separated by “&” symbol.
Although URLs containing parameters within the query string do themselves conform to REST constraints, the term “REST-style URL” is often used to signify a URL that contains its parameters within the URL file path, rather than the query string.
What I am thinking of doing is including the operator as part of the argument, delimited from the value. I would also define non-symbolic operators to avoid the need for ugly URL-encoding or confusion with the equals sign after the parameter name. For your example, this would be something like this for students not in grade 8:
GET /students?grade=neq|8
Students in grades > 8 would be:
GET /students?grade=gt|8
Students between grades 8 and 10 (inclusive):
GET /students?grade=gte|8,lte|10
This approach can be extended to other filterable fields without the need to add additional parameters to modify the way each field is filtered.
Stripe has one of the most respected APIs.
They use a separate parameter for each operator separated with a dot.
For example, to search on created date:
/charges?created.gt=
/charges?created.gte=
/charges?created.lt=
/charges?created.lte=
In your case you could do something like:
/students?grade.gt=8&grade.lt=8
Or even add another operator for not:
/students?grade.not=8
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