Python Requests Authentication: Bearer Token, API Key, and Basic Auth
Learn how to authenticate Python requests calls using basic auth, bearer tokens, and API keys. Includes practical code examples, error handling, and security considerations.

Authenticating a REST API call from Python with the requests library depends on the authentication scheme the server expects. This article covers the three most common methods—basic auth, bearer tokens, and API keys—and shows how to implement each one with practical code examples.
Choosing the Right Authentication Method
Before writing code, you need to know which scheme the server expects. The API documentation usually states it explicitly. Basic auth sends a username and password encoded in the Authorization header. Bearer token authentication sends a token in the same header, prefixed with Bearer. API keys are typically sent in a custom header like X-API-Key, but some services accept them as query parameters. The choice is not yours to make; it is dictated by the server. Your job is to implement the correct header or parameter format.
Basic Authentication with requests
Basic auth is the simplest scheme. The requests library accepts a tuple of (username, password) directly in the auth parameter. Internally, requests base64-encodes the username:password value and sets the Authorization header to Basic <base64-encoded-credentials>.
import requests
response = requests.get(
"https://api.example.com/resource",
auth=("alice", "secret-password")
)You can also use the HTTPBasicAuth class explicitly:
from requests.auth import HTTPBasicAuth
response = requests.get(
"https://api.example.com/resource",
auth=HTTPBasicAuth("alice", "secret-password")
)Both forms produce the same request. The tuple form is shorter and works for most cases. One important detail: basic auth sends credentials in plaintext if the connection is not HTTPS. Always use HTTPS in production, otherwise the credentials can be intercepted.
Bearer Token Authentication
Bearer tokens are common in OAuth 2.0 and OpenID Connect flows. The token is placed in the Authorization header with the Bearer prefix. With requests, you set this header manually using the headers parameter.
import requests
token = "your-oauth-token"
headers = {"Authorization": f"Bearer {token}"}
response = requests.get(
"https://api.example.com/secure-resource",
headers=headers
)The token is often obtained from an authentication endpoint before making the actual API call. In that case, you might store it in a variable or a session object. The important part is that the header value must be exactly Bearer <token> with a single space between the word and the token.
If you are using a requests.Session for multiple calls, set the header once on the session:
import requests
session = requests.Session()
session.headers.update({"Authorization": "Bearer your-token"})
response = session.get("https://api.example.com/resource")This avoids repeating the header in every request. Sessions also reuse the underlying TCP connection, which can reduce latency when you make many calls to the same host.
API Key Authentication
API keys are not standardized. The most common pattern is a custom header, often named X-API-Key or apikey. Some services accept the key as a query parameter. You need to read the API documentation to know which one the server expects.
API Key in a Header
import requests
api_key = "your-api-key"
headers = {"X-API-Key": api_key}
response = requests.get(
"https://api.example.com/data",
headers=headers
)API Key as a Query Parameter
import requests
api_key = "your-api-key"
params = {"api_key": api_key}
response = requests.get(
"https://api.example.com/data",
params=params
)Some services use a different parameter name, such as key or apikey. Always check the documentation. Sending the key in a query parameter can leak it into server logs and browser history, so the header approach is generally safer. Prefer headers when the server supports them.
Handling Authentication Errors
When credentials are missing or invalid, the server typically returns 401 Unauthorized. A 403 Forbidden can also appear if the authenticated user lacks permission. Your code should check the status code and respond appropriately.
import requests
response = requests.get(
"https://api.example.com/private",
auth=("alice", "wrong-password")
)
if response.status_code == 401:
print("Authentication failed. Check credentials.")
elif response.status_code == 403:
print("Authenticated but not allowed to access this resource.")
else:
response.raise_for_status()Do not silently ignore authentication failures. If you are building a client that retries requests, be careful not to retry on 401 with the same credentials; that will only waste resources. Instead, refresh the token or prompt the user for new credentials.
Security Considerations
Hardcoding credentials in source code is a common mistake. Even if the repository is private, credentials can leak through logs, screenshots, or dependency sharing. Use environment variables or a secrets manager.
import os
import requests
api_key = os.environ["API_KEY"]
headers = {"X-API-Key": api_key}
response = requests.get("https://api.example.com/data", headers=headers)For bearer tokens, the same principle applies. If you are writing a script that runs locally, you can read the token from a file with restricted permissions. In a server environment, use a secrets vault.
Another consideration is token expiry. Bearer tokens often expire after a short period. Your client should handle 401 responses by refreshing the token and retrying the request once. Basic auth credentials usually do not have the short expiry associated with bearer tokens, but they are long-lived secrets that should be rotated periodically.
When to Use Each Method
Basic auth is appropriate for internal tools or when the server has no other mechanism. It is simple but sends the username and password on every request. Use it only over HTTPS.
Bearer tokens are the standard for OAuth-based systems. They allow fine-grained scopes and short-lived sessions. The client does not normally need to inspect the token; the server decides whether it is valid. Use this when the API supports OAuth2 or returns a token from a login endpoint.
API keys are often used for simple access control on public APIs. They identify the calling application rather than a user. Use them when the service provides a key in its dashboard. If the service offers both header and query parameter options, choose the header to avoid logging the key.
In practice, many APIs support multiple methods. The decision is driven by the server's configuration, not by preference. Read the documentation and implement the method that the server expects. If you are designing an API, choose bearer tokens for user-level authentication and API keys for application-level access, and document the exact header names and formats.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.