[파이썬] requests 커스텀 인증 어댑터

In this blog post, we will explore how to create a custom authentication adapter for the requests library in Python. This can be useful when working with APIs that have non-standard or custom authentication methods.

Prerequisites

To follow along with this tutorial, make sure you have the requests library installed. You can install it using pip:

pip install requests

Creating the Custom Authentication Adapter

To create a custom authentication adapter, we need to subclass the requests.auth.AuthBase class and override the __call__ method.

Here’s an example implementation of a custom authentication adapter that adds custom headers to the request:

import requests
from requests.auth import AuthBase

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

    def __call__(self, r):
        # modify the request headers
        r.headers['Authorization'] = f'Token {self.token}'
        r.headers['Custom-Header'] = 'Custom Value'
        return r

In the __init__ method, you can initialize any custom parameters required for authentication. In this example, we are initializing the authentication token.

In the __call__ method, we modify the request object by adding custom headers. The modified request is then returned.

You can customize the __call__ method to implement any custom authentication logic specific to your use case.

Using the Custom Authentication Adapter with Requests

To use our custom authentication adapter with requests, we simply pass an instance of our custom adapter as the auth parameter when making a request:

url = 'https://api.example.com/resource'
auth = CustomAuth(token='your_token_here')
response = requests.get(url, auth=auth)

print(response.json())

In this example, we are making a GET request to an API endpoint and passing our custom authentication adapter as the auth parameter.

You can use the same approach for other HTTP methods (POST, PUT, etc.) and different API endpoints.

Conclusion

Creating a custom authentication adapter for the requests library allows us to handle non-standard or custom authentication methods when interacting with APIs. By subclassing the requests.auth.AuthBase class and overriding the __call__ method, we can implement our custom authentication logic.

I hope you found this tutorial helpful. Happy coding!