Python调用PayPal发票API创建草稿返回400错误求助
问题分析与解决方案
问题根源
你的代码调用requests.post时使用了data=data参数,而data是通过json.load(file)加载的Python字典。此时requests会把字典编码为**表单格式(application/x-www-form-urlencoded)**发送,尽管你在headers里设置了Content-Type: application/json,但实际请求体格式不符合PayPal接口要求,导致返回400格式错误。
Postman能正常执行是因为你在Postman里明确发送的是JSON格式请求体,和接口要求一致。
修复代码
把requests.post中的data=data替换为json=data即可:
import requests import json token="my token would be here" link="https://api-m.sandbox.paypal.com/v2/invoicing/invoices" headers={ "Content-Type": "application/json", "Authorization": f"Bearer {token}" } with open("Json Files\draft.json","r") as file: data=json.load(file) # 关键修改:将data=data改为json=data response=requests.post(link,json=data,headers=headers) print(response) with open("Json Files\Result.json","w") as file: json.dump(response.json(),file,indent=4)
补充说明
requests.post的json参数会自动把Python字典序列化为JSON字符串,并且会正确设置Content-Type(就算你不手动在headers里设置该字段也会自动添加)。- 如果非要用
data参数,需要手动把字典转成JSON字符串:data=json.dumps(data),但用json参数更简洁,不容易出错。
内容的提问来源于stack exchange,提问作者Tang0
相关产品推荐
相关产品推荐

