我正在通过 API 连接来接收数据。从网站API文档来看,说明使用两种CURL方法之一来连接API;但是,我需要使用 python 连接。
第一种方法 卷曲示例
curl -d '' -X POST 'https://api.bcda.cms.gov/auth/token' \
-H "accept: application/json" \
-H "authorization: Basic <Client_Secret>"
我的Python转换:
import requests
import json
url = 'https://api.bcda.cms.gov/auth/token'
headers = {"accept": "application/json", "authorization": 'Basic',
'<API_Key>': '<API_Secret>'}
r = requests.post(url = url, data ={}, headers = headers)
print(r)
第二种方法卷曲
curl -d '' -X POST 'https://api.bcda.cms.gov/auth/token' \
--user <Client_Key>:<Client_Secret> \
-H "accept: application/json"
我的第二个Python转换代码:
import requests
import json
url = 'https://api.bcda.cms.gov/auth/token'
user = {"<Client_Key>":"<Client_Secret>", "accept": "application/json"}
r = requests.post(url = url, headers = user)
print(r)
我收到 403 连接错误,意思是“响应状态代码表明服务器理解请求但拒绝授权。”
您应该使用
auth
参数而不是 headers
来转换 --user
选项
headers = {'accept': 'application/json'}
r = requests.post(url=url, headers=headers, auth=(client_key, client_secret))
@RJ Adriaansen 在评论中提到的curlconverter.com 为我完成了这项工作。这么棒的工具!