4

在 RESTful 应用程序中,我们如何区分“动作”和 HTTP 动词(GET、、、、POST)?PUTDELETE

例如,据我了解,GET对资源的请求/products应返回所有产品的列表。应创建新产品的POST请求。/products那么,用户如何请求用于创建产品的原始表单?我最初的响应是GET对同一个 URI 的请求,但如上所述,它应该返回所有产品的列表 - 而不是用于创建产品的空白表单。

在我研究过的大多数框架中,这个问题是通过将“动作”作为 URI 的一部分来解决的。例如,POST请求/products/create将创建新产品,而GET请求/products/create将提供用于创建产品的空白表单。要获得所有产品的列表,将根据所讨论的框架对或、等GET提出请求。这种方法解决了上面的歧义,但它与我读过的关于传统 REST 设计的内容相冲突。/products/products/get/products/read

4

2 回答 2

2

恕我直言,最好的选择是将请求方法作为控制器操作的一部分。

假设您正在访问http://who.cares/product/42http://who.cares/product/42/specification. 这个对网络服务器的查询将转换为Product控制器。动作名称应该通过结合请求方法和命令来创建:

DELETE "http://who.cares/product/42"

    controller: "Product", 
    action:     "deleteProduct()" 


GET "http://who.cares/product/42/details"

    controller: "Product", 
    action:     "getDetails()"


POST "http://who.cares/product/42/review"

    controller: "Product", 
    action:     "postReview()"


GET "http://who.cares/products/ 

    controller: "Products", 
    action:     "getProducts()"


POST "http://who.cares/products/ 

    controller: "Products", 
    action:     "postProducts()"
于 2012-08-07T23:40:18.093 回答
1

这是 Rails 的例子

REST request path    |  action name | Description
---------------------|-------------------|-------------
GET    /profile/new  | new               | Render a form for creating the profile
POST   /profile      | create            | Create a the profile from the received data
GET    /profile      | show              | Render a the profile
GET    /profile/edit | edit              | Render a form for editing the profile
PUT    /profile      | update            | Update the profile based on the received data
DELETE /profile      | destroy           | Destroy the profile

我没有看到任何冲突,想法是 url 是人类可读的,您可以引入新的 URI 来显示同一资源的不同表示。(如 profile/1/edit 和 profile/1)/profile/new - 为空的配置文件的地址(如 show 方法中的 profile/1、profile/2 .. 等)但如果你愿意,你可以建议 profile/1 /edit 是某种不同的 - profile/1/ 资源的嵌套资源,但我喜欢它只是 profile/1/ 资源的其他表示 =)

当您使用许多资源或使用一个资源时,使用复数和单数 URI 也是一个好主意,例如

/profile/1.html - gives you 1 resource
/profiles.html - gives you list of profiles
于 2012-08-07T23:35:06.640 回答