How to implement complex queries with a REST api?

Anonymous picture Anonymous · May 28, 2013 · Viewed 10.8k times · Source

I'm building an EmberJS app using ember-data.

Some of the functionality in my app requires quite complex queries.

As an example, let's say I have three entities - students, teachers and classes. If I wanted to get a list of all the students born before 1993 that are taking classes taught by teacher X, how can I do that with a RESTful api? In plain SQL it's easy enough, but I'm unsure of the best practice for implementing this into my API.

Do I need to build a custom endpoint alongside my basic REST api?

So I'd still have:

GET /students (which returns all the students)
GET /students/{id} (which returns a specific student)
etc

But then implement the following for my 'custom' query:

GET /students/custom/born_before/{date}/taught_by/{teacher_id}

Or is there a more standardized way of doing this?

Answer

Pablo Lozano picture Pablo Lozano · May 28, 2013

You can transform your

GET /students/custom/born_before/{date}/taught_by/{teacher_id}

into

GET /students/?born_before={date}&taught_by={teacher_id}

which is just a "query by example" option: you can populate a model instance with the provided fields and make a query using them. The less fields, the broader is the search and more results to show.

This is the way JIRA's API works, for example.