RESTful API设计中如何实现批量操作

RESTful API设计中如何实现批量操作?比如一次请求删除N个ID,类似ElasticSearch中bulk那种设计。

阅读 28.7k
5 个回答

设计方法有很多种,借用Backbone.js 的说法:There's More Than One Way To Do It,不要太纠结。

简单的说,下面几种都不错:

  • GET /ec2/instance/batch?id=aa,bb,cc:简约的设计
  • GET /ec2/instance?batch={"ids":["aa","bb","cc"]}:健壮的设计
  • GET /ec2/instance?batch=[{"method":"DELETE","id":"aa"},{"method":"DELETE","id":"bb"},{"method":"DELETE","id":"cc"}]facebook 的设计(墙外)

把上面的 GET 都改成 POST 也没什么问题。

设计 batch 的时候就不用太纠结于 RESTful 的定义(至少我是这样觉得),毕竟是为了优化性能而存在的东西。

批量操作主要是js的操作,获取多个id后用ajax把id集合发送给一个action,具体操作写在action中。
举个例子,routes可以这样写

resources :shops do
  collection do
    post :association_shops
  end
end

参考鬼佬对批量操作的RESTFUL的处理方案,我调整了一下,方案如下:

POST /post

 // Creates a new post!

GET /post/1

 // Returns a single post!

PUT /post/1

 // Updates a post that exists!

DELETE /post/1

 // Deletes a post that exists!

GET /posts

 // Returns a list of all posts available!

POST /posts

Body: {'delete':[1,2,3,4,5,10,42,68,99]}

POST /posts

Body: {'update':{1:{title:'My new title!'},2:{author:'Walter White'}}}

POST /posts

 Body: {'create':[{name:'New post!',body:'Some stuff..'},{name:'Another...',body:'This is nifty!'}]}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题