Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST url for resource collection, which filters resource by attribute not equal to a given value

Tags:

rest

url

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 ?

like image 980
Karthik Chandraraj Avatar asked Feb 28 '13 04:02

Karthik Chandraraj


People also ask

Which URL pattern is recommended when working with one resources and a collection of resources?

The recommended convention for URLs is to use alternate collection / resource path segments, relative to the API entry point.

How do I pass a filter in REST API?

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?

How do I pass multiple query parameters in REST URL?

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.

What are REST type URLs?

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.


2 Answers

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.

like image 184
randomhuman Avatar answered Sep 22 '22 15:09

randomhuman


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
like image 24
Jeremy Richardson Avatar answered Sep 22 '22 15:09

Jeremy Richardson