How to implement complex queries with a REST api?

我与影子孤独终老i 提交于 2020-01-01 08:03:10

问题


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?


回答1:


One option is to have a search endpoint on your students that you can post to.

So you might have:

POST /students/filter

The filter object that you'd POST would look something like:

{ BornBefore:1993, TaughtBy:123 }

I've also seen an option where instead of posting that, the API had a filter, and then used a query string.

I prefer the first one myself. Especially if it can be a long running process, because your POST could return an ID and/or a rel link to the API call the client should use to get status updates and get the results.

So then you'd POST /Students/filter and it would respond back with rel of /Students/Filter/123 and your client would do periodic GET's on /Students/Filter/123 until it got the result object. Of course, for simple, short queries, you could just instantly return the result. But if it was going to take more than a second or two you could go this route.

This book by O'Reilly has some good information on structuring ReSTful APIs.




回答2:


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.



来源:https://stackoverflow.com/questions/16795999/how-to-implement-complex-queries-with-a-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!