在RESTful应用程序中,我们如何区分"action"和HTTP动词(GET
,POST
,PUT
,DELETE
)?
例如,据我了解,对资源/products
的GET
请求应返回所有产品的列表。 POST
请求/products
应创建一个新产品。 那么,用户如何请求用于创建产品的原始表单? 我最初的响应是对同一 URI 的GET
请求,但如上所述,它应该返回所有产品的列表 - 而不是用于创建产品的空白表单。
在我研究过的大多数框架中,这个问题是通过使"操作"成为URI的一部分来解决的。 例如,对/products/create
POST
请求将创建一个新产品,而对/products/create
GET
请求将提供用于创建产品的空白表单。 获取所有产品的列表将是对/products
或/products/get
、/products/read
等的GET
请求,具体取决于所讨论的框架。 这种方法解决了上面的歧义,但它与我读到的关于传统 REST 设计的内容相冲突。
我直言,最好的选择是使请求方法成为控制器操作的一部分。
假设您正在访问http://who.cares/product/42
或http://who.cares/product/42/specification
。对 Web 服务器的此查询将转换为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()"
这是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 来显示同一资源的不同表示形式。(如个人资料/1/编辑和个人资料/1)/profile/new - 空配置文件的地址(如 show 方法中的配置文件/1、配置文件/2 .. 等)但是,如果您愿意,您可以建议配置文件/1/编辑是某种不同的 - 配置文件/1/资源的嵌套资源,但我喜欢它只是配置文件/1/资源的其他表示形式=)
使用多个资源或一个示例时,使用复数和单数 URI 也是一个好主意
/profile/1.html - gives you 1 resource
/profiles.html - gives you list of profiles