python - 如何使用请求模块使用 Python 将 JSON 文件的内容发布到 RESTFUL API

标签 python json api rest post

好吧,我放弃了。我正在尝试发布包含 JSON 的文件的内容。该文件的内容如下所示:


{
     "id”:99999999,
     "orders":[
     {
             "ID”:8383838383,
             "amount":0,
             "slotID":36972026
     },
     {
             "ID”:2929292929,
             "amount":0,
             "slotID":36972026
     },
     {
             "ID”:4747474747,
             "amount":0,
             "slotID":36972026
     }]
}

下面是可能偏离标记的代码:

#!/usr/bin/env python3

import requests
import json

files = {'file': open(‘example.json’, 'rb')}
headers = {'Authorization' : ‘(some auth code)’, 'Accept' : 'application/json', 'Content-Type' : 'application/json'}

r = requests.post('https://api.example.com/api/dir/v1/accounts/9999999/orders', files=files, headers=headers)

最佳答案

这应该可行,但它适用于非常大的文件。

import requests

url = 'https://api.example.com/api/dir/v1/accounts/9999999/orders'
headers = {'Authorization' : ‘(some auth code)’, 'Accept' : 'application/json', 'Content-Type' : 'application/json'}
r = requests.post(url, data=open('example.json', 'rb'), headers=headers)

如果要发送较小的文件,请将其作为字符串发送。

contents = open('example.json', 'rb').read()
r = requests.post(url, data=contents, headers=headers)

关于python - 如何使用请求模块使用 Python 将 JSON 文件的内容发布到 RESTFUL API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28259697/

相关文章:

python - 深度学习: Multiclass Classification with same amount of labels between the training dataset and test dataset

python - 在 Jupyter Notebook 中导入 pyplot

python - 如何在 Django 中检查与 mysql 的数据库连接

android camera2 将 TotalCaptureResult 与 Frame 相关联

javascript - 尝试访问 Youtube Data Api v3 时出现 `Google Maps API warning: NoApiKeys `

python - 可变 str 类扩展

jquery - 使用 JSON 将对象数组从 jsp 传递到 java servlet

javascript - 如何在使用 Reactjs 时将数据写入 JSON 文件

java - Servlet 返回 "到 AngularJS2 调用

ruby-on-rails - 如何从另一个 Controller 内部获取 Controller 的响应?