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

时间:2015-02-01 05:10:32

标签: 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)

4 个答案:

答案 0 :(得分:6)

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

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)

答案 1 :(得分:2)

首先,您的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)

答案 2 :(得分:0)

import requests
import json
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)

答案 3 :(得分:0)

在学习Open API时,我已经完成了下面的代码,对我来说很好。

`
import requests
url="your url"
json_data = {"id":"k123","name":"abc"}
resp = requests.post(url=url,json=json_data)
print(resp.status_code)
print(resp.text)
`