如何构建相关的RESTful URL

时间:2016-03-02 03:09:15

标签: api rest restful-architecture restful-url

我有两个资源,buildingsrooms

逻辑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?

如何构建更深的节点?当我们引入第三层时,似乎有三种方法可以获得相同的数据

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

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

#3) /api/chairs/3

似乎有不同的方法来获得#3椅子,这意味着重复工作。

2 个答案:

答案 0 :(得分: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/的链接。

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