[英]Making an API call in Python with an API that requires a bearer token
Looking for some help with integrating a JSON API call into a Python program.寻求将 JSON API 调用集成到 Python 程序的帮助。
I am looking to integrate the following API into a Python .py program to allow it to be called and the response to be printed.我希望将以下 API 集成到 Python .py 程序中,以允许调用它并打印响应。
The API guidance states that a bearer token must be generated to allow calls to the API, which I have done successfully. API 指南指出,必须生成不记名令牌以允许调用 API,我已成功完成此操作。 However I am unsure of the syntax to include this token as bearer token authentication in Python API request.
但是,我不确定在 Python API 请求中包含此令牌作为不记名令牌身份验证的语法。
I can successfully complete the above request using cURL with a token included.我可以使用包含令牌的 cURL 成功完成上述请求。 I have tried "urllib" and "requests" routes but to no avail.
我尝试过“urllib”和“requests”路由,但无济于事。
Full API details: IBM X-Force Exchange API Documentation - IP Reputation完整的 API 详细信息: IBM X-Force Exchange API 文档 - IP 声誉
It just means it expects that as a key in your header data这只是意味着它希望作为标题数据中的一个键
import requests
endpoint = ".../api/ip"
data = {"ip": "1.1.2.3"}
headers = {"Authorization": "Bearer MYREALLYLONGTOKENIGOT"}
print(requests.post(endpoint, data=data, headers=headers).json())
If you are using requests
module, an alternative option is to write an auth class, as discussed in " New Forms of Authentication ":如果您正在使用
requests
模块,另一种选择是编写一个 auth 类,如“ 新形式的身份验证”中所述:
import requests
class BearerAuth(requests.auth.AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers["authorization"] = "Bearer " + self.token
return r
and then can you send requests like this然后你可以发送这样的请求吗
response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))
which allows you to use the same auth
argument just like basic auth, and may help you in certain situations.它允许您像基本身份验证一样使用相同的
auth
参数,并且可能在某些情况下为您提供帮助。
The token has to be placed in an Authorization header according to the following format:令牌必须按照以下格式放置在 Authorization 标头中:
Authorization: Bearer [Token_Value]授权:Bearer [Token_Value]
import urllib2
import json
def get_auth_token():
"""
get an auth token
"""
req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
response=urllib2.urlopen(req)
html=response.read()
json_obj=json.loads(html)
token_string=json_obj["token"].encode("ascii","ignore")
return token_string
def get_response_json_object(url, auth_token):
"""
returns json object with info
"""
auth_token=get_auth_token()
req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
response=urllib2.urlopen(req)
html=response.read()
json_obj=json.loads(html)
return json_obj
1. Authorization 1. 授权
You have received access data like this:您已收到如下访问数据:
Username: johndoe
Password: zznAQOoWyj8uuAgq
Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa
Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga
Which you can call in cURL like this:您可以像这样在 cURL 中调用它:
curl -k -d "grant_type=password&username=Username&password=Password" \
-H "Authorization: Basic Base64(consumer-key:consumer-secret)" \
https://somedomain.test.com/token
or for this case it would be:或者对于这种情况,它将是:
curl -k -d "grant_type=password&username=johndoe&password=zznAQOoWyj8uuAgq" \
-H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \
https://somedomain.test.com/token
Answer would be something like:答案将是这样的:
{
"access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
"refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
}
2. Calling API 2.调用API
Here is how you call some API that uses authentication from above.以下是您如何调用一些使用上述身份验证的 API。
Limit
and offset
are just examples of 2 parameters that API could implement. Limit
和offset
只是 API 可以实现的 2 个参数的示例。 You need access_token
from above inserted after "Bearer "
.So here is how you call some API with authentication data from above:您需要在
"Bearer "
之后插入上面的access_token
。所以这里是您如何使用上面的身份验证数据调用一些 API:
curl -k -X GET "https://somedomain.test.com/api/Users/Year/2020/Workers?offset=1&limit=100" -H "accept: application/json" -H "Authorization: Bearer zz8d62zz-56zz-34zz-9zzf-azze1b8057f8"
Same thing from above implemented in Python.上面同样的事情在 Python 中实现。 I've put text in comments so code could be copy-pasted.
我在注释中添加了文本,以便可以复制粘贴代码。
# Authorization data
import base64
import requests
username = 'johndoe'
password= 'zznAQOoWyj8uuAgq'
consumer_key = 'ggczWttBWlTjXCEtk3Yie_WJGEIa'
consumer_secret = 'uuzPjjJykiuuLfHkfgSdXLV98Ciga'
consumer_key_secret = consumer_key+":"+consumer_secret
consumer_key_secret_enc = base64.b64encode(consumer_key_secret.encode()).decode()
# Your decoded key will be something like:
#zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh
headersAuth = {
'Authorization': 'Basic '+ str(consumer_key_secret_enc),
}
data = {
'grant_type': 'password',
'username': username,
'password': password
}
## Authentication request
response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
j = response.json()
# When you print that response you will get dictionary like this:
{
"access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
"refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
}
# You have to use `access_token` in API calls explained bellow.
# You can get `access_token` with j['access_token'].
# Using authentication to make API calls
## Define header for making API calls that will hold authentication data
headersAPI = {
'accept': 'application/json',
'Authorization': 'Bearer '+j['access_token'],
}
### Usage of parameters defined in your API
params = (
('offset', '0'),
('limit', '20'),
)
# Making sample API call with authentication and API parameters data
response = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, params=params, verify=True)
api_response = response.json()
import json
import os
import requests
def lambda_handler(event, context):
print(event)
item = list(map(lambda x: x['detail']['item'], event['inputData']))
print("item List :", item)
consumer_key = os.getenv('consumer_key')
consumer_secret = os.getenv('consumer_secret')
entitlement_url=os.getenv('entitlement_url')
storage_url=os.getenv('storage_url')
access_token = get_jwt_token(consumer_key,consumer_secret,entitlement_url)
print("Response from entitlement: ", access_token)
for listID in list:
print("listID: ", listID)
response = get_storage_service(access_token,storage_url,listID)
print("Response from storage: ", response.text)
return "Success"
def get_jwt_token(consumer_key, consumer_secret, url):
data = 'grant_type=client_credentials&client_id=' + consumer_key + '&client_secret=' + consumer_secret
header = {"Content-type": "application/x-www-form-urlencoded"}
try:
response = requests.post(url, data=data, headers=header)
access_token = json.loads(response.text)
final_response=access_token['access_token']
except requests.exceptions as err:
print(err)
final_response = 'error'
return final_response
def get_storage_service(jwt_token, url, list_id):
final_url = url + list_id + "/data"
print("Final url is :", final_url)
headers_api = {
'Authorization': 'Bearer ' + jwt_token
}
try:
response = requests.get(url=final_url, headers=headers_api)
except requests.exceptions as err:
print(err)
response = 'error'
return response
using enviornment variable使用环境变量
Token process: o A global variable created called 'Header' -令牌过程: o 创建名为“Header”的全局变量 -
o In the token_creation() method, header is initialized in this way: o 在 token_creation() 方法中,header 是这样初始化的:
token_creation() token_creation()
token_create_URL and token_create_json are initialized token_create_URL 和 token_create_json 被初始化
o The returning json in variable 'r' contains the token, but first converted to json o token_response_json contains the jsonified object from ro access_token extracts only the token from token_reponse_json o header["authorization"] = 'Bearer' + access_token o 变量 'r' 中返回的 json 包含令牌,但首先转换为 json o token_response_json 包含来自 ro 的 jsonified 对象 access_token 仅从 token_reponse_json 提取令牌 o header["authorization"] = 'Bearer' + access_token
Now, when any post/get action is required: r1 = requests.post(url=url, json=json_obj, headers=header, verify=False)现在,当需要任何 post/get 操作时: r1 = requests.post(url=url, json=json_obj, headers=header, verify=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.