python requests authorization header

Python Requests Authorization Header

Python Requests module is used to send HTTP requests to a website and to receive response from it. The module makes it easy for a Python developer to interact with a web service and retrieve the data in an easy and efficient manner. One of the most common use cases of Python Requests module is to send authenticated requests to web services that require an Authorization header.

What is an Authorization Header?

Authorization header is a part of the HTTP protocol that provides authentication information for the request. The header contains the credentials required to authenticate the user or application that is making the request. The most common type of Authorization header is the Basic Authorization header, which includes a username and password encoded in base64 format.

How to Add Authorization Header in Python Requests?

To add an Authorization header in Python Requests, you need to use the headers parameter of the requests.get() method. The headers parameter takes a dictionary of headers to be sent with the request. To add an Authorization header, you need to add a key-value pair to this dictionary where the key is 'Authorization' and the value is the authentication information.


import requests

url = 'https://api.example.com/data'
username = 'my_username'
password = 'my_password'
auth = (username, password)
headers = {'Authorization': 'Basic ' + b64encode(auth.encode()).decode()}
response = requests.get(url, headers=headers)

print(response.content)
    

In the above example, we are sending a GET request to https://api.example.com/data with Basic Authorization header. We are encoding the username and password in base64 format and adding it to the headers dictionary with the key 'Authorization'. Finally, we are sending the request using requests.get() method and printing the response content.

Other Ways to Add Authorization Header

There are other ways to add Authorization header in Python Requests module as well. One such way is to use HTTP basic authentication by passing the credentials directly to requests.get() method.


import requests

url = 'https://api.example.com/data'
username = 'my_username'
password = 'my_password'
response = requests.get(url, auth=(username, password))

print(response.content)
    

In the above example, we are sending a GET request to https://api.example.com/data with HTTP basic authentication. We are passing the username and password directly to requests.get() method using the auth parameter. Finally, we are sending the request and printing the response content.