我有一个关于如何组织API路由结构的问题。已经阅读了许多关于构建RESTful API的书籍,却找不到答案。每一本书都只讨论简单的CRUD操作以及在一级别中嵌套资源,例如/users
和/users/1/posts
。这没有问题。
例子:
但是让我们看一个更困难的现实生活例子:
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
问题:
在RESTful API中嵌套资源的最大层级是多少?.../defects
这种方式是正常做法吗?
如果我需要添加第四层嵌套,例如所有用于发现缺陷的零件,应该怎么办?
在RESTful API中嵌套资源时,最佳实践是什么?
有人可能会说可以不嵌套。例如:/cars
/repairs
/defects
/parts
,但是在RESTful API中使用嵌套资源的例子呢?那么资源的最大嵌套级别是0、1、2还是3?
此外,如果不进行嵌套,如何筛选具有嵌套筛选项的项目?
defects?car_id=1&repair_id=2&defect_id=3
像这样?看起来很丑陋。
请问是否有书籍或文章可以指导最大嵌套级别以及前面列出的问题的答案。
谢谢。