rest - 何时在 Rest API 中使用子资源?

标签 rest api-design

此问题与 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时,将返回汽车的完整表示,包括引擎:

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"
  }
}

要返回资源的部分表示,请考虑此 answer 中提到的方法.

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

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"
}

关于rest - 何时在 Rest API 中使用子资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42392259/

相关文章:

java - 关系实体约定的休息 Controller

java - Vertx客户端Http : Connection closed when perform rest call

rest - REST 应该是超文本驱动是什么意思?

rest - 什么是使用逻辑操作进行查询的 RESTful 方式?

ruby-on-rails - 如何在混合(JSON API + HTML)Rails 5应用程序中使用JSON响应处理通用错误?

java - 错误代码 : 1215 - Cannot add foreign key constraint

android - 改造 - 在字符串中获取响应错误

java - 我应该在 Java 中向我的库 API 添加帮助器/实用程序方法吗?

java - 正确处理返回数据

api - 过滤条件的查询字符串与资源路径