RESTful 服务中的非 CRUD 操作 [英] Non-CRUD operations in a RESTful service
问题描述
向 RESTful 服务添加非 CRUD 操作的RESTful"方式是什么?假设我有一个服务,允许 CRUD 访问这样的记录:
What is the "RESTful" way of adding non-CRUD operations to a RESTful service? Say I have a service that allows CRUD access to records like this:
GET /api/car/123 <- Returns information for the Car object with ID 123
POST /api/car <- Creates a new car (with properties in the request)
PUT /api/car/123 <- Updates car 123 (with properties in the request)
DELETE /api/car/123 <- Deletes car 123
POST /api/car/123/wheel/ <- Creates a wheel and associates it to car 123
如果我想更改汽车的颜色,我只需POST/api/car/123
并为新颜色包含一个 POST 变量.
If I want to change the car's color, I would simply POST /api/car/123
and include a POST variable for the new color.
但是假设我想购买汽车,并且该操作比简单地更新用户"记录的拥有的汽车"属性要复杂得多.简单地执行类似 POST/api/car/123/purchase
之类的事情是否是 RESTful,其中purchase"本质上是一个方法名称?或者我应该使用自定义 HTTP 动词,例如 PURCHASE
而不是 POST
?
But let's say I want to purchase a car, and that operation is more complicated than simply updating a "user" record's "owned car" property. Is it RESTful to simply do something like POST /api/car/123/purchase
, where "purchase" is essentially a method name? Or should I use a custom HTTP verb, like PURCHASE
instead of POST
?
或者非 CRUD 操作是否完全超出 REST 的范围?
Or are non-CRUD operations completely outside the scope of REST?
推荐答案
将 purchase 视为业务实体或 RESTful 字典中的 资源.话虽如此,购买实际上是在创造一种新资源.所以:
Think about purchase as a business entity or a resource in RESTful dictionary. That being said, making a purchase is actually creating a new resource. So:
POST /api/purchase
将下一个新订单.详细信息(用户、汽车等)应通过发送到此地址的内容中的 id(或 URI)引用.
will place a new order. The details (user, car, etc.) should be referenced by id (or URI) inside the contents sent to this address.
订购汽车不仅仅是在数据库中进行简单的 INSERT,这并不重要.实际上,REST 并不是将您的数据库表公开为 CRUD 操作.从逻辑的角度来看,您正在创建订单(购买),但服务器端可以随意执行任意数量的处理步骤.
It doesn't matter that ordering a car is not just a simple INSERT in the database. Actually, REST is not about exposing your database tables as CRUD operations. From logical point of view you are creating an order (purchase), but the server side is free to do as many processing steps as it wants.
您甚至可以进一步滥用 HTTP 协议.使用 Location
标头返回新创建订单的链接,谨慎选择 HTTP 响应代码以通知用户问题(服务器端或客户端)等.
You can even abuse HTTP protocol even further. Use Location
header to return a link to newly created order, carefully choose HTTP response codes to inform users about problems (server- or client-side), etc.
这篇关于RESTful 服务中的非 CRUD 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!