什么时候在 Rest API 中使用子资源?

When to use subresources in Rest API?

这个问题与 RESTful design: when to use sub-resources? 上发布的一个类似问题有关,但它没有提到这个案例。

我有这个例子

/cars/{carid}
{
"id": 1,
"brand": "something"
"engine":
{
"horse_power": 100,
"type": "hybrid"
}
}

什么是正确的推理可以帮助我决定是否应该将此示例拆分为子资源以使其看起来像这样

/cars/{carid}
{
"id": 1,
"brand": "something"
}

/cars/{carid}/engine
"engine":
{
"horse_power": 100,
"type": "hybrid"
}

如果主要资源是一个包含许多数组和其他相关实体的复杂实体,那么将主要资源拆分成多个子资源可能是有意义的。

但是,如果您担心性能问题,请记住 premature optimization is the root of all evil。在遇到性能问题并且您已经证明性能问题来自于发送大量资源表示之前,您不应该进行优化。


对于问题中提到的情况,支持/cars/{id}/engine这样的子资源在更换整车发动机时可能会有用,如下:

PUT /cars/1/engine HTTP/1.1
Host: example.org
Content-Type: application/json

{
  "horse_power" : 110,
  "type" : "eletric"
}
HTTP/1.1 204 No Content

请求 /cars/1 时,汽车的完整展示(包括引擎)将 returned:

GET /cars/1 HTTP/1.1
Host: example.org
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json

{
  "id" : 1,
  "brand" : "something",
  "engine" : {
    "horse_power" : 110,
    "type" : "eletric"
  }
}

要return资源的部分表示,请考虑中提到的方法。

当请求 /cars/1/engine 时,引擎的表示将是 returned:

GET /cars/1/engine HTTP/1.1
Host: example.org
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json

{
  "horse_power" : 110,
  "type" : "eletric"
}