Using Basic HTTP Authentication with Python Requests

Both great suggestions! Let me add one more nuance. Sometimes, once authenticated, the server uses cookies to manage the session. If the cookies aren’t passed correctly, you could still run into issues. To handle this, use a session object, which automatically manages cookies for you. Here’s how:

import requests
from requests.auth import HTTPBasicAuth

# Create a session
session = requests.Session()

# Authenticate with the session
session.auth = (user, password)

# Make the first request to authenticate
session.post(f'http://{hostname}')

# Make the second request with cookies and auth
response = session.get(f'http://{hostname}/rest/applications')

print(response.status_code)

This approach not only keeps your python requests basic auth credentials intact but also ensures that session cookies (like JSESSIONID) are passed correctly. It’s particularly useful for more complex setups or when the server requires cookies for further interaction.