使用需要持有者令牌的 API 在 Python 中进行 API 调用

寻找将 JSON API 调用集成到 Python 程序中的一些帮助。

我希望将下面的 API 集成到 Python 中。Py 程序,以允许调用它并打印响应。

API 指南指出,必须生成一个持有者令牌,以允许对 API 的调用,我已经成功地完成了这项工作。然而,我不确定在 PythonAPI 请求中将此令牌作为持有者令牌身份验证包含在内的语法。

我可以使用包含令牌的 cURL 成功地完成上述请求。我试过“ urllib”和“ request”路由,但都没有用。

API 详情: IBMX-ForceExchangeAPI 文档-IP 声誉

334308 次浏览

它只是意味着它期望将它作为头数据中的键

import requests
endpoint = ".../api/ip"
data = {"ip": "1.1.2.3"}
headers = {"Authorization": "Bearer MYREALLYLONGTOKENIGOT"}


print(requests.post(endpoint, data=data, headers=headers).json())

令牌必须按照以下格式放置在授权标头中:

授权: 持有人[令牌 _ 价值]

密码如下:

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

如果您正在使用 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

然后你能像这样发送请求吗

response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))

它允许您像使用基本 auth 一样使用相同的 auth参数,并且在某些情况下可以帮助您。

下面是在 cURL 和 Python 中实现的完整示例——用于授权和 API 调用

CURL

1. 授权

您收到的访问数据如下:

Username: johndoe


Password: zznAQOoWyj8uuAgq


Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa


Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga

可以像下面这样调用 cURL:

curl -k -d "grant_type=password&username=Username&password=Password" \


-H "Authorization: Basic Base64(consumer-key:consumer-secret)" \


https://somedomain.test.com/token

或者在这种情况下,应该是:

curl -k -d "grant_type=password&username=johndoe&password=zznAQOoWyj8uuAgq" \


-H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \


https://somedomain.test.com/token

答案是这样的:

{
"access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
"refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
}

2. 调用 API

下面介绍如何调用一些使用上述身份验证的 API。Limitoffset只是 API 可以实现的两个参数的例子。 你需要在 "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"

巨蟒

上面在 Python 中实现了同样的东西,我在注释中加入了文本,这样代码就可以被复制粘贴了。

# 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

使用环境变量