英文:
Python POST request doesn't receive post data from console but works fine on postman
问题
这是我的Postman调用API的请求,我成功获得了所需的响应。
P.S.:我已经添加了头部:'Content-Type': 'application/json'
以下是Postman生成的CURL命令:
curl --location 'api.example.com/apis/v2/show_user_reports' \
--header 'Content-Type: application/json' \
--form 'token="XXXXXXXXXXXXXXXXXXXXXX"' \
--form 'client_id="61"' \
--form 'user_id="7801"'
现在我正在使用Python 3.6进行相同参数和头部的API调用,但它不起作用:
url = 'https://api.example.com/apis/v2/show_user_reports'
headers = {'Content-Type': 'application/json'}
data = {'token': 'XXXXXXXXXXXXXXXXXXXXXX', 'client_id': '61', 'user_id': '7801'}
requests.post(url=url, data=json.dumps(data), headers=headers).json()
通过这样做,我得到了以下响应:
{'error': 'Please Provide Client Id'}
我肯定是在这里漏掉了一些小细节,但找不到是什么。
英文:
This is my postman call for the API and I am getting the needed response successfully.
P.S.: I have added the header: 'Content-Type': 'application/json'
Here's the CURL generated by Postman:
curl --location 'api.example.com/apis/v2/show_user_reports' \ --header 'Content-Type: application/json' \ --form 'token="XXXXXXXXXXXXXXXXXXXXXX"' \ --form 'client_id="61"' \ --form 'user_id="7801"'
Now I am making an this API call using python 3.6 with same parameters and headers but it doesn't work:
url = 'https://api.example.com/apis/v2/show_user_reports'
headers = {'Content-Type': 'application/json'}
data = {'token': 'XXXXXXXXXXXXXXXXXXXXXX', 'client_id': '61', 'user_id': '7801'}
requests.post(url=url, data=json.dumps(data), headers=headers).json()
By doing this, I am getting this response:
> {'error': 'Please Provide Client Id'}
Sure I am missing some small thing in this but couldn't find what.
答案1
得分: 1
你的curl
命令使用--form
选项,将每个参数作为附件进行提交。在requests.post
中,可以使用files
参数来实现这个功能:
url = 'https://api.example.com/apis/v2/show_user_reports'
headers = {'Content-Type': 'application/json'}
files = {
'token': (None, '"XXXXXXXXXXXXXXXXXXXXXX"'),
'client_id': (None, '"61"'),
'user_id': (None, '"7801"'),
}
requests.post(url=url, files=files, headers=headers)
参数的附件不需要指定文件名,因此在这里使用了None
。
英文:
EDITED (previous answer was not correct)
Your curl
is posting using --form
, placing each parameter as an attachment. This is done by using files
parameter in requests.post
:
url = 'https://api.example.com/apis/v2/show_user_reports'
headers = {'Content-Type': 'application/json'}
files = {
'token': (None, '"XXXXXXXXXXXXXXXXXXXXXX"'),
'client_id': (None, '"61"'),
'user_id': (None, '"7801"'),
}
requests.post(url=url, files=files, headers=headers)
The parameter attachments do not need a filename, so None
is specified.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论