API Navigator Logo

Python Requests with Basic Authentication

Author: Newtum

This example shows how to perform Basic Authentication when making requests with the Python Requests library.

What is Basic Authentication?

Basic Authentication is a simple authentication scheme built into the HTTP protocol. The client sends a username and password with the request in the `Authorization` header. The credentials are not encrypted, only Base64 encoded, so it should only be used over HTTPS.

Using the `auth` Parameter

Requests provides a convenient `auth` parameter that takes a tuple of (username, password) to handle Basic Auth for you.

import requests
from requests.auth import HTTPBasicAuth

# This is a sample endpoint that requires basic auth
url = 'https://httpbin.org/basic-auth/user/passwd'

# Provide username and password
response = requests.get(url, auth=HTTPBasicAuth('user', 'passwd'))

print('Status Code:', response.status_code)
if response.status_code == 200:
    print('Authentication successful!')
    print(response.json())
else:
    print('Authentication failed.')