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

查看:288
本文介绍了如何使用密钥而不是基本身份验证用户名和密码将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:

卷曲-v -X GET -H"X-ABC-API-ID:x-x-x-x-x" -H"X-ABC-API-KEY:nnnnnnnnnnnnnnnnnnnnnnnnn" -H"X-DE-API-ID:x" -H"X-DE-API-KEY:nnnnnnnnnnnnnnnnnnnnnnnnnn" " 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天全站免登陆