問題描述
作為一個個人編程項目,我正在努力抓取我大學的課程目錄并將數據作為 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?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!