python requests module username password

Python Requests Module Username Password

If you are working with Python and you need to access resources that require authentication, you can use the requests module to make HTTP requests with a username and password.

Method 1: Using the auth parameter

The most basic way to use authentication with the requests module is to pass a tuple of (username, password) to the auth parameter of the request function.


import requests

url = 'https://example.com/api'
username = 'myusername'
password = 'mypassword'

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

Method 2: Using the HTTPBasicAuth class

You can also use the HTTPBasicAuth class to create an authentication object that you can pass to the auth parameter. This can be useful if you need to reuse the same credentials for multiple requests.


import requests
from requests.auth import HTTPBasicAuth

url = 'https://example.com/api'
username = 'myusername'
password = 'mypassword'
auth = HTTPBasicAuth(username, password)

response = requests.get(url, auth=auth)
print(response.text)
    

Method 3: Using the Session object

If you need to make multiple requests with the same authentication credentials, you can use a Session object to persist the credentials across requests. This can be more efficient than passing the credentials with each request.


import requests

url = 'https://example.com/api'
username = 'myusername'
password = 'mypassword'

session = requests.Session()
session.auth = (username, password)

response1 = session.get(url)
print(response1.text)

response2 = session.get(url + '/another-endpoint')
print(response2.text)