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

use*_*657 52 python curl pycurl python-2.7 ibm-cloud

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

我希望将以下API集成到Python .py程序中,以允许它被调用并打印响应.

API指南规定必须生成承载令牌以允许调用API,这是我成功完成的.但是,我不确定在Python API请求中将此令牌包含为承载令牌身份验证的语法.

我可以使用包含令牌的cURL成功完成上述请求.我试过"urllib"和"请求"路线但无济于事.

完整的API详细信息:IBM X-Force Exchange API文档 - IP信誉

Jor*_*ley 84

它只是意味着它期望作为标题数据中的一个键

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

print(requests.post(endpoint, data=data, headers=headers).json())
Run Code Online (Sandbox Code Playgroud)


Zhe*_*Zhe 84

如果您正在使用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
Run Code Online (Sandbox Code Playgroud)

然后你可以发送这样的请求吗

response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))
Run Code Online (Sandbox Code Playgroud)

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


小智 18

必须根据以下格式将令牌放置在Authorization标头中:

授权:承载[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
Run Code Online (Sandbox Code Playgroud)


Har*_*vey 11

这是在 cURL 和 Python 中实现的完整示例 - 用于授权和进行 API 调用

卷曲

1. 授权

您已收到如下访问数据:

Username: johndoe

Password: zznAQOoWyj8uuAgq

Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa

Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga
Run Code Online (Sandbox Code Playgroud)

您可以像这样在 cURL 中调用它:

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

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

                       https://somedomain.test.com/token
Run Code Online (Sandbox Code Playgroud)

或者对于这种情况,它将是:

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

                    -H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \

                      https://somedomain.test.com/token
Run Code Online (Sandbox Code Playgroud)

答案将是这样的:

{
    "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
    "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
    "scope": "default",
    "token_type": "Bearer",
    "expires_in": 3600
}
Run Code Online (Sandbox Code Playgroud)

2.调用API

以下是您如何调用一些使用上述身份验证的 API。Limit并且offset只是 API 可以实现的 2 个参数的示例。您需要access_token从上面插入"Bearer ".So 以下是您如何使用上面的身份验证数据调用一些 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"
Run Code Online (Sandbox Code Playgroud)

Python

上面同样的事情在 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()
Run Code Online (Sandbox Code Playgroud)