如何最好地设计具有多个过滤器的 REST API? [英] How best to design a REST API with multiple filters?

查看:39
本文介绍了如何最好地设计具有多个过滤器的 REST API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个个人编程项目,我正在努力抓取我大学的课程目录并将数据作为 REST API 提供.我已成功抓取所有数据并将其存储在数据库中,现在正在开发 API.

As a personal programming project, I am working on scraping my University's course catalog and providing the data as a REST API. I have successfully scraped all the data and stored it in a database, and am now working on the API.

可以根据许多标准过滤课程:讲师、大学、学分、时间、天数等.

The courses can be filtered on the basis of many criteria: instructor, college, credits, time, day etc.

在这种情况下提供 API 的最佳方式是什么?

What is the best way to provide an API in this situation?

选项 1

提供多个 URL,例如

Provide numerous URLs such as

example.com/api/byinstructor/<instructorcode>
example.come/api/bycollege/<collegecode>
example.com/api/bycollegeandinstructor/<collegecode>/<instructorcode>
...and so on

我需要所有排列的 URL.这对于我和 API 消费者来说似乎非常麻烦,而且非常不干.

I would need to have a URL for all permutations. This seems very cumbersome, both for me and the API consumers, and very un-DRY.

选项 2

仅提供主要选项的 API,例如:

Only provide APIs for the major options like:

example.com/api/byinstructor/<instructorcode>
example.come/api/bycollege/<collegecode>

如果消费者想要bycollegeandinstructor,他会在自己的一端进行过滤.

And if the consumer wants bycollegeandinstructor, he does the filtering on his end.

选项 3

用户向我传递一个 JSON 字符串,我用它来获取过滤条件

The user passes a JSON string to me, and I use that to get the filtering criteria

example.com/api/getcourses/<jsonstring>

jsonstring = 
{ 
  instructor:<instructorcode>,
  college:<collegecode>,
  ...and so on
}

我想除了 Json 字符串,我还可以需要一个 POST 数组,但这对消费者来说似乎不直观,因为他正在 GET 数据.

I suppose instead of the Json string, I could also require a POST array, but that seems un-inituitive for the consumer since he is GETing data.

或者还有其他我不知道的方法吗?如果第三个选项是最佳选项,您能否提供一个简短的摘要,以便根据可能具有可变数量值的 JSOn 字符串准备 SQL 查询?

Or is there another way of doing this I am not aware of? If it is the third option that is the best option, could you provide a short summary best to prepare a SQL query on the basis of a JSOn string that may have variable number of values?

推荐答案

为了扩展 J.F. 的答案,听起来您有一个资源,即课程集,位于 URI:

To expand on the answer from J.F., it sounds like you have one resource, the set of courses, which would be at the URI:

/courses

过滤该资源通常是使用查询参数来过滤单个资源来完成的,例如:

Filtering that resource is usually accomplished using query parameters to filter that single resource, e.g:

/courses?college=123&instructor=321

通过这样做,您可以避免所有可能的排列造成资源激增的问题.

By doing this, you avoid the issue with all possible permutations creating a proliferation of resources.

从根本上说:只有一种资源,可以根据需要对其进行过滤.

Fundamentally: There's one resource, which can be filtered as necessary.

这篇关于如何最好地设计具有多个过滤器的 REST API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆