【问题标题】:When to use subresources in Rest API?何时在 Rest API 中使用子资源?
【发布时间】:2017-04-19 16:42:21
【问题描述】:

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

【问题讨论】:

    标签: rest api-design


    【解决方案1】:

    如果主要资源是具有许多数组和其他相关实体的复杂实体,则将主要资源拆分为多个子资源可能是有意义的。

    但是,如果您担心性能问题,请记住 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"
    }
    

    【讨论】:

    • 但这也可以使用 PUT /cars/1/HTTP/1.1 主机:example.org 内容类型:application/json { "horse_power" : 110, "type" : "eletric" }
    • 在拆分资源时,我一直在寻找更多与休息相关的好处,而不是更简洁的代码和更少的标记。
    • 完全正确,因此您实际上可以只发送诸如 { "horse_power" : 110, "type" : "eletric" } 之类的引擎,以便对 cars/1 甚至 {"horse_power " : 110, } 只是改变引擎的马力。我相信这是休息所允许的
    • @mko 没有。PUT 方法的意思是替换。使用PUT 时,目标资源必须完全替换为请求有效负载中发送的表示。对于部分更新,必须使用PATCH
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    相关资源
    最近更新 更多