Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API call to filter resource

Tags:

rest

I'm building a REST API, i have a resource say Movies.

1) POST : movies/

2). GET : movies/{movie_id}

call 1) creates a post.

call 2) when movie_id supplied, it returns specific movie's details, otherwise returns all movies.

Now i have to filter out the movies based on movie attributes like popular, rating etc

My doubts is :

Should there be separate URL for filtering the movies something like

GET: movies/filter/

This call will have GET parameters like popuplar, rating etc And based on those parameters movies can be filtered out.

Not sure what is the standard way to handle this case, please share your thoughts on this,

like image 582
navyad Avatar asked Mar 17 '23 15:03

navyad


1 Answers

I have seen two basic approaches in this case. One is the one you suggested, which is to use a separate URL movies/filter/ and filter them out. The classic example is cars/colors/red/maker/porsche.

The other is to use query params, which is, when possible, my preferred approach.

GET /movies?year=2010&actor=Carrey

Variants can include multiples of each (URL encoded appropriately, of course)

GET /movies?year=[2010,2011]&actor=Carrey

I like this approach because it clearly says, "get a list of movies, but limit by these properties".

Two variants I have seen and sometimes used, when necessary, are attempts to separate out actual search terms in query params from other submissions. These generally come up when you need to use query params for things other than search.

The first is a hybrid, that says, "only search, and treat query params as search terms, in a particular sub path. So something like:

GET /movies/filter?year=2010&actor=Carrey

Or if you prefer

GET /movies/search?year=2010&actor=Carrey

A variant is to flag any search terms

GET /movies?search.year=2010&search.actor=Carrey

Finally, a variant I do not like much is to have a /search path

GET /search/movies?year=2010&actor=Carrey

It sometimes is necessary, but I do not like it because search is an action, not a resource, and thus is not very RESTful of a path. But others may like it.

like image 151
deitch Avatar answered Mar 20 '23 03:03

deitch