Python requests library basic auth
Python requests library is one of the most popular and widely used libraries for sending HTTP requests in Python. One of the most common use cases for requests is to interact with web APIs that require authentication. Basic authentication is one of the simplest forms of authentication, where the client sends a username and password in every request.
Using Basic Authentication with Requests
The requests library makes it easy to send HTTP requests with basic authentication. To send a request with basic authentication, we need to pass the username and password as a tuple to the auth
parameter of the requests.get()
or requests.post()
method.
import requests
url = 'https://api.example.com'
username = 'myusername'
password = 'mypassword'
response = requests.get(url, auth=(username, password))
print(response.status_code)
In the above code snippet, we import the requests library and define the URL of the API we want to send a request to. We also define the username and password as variables. We then send a GET request to the API with basic authentication by passing the auth
tuple to the requests.get()
method. Finally, we print the status code of the response.
Using Session Objects for Basic Authentication
If we need to send multiple requests with the same authentication credentials, we can use session objects in requests. Session objects allow us to persist certain parameters across requests, including authentication credentials.
import requests
url = 'https://api.example.com'
username = 'myusername'
password = 'mypassword'
session = requests.Session()
session.auth = (username, password)
response1 = session.get(url + '/resource1')
response2 = session.get(url + '/resource2')
print(response1.status_code)
print(response2.status_code)
In the above code snippet, we create a session object and set the authentication credentials to the auth
attribute of the session object. We then send two GET requests to different resources on the API using the same session object. Finally, we print the status codes of both responses.
Conclusion
The requests library makes it easy to interact with web APIs that require authentication. Basic authentication is one of the simplest forms of authentication, and requests provides an easy way to send requests with basic authentication. We can also use session objects to persist authentication credentials across multiple requests.