Back to Blog
Python

Python Requests Authentication: Bearer Token, API Key, and Basic Auth

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, with...

pythonrequestsauthenticationbearer-tokenapi-keybasic-auth
Illustration of Python requests authentication methods including bearer token, API key, and basic auth.

python requests authentication bearer token api key and basic auth requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

When calling a REST API from Python, the requests library is the standard tool, but the way you pass credentials depends on the authentication scheme the server expects. This article covers the three most common methods—basic auth, bearer token, and API key—and shows exactly how to implement each with requests. The focus is on practical syntax and behavior, so you can adapt the examples to your own API client.

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 encodes the credentials and sets the Authorization header to Basic base64(username:password).

import requests response = requests.get( "https://api.example.com/resource", auth=("alice", "secret-password") )

If you need more control, you can 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 expire, 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 token is opaque to the client, so you do not need to parse it. 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.

python requests authentication bearer token api key and basi | RYUSLOG DEV