2017-12-27 394 views
-1

我有關於如何組織API路由結構的問題。閱讀了許多關於構建RESTful API的書籍,但無法找到答案。每本書都講述簡單的CRUD操作,並在一個層次上嵌套資源。 Like /users/users/1/posts。沒有問題。REST風格的API:如何組織嵌套的資源

例:

但讓我們來看看更加困難現實生活中的例子:

GET /cars // List of cars 
GET /cars/{car_id} // Get single car 
POST /cars // Add new car 
PUT /cars/{car_id} // Update existing car 
DELETE /cars/{car_id} // Delete car by specified ID 

cars數據庫表結構將

Table "cars" 
    - id 
    - uuid 
    - make 
    - model 
    - year 
    - created_at 
    - updated_at 
    - deleted_at 

沒有問題,到目前爲止,但那麼我需要添加嵌套的資源。 所有使用指定車輛進行的修理。

GET /cars/{car_id}/repairs // List of repairs that were done with car 
GET /cars/{car_id}/repairs/{repair_id} // Get single repair 
POST /cars/{car_id}/repairs // Add new repair for specified car 
PUT /cars/{car_id}/repairs/{repair_id} // Update existing repair for specified car 
DELETE /cars/{car_id}/repairs/{repair_id} // Delete repair by specified ID 

結構,數據庫表將

Table "car_repairs" 
    - id 
    - uuid 
    - car_id (foreign key to cars) 
    - title 
    - description 
    - repair_started_at 
    - repair_ended_at 
    - created_at 
    - updated_at 
    - deleted_at 

到目前爲止,沒有任何問題。就像所有的書一樣。一個/users路由和嵌套路由/users/1/posts。但是當我需要添加另一層嵌套時,這裏就開始出現問題。

我需要爲所發現的,當車子在維修所有的缺陷CRUD路線

GET /cars/{car_id}/repairs/{repair_id}/defects // List of all defects that were found for specified repair for speicified car 
GET /cars/{car_id}/repairs/{repair_id}/defects/{defect_id} // Get single defect 
POST /cars/{car_id}/repairs/{repair_id}/defects // Add new defect 
PUT /cars/{car_id}/repairs/{repair_id}/defects/{defect_id} // Update existing defect 
DELETE /cars/{car_id}/repairs/{repair_id}/defects/{defect_id} // Delete existing defect 

表的結構將是:

Table "car_repair_defects" 
    - id 
    - uud 
    - car_id 
    - repair_id 
    - name 
    - description 
    - created_at 
    - updated_at 
    - deleted_at 

QUESTSIONS:

在這裏做什麼,是否正常練習的水平爲.../defects

考慮的情況,如果我需要添加到另一個嵌套,第4級,在例子中,使用的所有部件發現缺陷

什麼最佳實踐時的RESTful API的嵌套資源

可以說,這可以在沒有嵌套的情況下完成。示例/cars/repairs/defects/parts但是,那麼對於嵌套資源的RESTful示例呢?那麼什麼是最大的嵌套資源級別0,1,2,3?例如,您需要創建字典路線/defects,其中只列出了所有可能的汽車缺陷。所以會有名稱衝突。

此外,如果沒有嵌套,你將如何過濾項目,你會過濾嵌套?

defects?car_id=1&repair_id=2&defect_id=3

喜歡這個?這看起來很醜。

請有人指向一本書或文章,或者給出有關最大嵌套級別和以前列出的問題的答案。 謝謝。

+0

如果我的問題得到了投票,請評論爲什麼? – user991

回答

0

這裏的關鍵點:REST不護理你用什麼拼寫標識符。

也就是說,REST認爲每個這些URI都是同樣好的。

/cars/{car_id}/repairs/{repair_id}/defects 
/08617423-cc74-4967-9a67-49e4171f01b7 

至於客戶而言,所述標識符是不透明的;將信息編碼到URI中是由服務器自行決定完成的,以供它自己使用。

除此之外,標識符拼寫約定是有效的代碼風格約定;使用與當地風格一致的拼寫。

從客戶端的角度來看,標識符而不是描述資源的語義;這是超媒體表示的工作。