如何使用密钥而不是基本身份验证用户名和密码将 Python 连接到 RESTful API? [英] How do I connect with Python to a RESTful API using keys instead of basic authentication username and password?

查看:37
本文介绍了如何使用密钥而不是基本身份验证用户名和密码将 Python 连接到 RESTful API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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"]

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

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

curl -v -X GET -H "X-ABC-API-ID:x-x-x-x-x" -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/"

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 字符串中获取 ID 和密钥以允许使用 Python 访问 Ver 2 API 的方法.感谢您考虑帮助菜鸟完成此代码更改!

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!

推荐答案

您可以向请求添加 HTTP 标头

you can add HTTP headers to a request

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)

这篇关于如何使用密钥而不是基本身份验证用户名和密码将 Python 连接到 RESTful API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆