将对象的POST数组发送到REST API [英] POST array of objects to REST API

查看:361
本文介绍了将对象的POST数组发送到REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计应该能够接受对象数组的REST API

I'm designing REST API that should be able to accept array of objects, say

[
 {
   'name': 'Alice',
   'age': 15
 },
 {
   'name': 'Bob',
   'age': 20
 },
 ...
]

实际上,API可以有一个用于接受单个对象的方法,该方法将被循环调用.但是,出于性能原因,我希望在一个请求中发布多个对象.

Indeed, the API could have a method for accepting single object, which would be called in cycle. However, for performance reasons, I wish to POST multiple objects in one request.

最优雅的方式是什么?到目前为止,我唯一的想法是使用JSON,例如:

What is the most elegant way of doing so? So far my only idea is to use JSON, such as:

post_params = { 'data' : to_json_string([ { 'name' : 'Alice', 'age' : 15 },
                                          { 'name' : 'Bob',   'age' : 20 },
                                          ...
                                        ])
              };
post(url, post_params);

这样可以吗,还是应该使用完全不同的方法?

Is this OK, or should I use some completely different approach?

推荐答案

基本上,我正在寻找的答案是:

Basically, the answer I was looking for was:

  1. 无需使用网络中标准的Content-Type: application/x-www-form-urlencoded;相反,应该使用Content-Type: application/json
  2. 整个HTTP请求如下所示:

  1. There is no need to use Content-Type: application/x-www-form-urlencoded which is standard in web; instead, Content-Type: application/json should be used,
  2. The whole HTTP request then looks as follows:

POST /whatever HTTP/1.1
Host: api.example.com
Content-Type: application/json

[
  {
    'name': 'Alice',
    'age': 15
  },
  {
    'name': 'Bob',
    'age': 20
  },
  ...
]

这篇关于将对象的POST数组发送到REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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