[英]How to implement complex queries with a REST api?
I'm building an EmberJS app using ember-data. 我正在使用ember-data构建一个EmberJS应用程序。
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? 如果我想得到1993年之前出生的所有在X老师上课的学生的名单,我怎么能用RESTful api做到这一点? In plain SQL it's easy enough, but I'm unsure of the best practice for implementing this into my API. 在简单的SQL中,它很容易,但我不确定在我的API中实现它的最佳实践。
Do I need to build a custom endpoint alongside my basic REST api? 我是否需要与基本的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? 或者有更标准化的方法吗?
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. 例如,这就是JIRA API的工作方式。
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: 您发布POST的过滤器对象如下所示:
{ 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. 我还看到了一个选项,而不是发布,API有一个过滤器,然后使用查询字符串。
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. 特别是如果它可以是一个长时间运行的进程,因为你的POST可以返回一个ID和/或rel
链接到API调用,客户端应该使用它来获取状态更新并获得结果。
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. 那么你就是POST /Students/filter
,它会用/Students/Filter/123
rel回复,你的客户会在/Students/Filter/123
上定期GET
直到得到结果对象。 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. O'Reilly的这本书提供了有关构建ReSTful API的一些很好的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.