python requests basic auth header

Python Requests - Basic Auth Header

If you're working with APIs that require authentication, you need to pass the authentication credentials to the server to get the data. HTTP Basic Authentication is a simple way to provide authentication information for HTTP-based APIs. In this case, you need to send an Authorization header with each HTTP request that contains the authentication credentials encoded in base64.

Using Python Requests Library

Python Requests library is a popular HTTP client library for Python programmers. It provides a simple way to send HTTP/1.1 requests using Python.

To send an HTTP request with Basic Authentication using Python Requests, you need to pass the authentication credentials in the Authorization header. Here's how you can do it:


import requests

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

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

print(response.status_code)
print(response.text)
  

In the above code snippet, we are sending an HTTP GET request to https://api.example.com/data with Basic Authentication. We pass the username and password as a tuple to the auth parameter of the get method.

Alternative way to send Basic Auth Header

You can also send the Basic Authentication header manually if you want more control over the header. Here's how you can do it:


import requests
import base64

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

credentials = f"{username}:{password}"
b64_credentials = base64.b64encode(credentials.encode()).decode('utf-8')

headers = {'Authorization': f'Basic {b64_credentials}'}

response = requests.get(url, headers=headers)

print(response.status_code)
print(response.text)
  

In the above code, we are manually encoding the authentication credentials in base64 and setting the Authorization header to 'Basic ' followed by the base64-encoded credentials. We then pass the headers dictionary to the get method of the requests library.