如何使用requests模块使用Python将JSON文件的内容发布到restfulapi

如何使用requests模块使用Python将JSON文件的内容发布到restfulapi,python,json,api,rest,post,Python,Json,Api,Rest,Post,好吧,我放弃。我试图发布一个包含JSON的文件的内容。文件的内容如下所示: 以下代码可能有点离题: #!/usr/bin/env python3 import requests import json files = {'file': open(‘example.json’, 'rb')} headers = {'Authorization' : ‘(some auth code)’, 'Accept' : 'application/json', 'Content-Type' : 'ap

好吧,我放弃。我试图发布一个包含JSON的文件的内容。文件的内容如下所示:



以下代码可能有点离题:

#!/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)

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

您需要解析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)

我在学习OpenAPI的过程中完成了以下代码,对我来说效果很好

`
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)
`

不知道为什么会有引号。它们在文件中很好,但当我复制并粘贴到这个问题时,它们就如上面所示。无论如何,代码对我不起作用,但可能对其他人起作用。Python 3可能与此有关?将JSON文件的内容发布到API:D-data=JSON.dumps(JSON_数据)这是一个非常古怪的把戏。如果没有,我应该在(某些身份验证代码)中提到什么?在这里,标题={'Authorization':'(某些身份验证代码)……。}(某些身份验证代码)应该替换为'Auth=('username','password')正确吗?更可能的是(某些身份验证代码)='(用户名,密码)“。但我不确定他是如何通过服务器进行身份验证的。在requests.post调用中,作为关键字参数传递这些内容可能更容易,就像在文档中一样:
`
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)
`