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

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:

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.

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

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

Authorization: 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

Leave a Reply

Your email address will not be published. Required fields are marked *