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

Alternatives of using verbs and adjectives in RESTful URL

我想向我的 REST API 添加操作,这将在不同 'stores' 之间移动 'resources'。

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

/resources
/resources/{resourceId}

现在假设我想 'deactivate' 一些资源,即在概念上将其移动到另一个子文件夹。允许这样做的最直接的方法如下。

  1. 'Deactivate' 资源,即导致它在 /resources 下不可用。从概念上讲,它 'moves' 对象到 '/resources/deactivated/' 子文件夹:

    POST /resources/{resourceId}/deactivate   
    

    或者:

    POST /resources/deactivated/{resourceId}
    
  2. 获取所有停用对象:

    GET /resources/deactivated      
    
  3. 反转 'deactivate' 操作,即在概念上将对象从“/resources/deactivated/”子文件夹移回主文件夹('/资源').

    两者都

    POST /resources/{resourceId}/reactivate    
    

    POST /resources/deactivated/{resourceId}/restore     
    

    这个 API 对我来说似乎很直观。但是好像违反了我在很多best practices-articles on REST看到的'prefer nouns'规则API:我用动词和形容词代替名词!

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

我的 REST API 有更好的替代品吗? IE。更多 RESTful,但也不少?

我可以找到关于该主题的好资源:

活动资源与停用资源真的有那么大不同吗?考虑只使用一个 属性 来跟踪 activeness。您可以随时将它们过滤掉,例如

GET /things?active=true

您可以使用 microPUT

仅更改 属性
PUT /things/{id}/active
false

如果 thingdeactivated-thing 在概念上不同,则有两个独立的端点是合理的。我会使用

在它们之间移动
POST `/deactivated-things`
{
    "thing": "/things/12"
}

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

你应该尽量避免一条路径有多重含义。例如,不要这样做:

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

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

首先,请记住 REST 代表 Representational State T转.

一切都是关于 资源及其状态 activatedeactivatemove 等操作都是关于将资源的当前状态替换为新的表示形式,您不需要 URL 中的动词来表达此类操作。


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

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

{ "status" : "active" }

可以理解为[id]标识的资源状态替换为请求payload中发送的状态


然后您可以通过以下方式获取具有特定状态的资源:

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]标识的资源文件夹替换为请求payload中发送的文件夹

感谢 Cassio 强调 'changing the object state' 方法。

我自己的完整性回答:

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

关于 REST,您从未见过的一件事:

不要将 REST 与网络应用程序或漂亮的 urls 混淆。

例如。当用户登录编辑他们的帐户时,您会显示

www.example.com/home
www.example.com/account
www.example.com/profile

而不是

// www.example.com/users/{id} ...
www.example.com/users/433563444335634443356344
www.example.com/users/433563444335634443356344/edit

我认为这是许多开发人员感到困惑的地方。 REST 非常适合 APIs,但就 Web 应用程序而言,它应该用作表单操作端点的内部 API 或 ajax,例如,但不一定是漂亮的url.