如何使用requests modu用Python将JSON文件的内容发布到RESTFUL API

2024-09-30 08:32:50 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我放弃。我试图发布包含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)

Tags: 文件importapiidjson内容applicationexample
3条回答

您需要解析JSON,然后像这样传递主体:

import requests
import json
json_data = None

with open('example.json') as json_file:
    json_data = json.load(json_file)

auth=('token', 'example')

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

首先,json文件不包含有效的json。如中所示,"id”-这里的右引号不同于左引号。其他ID字段也有相同的错误。像这样"id"

现在你可以这样做了

import requests
import json
with open('example.json') as json_file:
    json_data = json.load(json_file)

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', data=json.dumps(json_data), 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)

相关问题 更多 >

    热门问题