python requests with bearer token

Python Requests with Bearer Token

If you are working with an API that requires authentication, you may need to include a bearer token in your requests. Here's how you can do it with Python Requests:

Method 1: Using Headers

You can include the bearer token in the headers of your request. Here's an example:


import requests

url = 'https://api.example.com/data'
headers = {'Authorization': 'Bearer YOUR_TOKEN_HERE'}

response = requests.get(url, headers=headers)
print(response.json())
    

In this example, we're making a GET request to 'https://api.example.com/data' and passing in a dictionary of headers that includes the bearer token. This will authenticate our request and allow us to access the protected resource.

Method 2: Using Session

You can also use a session object to include the bearer token in all of your requests. Here's how:


import requests

url = 'https://api.example.com/data'
headers = {'Authorization': 'Bearer YOUR_TOKEN_HERE'}

session = requests.Session()
session.headers.update(headers)

response = session.get(url)
print(response.json())
    

In this example, we're creating a session object and updating its headers with the bearer token. From there, we can make any number of requests using this session object and the headers will be automatically included.

Method 3: Using OAuth2Session

If you are using OAuth2 to authenticate, you can use the OAuth2Session library to make requests. Here's an example:


from requests_oauthlib import OAuth2Session

token = {'access_token': 'YOUR_TOKEN_HERE'}
oauth = OAuth2Session(token=token)

url = 'https://api.example.com/data'
response = oauth.get(url)

print(response.json())
    

In this example, we're creating an OAuth2Session object with our bearer token and using it to make a request to the API. This library takes care of the authentication for us, so we don't need to manually include the token in our headers.