How best to design a REST API with multiple filter

2019-04-07 12:21发布

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.

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

Option 1

Provide numerous URLs such as

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

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.

Option 2

Only provide APIs for the major options like:

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

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

Option 3

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
}

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.

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?

标签: mysql api rest
2条回答
Viruses.
2楼-- · 2019-04-07 12:53
GET example.com/courses?college=<collegecode>&instructor=<instructorcode>
查看更多
贼婆χ
3楼-- · 2019-04-07 13:00

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.

查看更多
登录 后发表回答