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

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


It just means it expects that as a key in your header data

import requestsendpoint = ".../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":

import requestsclass 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.


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

Authorization: Bearer [Token_Value]

Code below:

import urllib2import jsondef 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_stringdef 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