使用需要不记名令牌的 API 在 Python 中进行 API 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29931671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:10:40  来源:igfitidea点击:

Making an API call in Python with an API that requires a bearer token

pythonpython-2.7curlibm-cloudpycurl

提问by user4657

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. However I am unsure of the syntax to include this token as bearer token authentication in Python API request.

API 指南指出,必须生成不记名令牌以允许调用 API,我已成功完成此操作。但是,我不确定在 Python API 请求中包含此令牌作为不记名令牌身份验证的语法。

I can successfully complete the above request using cURL with a token included. I have tried "urllib" and "requests" routes but to no avail.

我可以使用包含令牌的 cURL 成功完成上述请求。我尝试过“urllib”和“requests”路由,但无济于事。

Full API details: IBM X-Force Exchange API Documentation - IP Reputation

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

回答by Joran Beasley

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())

回答by DSG

The token has to be placed in an Authorization header according to the following format:

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

Authorization: Bearer [Token_Value]

授权:Bearer [Token_Value]

Code below:

代码如下:

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

回答by Zhe

If you are using requestsmodule, 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 authargument just like basic auth, and may help you in certain situations.

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