python requests auth

Python Requests Auth

Python requests library is widely used to send HTTP requests and handle their responses. It provides a very simple API to access web resources, which makes it easy to use for developers. One of the important features of the requests library is the ability to authenticate HTTP requests. In this blog, we will learn about different types of authentication, how to add authentication information to requests and how to handle authentication errors.

Types of Authentication:

  • Basic Authentication
  • Token Authentication
  • Digest Authentication
  • OAuth Authentication
  • API key Authentication

Adding Authentication Information:

To add authentication information, we need to pass the credentials to the requests library. The credentials can be passed in different ways depending on the authentication method.

One common way to add authentication information is by passing a tuple containing the username and password to the auth parameter of the requests.get() method. This is used for Basic Authentication.


import requests
from requests.auth import HTTPBasicAuth
 
url = 'https://example.com/api/resource'
response = requests.get(url, auth=HTTPBasicAuth('username', 'password'))

Another way to add authentication information is by passing a dictionary containing the token value to the headers parameter of the requests.get() method. This is used for Token Authentication.


import requests
 
url = 'https://example.com/api/resource'
headers = {'Authorization': 'Token 1234567890abcdef'}
response = requests.get(url, headers=headers)

For Digest Authentication, we need to pass the username and password to the auth parameter of the requests.get() method. The Digest Authentication is more secure than Basic Authentication.


import requests
from requests.auth import HTTPDigestAuth
 
url = 'https://example.com/api/resource'
response = requests.get(url, auth=HTTPDigestAuth('username', 'password'))

For OAuth Authentication, we need to pass the access token value to the headers parameter of the requests.get() method.


import requests
 
url = 'https://example.com/api/resource'
headers = {'Authorization': 'Bearer ACCESS_TOKEN'}
response = requests.get(url, headers=headers)

For API key Authentication, we need to pass the API key value to the headers parameter of the requests.get() method.


import requests
 
url = 'https://example.com/api/resource'
headers = {'X-API-Key': 'API_KEY_VALUE'}
response = requests.get(url, headers=headers)

Handling Authentication Errors:

In case of authentication errors, the requests library raises an HTTPError with a status code of 401. We can catch this error and handle it in our code.


import requests
from requests.exceptions import HTTPError
 
url = 'https://example.com/api/resource'
response = None
 
try:
    response = requests.get(url, auth=HTTPBasicAuth('username', 'password'))
    response.raise_for_status()
except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
except Exception as err:
    print(f'Other error occurred: {err}')
finally:
    if response:
        print('Response received')