将非CRUD操作添加到RESTful服务的“ RESTful”方式是什么?假设我有一项服务,允许CRUD访问以下记录:
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变量即可。
但是,假设我要购买汽车,并且该操作比简单地更新“用户”记录的“自有汽车”属性要复杂得多。简单地做类似RESTful的事情POST /api/car/123/purchase
,其中“购买”本质上是一个方法名称?还是应该使用自定义HTTP动词,例如PURCHASE
代替POST
?
还是非CRUD操作完全超出REST的范围?
PATCH /api/car/123
并发送颜色参数,或者使用PUT /api/car/123
并发送整个汽车对象。POST会推断您正在制造一辆新车,并且可能永远不应在URL末尾包含id