Last modified: Nov 12, 2024 By Alexander Williams

Python Requests: Master Basic and Digest Authentication

Authentication is crucial for securing web applications and APIs. The Python requests library provides robust support for different authentication methods, particularly Basic and Digest authentication.

Basic Authentication

Basic authentication is the simplest form of HTTP authentication. It sends credentials in base64-encoded format. While simple, it should only be used with HTTPS to ensure security.

Here's how to implement Basic authentication with the requests library:


import requests
from requests.auth import HTTPBasicAuth

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

print(response.status_code)


200

For simpler usage, you can also use a tuple instead of HTTPBasicAuth:


response = requests.get(url, auth=('username', 'password'))

Digest Authentication

Digest authentication is more secure than Basic authentication as it doesn't transmit passwords in encoded format. Instead, it uses a nonce-based authentication system.

To use Digest authentication, you'll need to import HTTPDigestAuth:


from requests.auth import HTTPDigestAuth

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

print(response.status_code)

Error Handling

When dealing with authentication, it's important to handle potential errors. For more details on error handling, check our guide on Python Requests Error Handling.


try:
    response = requests.get(url, auth=HTTPBasicAuth('username', 'wrong_password'))
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    if e.response.status_code == 401:
        print("Authentication failed")
    else:
        print(f"HTTP Error: {e}")

Custom Authentication

You can create custom authentication by subclassing requests.auth.AuthBase. This is useful when working with APIs that require special authentication methods.


from requests.auth import AuthBase

class TokenAuth(AuthBase):
    def __init__(self, token):
        self.token = token

    def __call__(self, r):
        r.headers['Authorization'] = f'Token {self.token}'
        return r

response = requests.get(url, auth=TokenAuth('your-token'))

Session Authentication

For multiple requests to the same host, using a session is more efficient. Learn more about sessions in our guide about Python Requests Session Management.


with requests.Session() as session:
    session.auth = ('username', 'password')
    response1 = session.get('https://api.example.com/endpoint1')
    response2 = session.get('https://api.example.com/endpoint2')

Security Best Practices

Never store credentials in your code. Use environment variables or secure configuration files to store sensitive information.

Always use HTTPS when transmitting credentials. Basic authentication over HTTP is extremely insecure.

Conclusion

Understanding authentication in Python Requests is essential for secure API interactions. Choose the appropriate authentication method based on your security requirements and API specifications.

For more advanced usage, including working with JSON data, check our guide on handling JSON responses with Requests.