Authorization header in Python Requests
If you are working with APIs, you would definitely come across the need to authenticate and authorize your API requests. Authorization header is a way to do that. In Python Requests library, adding authorization header to a request is very easy.
Using Basic Authorization
Basic authorization is the simplest form of authorization where you send the username and password in base64 encoded format in the Authorization header. Here is how you can do it in Python Requests:
import requests
import base64
url = "https://api.example.com/users"
username = "rajupython"
password = "secretpassword"
auth_header = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()
headers = {
"Authorization": auth_header
}
response = requests.get(url, headers=headers)
In the above example, we are sending a GET request to the API endpoint with Basic Authorization. We first encode the username and password string in base64 format and then add it to the Authorization header prefixed with "Basic ". This is how we send Basic Authorization header in Python Requests.
Using Token Authorization
Token authorization is another way to authorize API requests. In this method, you get a token from the API endpoint after authenticating with username and password. You then use this token in the Authorization header for subsequent API requests. Here is how you can do it in Python Requests:
import requests
url = "https://api.example.com/token"
username = "rajupython"
password = "secretpassword"
response = requests.post(url, auth=(username, password))
token = response.json()["token"]
headers = {
"Authorization": f"Bearer {token}"
}
response = requests.get("https://api.example.com/users", headers=headers)
In the above example, we are first sending a POST request to the API endpoint to get the token. We use the auth parameter of the requests.post() method to send the username and password. We then extract the token from the response and use it in the Authorization header with "Bearer " prefix for subsequent API requests.