In this lesson, you will learn how to design reusable request middleware to automatically inject authentication headers into every outgoing API call within your application.
The Problem: Repetitive Authentication
When building robust integrations, you likely interact with multiple endpoints of the same service. Manually attaching an Authorization header to every single requests.get() or requests.post() call is error-prone and leads to code duplication. If the authentication scheme changes—for example, switching from a simple Bearer token to a custom X-API-Key header—you would have to hunt down and update every single request in your codebase.
The Solution: Request Middleware
Instead of manually managing headers, we can leverage the requests library's AuthBase class. By subclassing AuthBase, we create a "middleware" object that intercepts the request lifecycle, ensuring our credentials are injected consistently without cluttering our business logic.
Here is how you implement a custom BearerAuth middleware:
import requests
from requests.auth import AuthBase
class BearerAuth(AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
# This method is automatically called by the requests session
r.headers["Authorization"] = f"Bearer {self.token}"
return r
# Usage:
token = "my_secret_api_token"
session = requests.Session()
session.auth = BearerAuth(token)
# Every request made via this session will now automatically include the header
response = session.get("https://api.example.com/data")
Why This Architecture Matters
By encapsulating the authentication logic within a custom class, you achieve two goals:
- Separation of Concerns: Your API client logic focuses on the data flow, while your
AuthBasesubclass handles the security handshake. - Global Configuration: By attaching the custom class to a
requests.Sessionobject, you guarantee that every subsequent call—regardless of the URL or method—is authenticated correctly. If you need to add dynamic logic, such as appending a timestamp or a signature to the headers, you only need to modify the__call__method in one place.
Key Takeaway: Use the AuthBase interface to create reusable authentication middleware, ensuring your credentials are injected consistently while keeping your primary API logic clean and maintainable.