如何使用密钥而不是基本身份验证用户名和密码将 Python 连接到 RESTful API?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32998640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:35:29  来源:igfitidea点击:

How do I connect with Python to a RESTful API using keys instead of basic authentication username and password?

pythonapicurlpython-requests

提问by wautry

I am new to programming, and was asked to take over a project where I need to change the current Python code we use to connect to a Ver 1 RESTful API. The company has switched to their Ver 2 of the API and now require IDs and Keys for authentication instead of the basic username and password. The old code that worked for the Ver 1 API looks like this:

我是编程新手,被要求接管一个项目,我需要更改当前用于连接到 Ver 1 RESTful API 的 Python 代码。该公司已切换到 API 的第 2 版,现在需要 ID 和密钥进行身份验证,而不是基本的用户名和密码。适用于 Ver 1 API 的旧代码如下所示:

import requests
import simplejson as json
import pprintpp as pprint

#API_Ver1 Auth
USER = 'username'
PASS = 'password'
url = 'https://somecompany.com/api/v1/groups'
s = requests.Session()
s.auth = (USER, PASS)

r = json.loads(s.get(url).text)
groups = r["data"]

I can connect to the Ver 2 API via a terminal using a cURL string like this:

我可以使用像这样的 cURL 字符串通过终端连接到 Ver 2 API:

curl -v -X GET -H "X-ABC-API-ID:x-x-x-x-x" -H "X-ABC-API-KEY:nnnnnnnnnnnnnnnnnnnnnnn" -H "X-DE-API-ID:x" -H "X-DE-API-KEY:nnnnnnnnnnnnnnnnnnnnnnnn" "https://www.somecompany.com/api/v2/groups/"

curl -v -X GET -H "X-ABC-API-ID:xxxxx" -H "X-ABC-API-KEY:nnnnnnnnnnnnnnnnnnnnn" -H "X-DE-API-ID:x" -H "X- DE-API-KEY:nnnnnnnnnnnnnnnnnnnnnn" " https://www.somecompany.com/api/v2/groups/"

I have searched, but have been unsuccessful in finding a way to get the IDs and Keys from the cURL string to allow access to the Ver 2 API using Python. Thanks for your consideration in helping a noob get through this code change!

我进行了搜索,但未能找到从 cURL 字符串中获取 ID 和密钥以允许使用 Python 访问 Ver 2 API 的方法。感谢您考虑帮助菜鸟完成此代码更改!

回答by r-m-n

you can add HTTP headers to a request

您可以向请求添加 HTTP 标头

headers = {
    'X-ABC-API-ID': 'x-x-x-x-x',
    'X-ABC-API-KEY': 'nnnnnnnnnnnnnnnnnnnnnnn',
    'X-DE-API-ID': 'x',
    'X-DE-API-KEY': 'nnnnnnnnnnnnnnnnnnnnnnnn'
}
r = requests.get('https://www.somecompany.com/api/v2/groups/', headers=headers)