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

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

问题描述

我正在开发一个用于收集订单的小型客户端服务器程序.我想以REST(ful)方式"做到这一点.

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

目前我看到两个选项:

  1. 将每个订单行发送到服务器:POST qty 和 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} 这样的端点,我们可以 POST 到 /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/-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天全站免登陆