一种在一个请求中创建多个项目的RESTful方法 [英] RESTful way to create multiple items in one request

查看:74
本文介绍了一种在一个请求中创建多个项目的RESTful方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个小型客户端服务器程序来收集订单.我想以"REST(有效)方式"执行此操作.

I am working on a small client server program to collect orders. I want to do this in a "REST(ful) way".

我想做的是:

收集所有订单行(产品和数量)并将完整的订单发送到服务器

Collect all orderlines (product and quantity) and send the complete order to the server

此刻,我看到两个选项可以做到这一点:

At the moment I see two options to do this:

  1. 将每个订单行发送到服务器:POST数量和product_id

我实际上不想这样做,因为我想限制对服务器的请求数量,所以选择2:

I actually don't want to do this because I want to limit the number of requests to the server so option 2:

  1. 收集所有订单行并将它们立即发送到服务器.

我应该如何实施选项2?我有几个想法是: 将所有订单行包装在JSON对象中,然后将其发送到服务器,或使用数组发布订单行.

How should I implement option 2? a couple of ideas I have is: Wrap all orderlines in a JSON object and send this to the server or use an array to post the orderlines.

实施选项2是个好主意还是好的做法,如果是的话,我应该怎么做.

Is it a good idea or good practice to implement option 2, and if so how should I do it.

什么是良好做法?

推荐答案

我认为,解决此问题的另一种正确方法是创建另一个代表您的资源集合的资源. 例如,假设我们有一个像/api/sheep/{id}这样的终结点,并且可以将其发布到/api/sheep来创建绵羊资源.

I believe that another correct way to approach this would be to create another resource that represents your collection of resources. Example, imagine that we have an endpoint like /api/sheep/{id} and we can POST to /api/sheep to create a sheep resource.

现在,如果我们要支持批量创建,则应考虑在/api/flock(或/api/<your-resource>-collection,如果您缺少一个更有意义的名称)处使用新的羊群资源.请记住,资源无需映射到您的数据库或应用程序模型.这是一个常见的误解.

Now, if we want to support bulk creation, we should consider a new flock resource at /api/flock (or /api/<your-resource>-collection if you lack a better meaningful name). Remember that resources don't need to map to your database or app models. This is a common misconception.

资源是更高级别的表示形式,与您的数据无关.对资源进行操作会产生严重的副作用,例如向用户发出警报,更新其他相关数据,启动长期存在的进程等.例如,我们可以将文件系统甚至unix ps命令映射为REST API.

Resources are a higher level representation, unrelated with your data. Operating on a resource can have significant side effects, like firing an alert to a user, updating other related data, initiating a long lived process, etc. For example, we could map a file system or even the unix ps command as a REST API.

我认为可以肯定地认为,操作资源也可能意味着要创建其他几个实体.

I think it is safe to assume that operating a resource may also mean to create several other entities as a side effect.

这篇关于一种在一个请求中创建多个项目的RESTful方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆