Python Requests Authorization Bearer: Explained
As a developer who has worked on web applications, I have dealt with authentication and authorization many times. In this post, I will explain how to use Python Requests library to add Authorization Bearer token to an HTTP request.
What is Authorization Bearer?
Authorization Bearer is an authentication scheme that involves the use of tokens. A token is a string of characters that are used to grant access to a resource. The token is sent along with the request, and the server verifies it before allowing access. The Authorization Bearer scheme is used to authenticate users in RESTful APIs.
How to add Authorization Bearer token using Python Requests?
To add Authorization Bearer token to an HTTP request using Python Requests, you need to follow these three steps:
- Get the token
- Add it to the headers
- Send the request
Step 1: Get the token
The first step is to get the authorization token. This token is usually obtained by logging in or by using an API key. In this example, we will assume that we have already obtained the token and stored it in a variable named token.
import requests
token = "Bearer your_token_here"
Step 2: Add it to the headers
The second step is to add the token to the headers of the HTTP request. This is done using the headers parameter of the requests library. We set the value of the Authorization key as "Bearer my_token_here" where my_token_here is replaced with the actual token.
headers = {
"Authorization": token
}
Step 3: Send the request
The final step is to send the HTTP request with the added token header. This is done using the requests.get() method.
response = requests.get("https://api.example.com", headers=headers)
The above code will send a GET request to https://api.example.com with the Authorization Bearer token included in the headers.
Alternative way to add Authorization Bearer token using Python Requests
Another way to add Authorization Bearer token to an HTTP request using Python Requests is by using the auth parameter. This is useful when the token needs to be added to every request. Here is an example:
import requests
auth = ("", "my_token_here")
response = requests.get("https://api.example.com", auth=auth)
In the above code, we pass an empty string for the username and the token as the password in the auth parameter. This will add the Authorization Bearer token to every request.
Conclusion
In this post, we have seen how to use Python Requests library to add Authorization Bearer token to an HTTP request. The Authorization Bearer scheme is a widely used authentication scheme that involves the use of tokens. By following the steps outlined in this post, you can easily add Authorization Bearer token to your HTTP requests in Python.