此问题与 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/