【问题标题】:How to structure related RESTful URLs如何构建相关的 RESTful URL
【发布时间】:2016-03-02 03:09:15
【问题描述】:

我有两个资源,buildingsrooms

逻辑 API URL 是:

/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 层时,似乎有 3 种方法可以获取相同的数据

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

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

#3) /api/chairs/3

似乎有不同的方法可以得到 3 号椅子,这意味着重复工作。

【问题讨论】:

  • 每把椅子是否都有唯一的 ID - 无论它在哪栋建筑中?

标签: api rest restful-architecture restful-url


【解决方案1】:

/api/buildings/1/rooms/5/chairs/3/api/rooms/5/chairs/3 没有意义。 api/.../chairs 资源应包含指向 /api/chairs/3 的链接,/api/buildings/1/rooms 资源应包含指向 /api/rooms/5/ 的链接。

【讨论】:

  • 谢谢!你说should have a link to是什么意思?
  • 来自GET /api/rooms/ 的响应应包含指向/api/rooms/5/ 的超文本链接,例如,['api/rooms/5/', ...] 用于 JSON 或 <rooms><room href='api/rooms/5/' /></rooms> 用于 XML。
【解决方案2】:

我建议尽可能避免嵌套。

/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 /rooms 创建房间,然后作为单独的事务通过 POST /buildings/5/rooms 将其分配给建筑物
  • 在发布到 /rooms 时,将建筑物设为房间属于其构造的必需部分
  • 使用查询参数,例如POST /rooms?building=12 { body }。这种结构是非典型的,不推荐。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-08
    • 2011-10-30
    • 2013-01-06
    • 2011-10-06
    • 1970-01-01
    • 2018-08-14
    相关资源
    最近更新 更多