使用请求和 json 将 CURL API 命令转换为 Python API
Convert CURL API command to Python API using requests and json
我正在通过 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))
我正在通过 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))