首页 文章

在RESTful URL中使用动词和形容词的替代方法

提问于
浏览
1

我想在我的REST API中添加操作,以便在不同的“商店”之间移动“资源” .

例如,假设我的资源通常由以下URL访问:

/resources
/resources/{resourceId}

现在假设我想'停用'某些资源,即从概念上将其移动到另一个子文件夹 . 允许这种情况的最直接的方法如下 .

  • 'Deactivate'资源,即使其在/ resources下不可用 . 从概念上讲,它是'/ resources / deactivated /'子文件夹的对象'moves':
POST /resources/{resourceId}/deactivate

或者:

POST /resources/deactivated/{resourceId}
  • 获取所有已停用的对象:
GET /resources/deactivated
  • 反转'deactivate'操作,即概念性地从'/ resources / deactivated / ' subfolder back to the main one (' / resources'移动对象 .

POST /resources/{resourceId}/reactivate

要么

POST /resources/deactivated/{resourceId}/restore

这个API对我来说似乎很直观 . 但它似乎违反了我在许多最佳实践中看到的“首选名词”规则 - 关于REST API的文章:我使用动词和形容词而不是名词!

请注意,我可能有所有 endpoints 的参数,例如GET / resources / deactivated?createdBefore = 01022017

Are there any better alternatives for my REST API? I.e. more RESTful, but not less intuitive ones?

我能找到关于这个主题的好资源:

3 回答

  • 0

    首先,请记住 REST 代表 Re presentational S tate T ransfer .

    这完全取决于资源及其状态 . 激活,停用和移动等操作都是用新表示替换资源的当前状态,并且URL中不需要动词来表示此类操作 .


    例如,要替换资源的状态,您可以在 PUT 请求的有效负载中发送资源的新表示:

    PUT /api/resources/[id]/status HTTP/1.1
    Host: example.org
    Content-Type: application/json
    
    { "status" : "active" }
    

    可以理解为将 [id] 标识的资源的状态替换为请求有效负载中发送的资源的状态 .


    然后,您可以使用以下内容来获取具有特定状态的资源:

    GET /api/resources?status=active HTTP/1.1
    Host: example.org
    Accept: application/json
    

    可以理解为给我一个状态为 active 的所有资源的表示 .


    例如,要将资源移动到另一个文件夹,您可以:

    PUT /api/resources/[id]/folder HTTP/1.1
    Host: example.org
    Content-Type: application/json
    
    { "target" : "draft" }
    

    可以理解为将 [id] 标识的资源的文件夹替换为请求有效负载中发送的文件夹 .

  • 6

    活动资源是否真的与已停用的资源不同?考虑只有一个跟踪 active ness的属性 . 您可以随时过滤掉它们,例如

    GET /things?active=true
    

    您可以使用microPUT改变该属性

    PUT /things/{id}/active
    false
    

    如果 thingdeactivated-thing 在概念上不同,则有两个单独的 endpoints 是合理的 . 我会在他们之间使用

    POST `/deactivated-things`
    {
        "thing": "/things/12"
    }
    

    POST `/things`
    {
        "deactivated-thing": "/deactivated-things/12"
    }
    

    您应该尽量避免具有多种含义的路径 . 例如,不要这样做:

    /resources/{id}
    /resources/deactivated/{id}
    

    /resources 之后不要重载路径段的含义 .

  • 3

    感谢Cassio强调“改变对象状态”的方法 .

    我自己对完整性的回答:

    PATCH /resources/{resourceId} with body {"active":false}  -- deactivate a resource
    PATCH /resources/{resourceId} with body {"active":true}  -- restore a resource
    GET    /resources                        -- return all 'normal' resources
    GET    /resources?includeInactive=true   -- return all resources including the deactivated ones
    GET    /resources/{resourceId}           -- return the resource
    

    ('GET'检索的资源将包含属性'active=true/false') .

    看起来像PATCH的经典案例:REST API PATCH or PUT

相关问题