2016-03-02 73 views
2

我有兩個資源,buildingsrooms如何構建相關的RESTful URL

邏輯API網址是:

/api/buildings   -> all buildings 
/api/buildings/1   -> building #1 
/api/buildings/1/rooms -> rooms from building #1 
/api/buildings/1/rooms/5 -> room #5 from building #1 
/api/rooms    -> all rooms, any building 
/api/rooms/5    -> room #5/(?) Is this necessary? 

你如何構建更深層次的節點?好像有3種方式來獲得相同的數據時,我們引入了第三層

#1) /api/buildings/1/rooms/5/chairs/3 

#2) /api/rooms/5/chairs/3 

#3) /api/chairs/3 

好像有不同的方式來獲得的椅子#3,這意味着重複的工作。

+0

是否每個椅子都有唯一的ID--無論它在哪個建築物中? – morsor

回答

2

/api/buildings/1/rooms/5/chairs/3/api/rooms/5/chairs/3沒有任何意義。 api/.../chairs資源應該鏈接到/api/chairs/3,並且/api/buildings/1/rooms資源應該包含鏈接到/api/rooms/5/

+0

謝謝!當你說'應該鏈接到'時,你的意思是什麼? –

+0

來自'GET/api/rooms /'的響應應該包含到'/ api/rooms/5 /'的超文本鏈接,例如'['api/rooms/5 /',...]'用於JSON或' XML中的'。 –

1

我會建議儘可能避免嵌套。

/api/buildings 
/api/buildings/1 
/api/buildings/1/rooms 
    # GET returns all rooms in building 1. Each room has a "self" link 
    # which points to /rooms/{id}, and a "building" link which points to 
    # /api/buildings/1 
    # POST adds a room to the building and the rooms collection 
    # DELETE deletes the room from the building and the rooms collection 
    # This is reasonable because a room's scope is the building it belongs to 

/api/rooms 
    # No POST supported 
    # DELETE deletes the room from its building and this collection 
/api/rooms/5 
/api/rooms/5/chairs 
    # All chairs currently in this room 
    # POST moves an existing chair to this room 
    # DELETE removes an existing chair from the room, but not /chairs 

/api/chairs 
    # POST creates a chair 
    # DELETE deletes the chair and removes it from the room it belongs to 

一個可能的問題是,在POST和/buildings/1/rooms作用/rooms/5/chairs不同。這是否可接受是由您決定的。替代方案是:

  • 允許/強制用戶創建通過POST /間,然後作爲一個單獨的事務將其分配到通過POST建築/建築/ 5 /間
  • 房間使建設機房屬於到/
  • 使用查詢參數,例如POST /rooms?building=12 { body }時在其構建的必需部分。這種結構是非典型的,不推薦。