Basic authentication helps a server check who you are by asking for a username and password. It keeps things simple and quick.
Basic authentication in Rest API
Authorization: Basic base64(username:password)
The username and password are joined by a colon and then encoded in base64.
This header is sent with each request to prove who you are.
Authorization: Basic dXNlcjpwYXNz
Authorization: Basic YWRtaW46MTIzNA==
This program shows how to send a request with Basic authentication. It encodes the username and password, adds them to the header, and calls a test API that requires these credentials.
import base64 import requests username = 'user' password = 'pass' # Combine username and password user_pass = f'{username}:{password}' # Encode to base64 encoded = base64.b64encode(user_pass.encode()).decode() # Prepare headers with Basic Auth headers = {'Authorization': f'Basic {encoded}'} # Example URL (replace with real API endpoint) url = 'https://httpbin.org/basic-auth/user/pass' # Send GET request with headers response = requests.get(url, headers=headers) # Print status and response JSON print('Status code:', response.status_code) print('Response:', response.json())
Basic authentication sends credentials in base64, which is not encrypted. Use HTTPS to keep it safe.
Each request must include the Authorization header with the encoded credentials.
For better security, consider more advanced methods like token-based authentication.
Basic authentication uses a username and password encoded in base64 sent in the Authorization header.
It is simple but should be used only over secure connections (HTTPS).
It is useful for quick and easy protection of APIs or services.