[파이썬] requests 기본 인증 방식

In this blog post, we will explore how to use basic authentication with the requests library in Python.

What is Basic Authentication?

Basic authentication is a simple authentication scheme where the client includes a username and password in the HTTP headers. It is commonly used to protect resources with a password.

Using Requests for Basic Authentication

The requests library is a popular choice for making HTTP requests in Python. It provides an easy-to-use interface and supports various authentication methods, including basic authentication.

To use basic authentication in requests, you need to pass the credentials in the auth parameter of the request. Here’s an example:

import requests

username = 'your_username'
password = 'your_password'
url = 'https://api.example.com'

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

print(response.text)

In the above example, we import the requests module and define the username, password, and URL variables. We then make a GET request to the specified URL, passing the auth parameter with the username and password.

If the credentials are valid, the server will return the requested resource, and the response can be accessed using the response.text attribute.

Handling Authentication Errors

If the username or password is incorrect, the server will respond with a 401 Unauthorized status code. In this case, you can catch the error using a try-except block and handle it accordingly.

try:
    response = requests.get(url, auth=(username, password))
    response.raise_for_status() # Raises an exception for non-2xx responses
except requests.exceptions.HTTPError as err:
    print("HTTP Error:", err)
except requests.exceptions.RequestException as err:
    print("Error:", err)

In the above example, we use the response.raise_for_status() method to raise an exception for any non-2xx responses. This allows us to handle authentication errors or any other HTTP errors that may occur.

Conclusion

Basic authentication is a straightforward way of protecting resources with a password. In Python, the requests library makes it easy to use basic authentication by providing the auth parameter to pass the credentials.

Remember to keep your credentials secure and use HTTPS when transmitting sensitive information over the network.

I hope this blog post has been helpful in understanding how to use basic authentication with requests in Python. Happy coding!