When you call an API that requires authentication, you need to send credentials with each request. Adding authentication headers to Python requests is straightforward with the requests library. This guide shows you how to add common auth headers—Bearer tokens, Basic auth, and custom API keys—and how to handle them securely.
What You’ll Need
- Python 3.6 or newer installed
- The
requestslibrary installed (pip install requests) - An API endpoint that requires authentication
- Your credentials (API key, token, or username/password)
Step-by-Step
- Install the requests library if you haven’t already. Open your terminal and run
pip install requests. - Import the requests module at the top of your Python script:
import requests - Choose your authentication type. The most common are:
- Bearer token (used by OAuth 2.0 and many modern APIs)
- Basic auth (username and password)
- Custom API key (a simple header like
X-API-Key)
- Add a Bearer token header. Create a dictionary with the
Authorizationheader:headers = {"Authorization": "Bearer YOUR_TOKEN_HERE"}
Then pass it to the request:response = requests.get("https://api.example.com/data", headers=headers) - Use Basic auth. Instead of manually encoding, use the
authparameter:response = requests.get("https://api.example.com/data", auth=("username", "password"))
Requests will automatically encode it as a Basic auth header. - Add a custom API key header. Many APIs expect a header like
X-API-Keyorapi_key. Add it to your headers dict:headers = {"X-API-Key": "your_api_key_here"}
Then pass it as above. - Combine multiple headers. You can include other headers like
Content-Typein the same dict:headers = {"Authorization": "Bearer token", "Content-Type": "application/json"} - Make the request and check the response. Always check
response.status_code. A 200 or 201 means success. If you get 401 or 403, your auth is wrong or missing. - Handle the response. Use
response.json()if the API returns JSON, orresponse.textfor raw content.
Common Mistakes
- Hardcoding credentials in your script. This is a security risk. Use environment variables or a config file that is not committed to version control.
- Using the wrong header name. Some APIs use
Authorization, others useX-API-Key, still others usetoken. Check the API documentation. - Forgetting the word “Bearer” before the token. Most OAuth APIs require it exactly as shown.
- Not setting Content-Type when sending JSON. Many APIs require
Content-Type: application/jsonfor POST/PUT requests. - Mixing up Basic auth with Bearer. Basic auth uses the
authparameter, not a manual header (unless you want to encode it yourself, which is error-prone). - Using HTTP instead of HTTPS when sending credentials. Always use HTTPS to avoid exposing tokens in transit.
Tips
- Use environment variables for secrets. For example:
import os; token = os.environ.get("API_TOKEN") - Create a session if you make multiple requests. It reuses the connection and can store headers:
session = requests.Session()session.headers.update({"Authorization": "Bearer token"})
Then usesession.get(...). - Use a .env file with the
python-dotenvpackage to manage secrets locally. - Log the response status to debug quickly:
print(response.status_code) - Test with a simple endpoint like
https://httpbin.org/bearerto verify your headers work before hitting a real API.
Troubleshooting
If your request fails, follow these steps:
- Check the status code. 401 means unauthorized—your token is missing, invalid, or expired. 403 means forbidden—you don’t have permission even with valid auth.
- Verify the header format. Print your headers before sending:
print(headers). Make sure there are no typos or extra spaces. - Check the API documentation for the exact header name and value format. Some APIs use lowercase, some use a different scheme.
- Ensure your token hasn’t expired. Many tokens are valid for a limited time. Refresh it if needed.
- Test with curl to isolate the problem. For example:
curl -H "Authorization: Bearer token" https://api.example.com/data. If curl works but Python doesn’t, the issue is in your code. - Check for redirects. If the API redirects, the headers might be stripped. Use
allow_redirects=Falseto see what happens. - Check for proxies or firewalls that might block or modify your request.
Frequently Asked Questions
How do I add multiple authentication headers?
Just include all headers in the same dictionary. For example: headers = {"Authorization": "Bearer token", "X-API-Key": "key"}. Pass that dict to the request.
What is the difference between Basic auth and Bearer token?
Basic auth uses a username and password (or API key as username) encoded in base64. Bearer tokens are usually generated by an OAuth flow and are more secure because they can be revoked and have an expiry.
Can I use the auth parameter for Bearer tokens?
No, the auth parameter is for Basic auth. For Bearer tokens, you must set the Authorization header manually.
Is it safe to put tokens in the URL?
No. URLs are logged in server logs and browser history. Always put tokens in headers, never in the URL string.
How do I refresh an expired token automatically?
You can catch a 401 response and then call a refresh endpoint to get a new token, then retry the original request. This requires implementing a token refresh logic in your code.
What if the API expects the token in a cookie?
Some APIs use cookies for authentication. You can use a session and set the cookie via session.cookies.set("name", "value") or let the session handle it from a login response.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Campus Tech Innovation Hubs: What They Are
- Poco C51 Airtel Prepaid Locked Variant India?
- Jenkins vs GitHub Actions: Which CI/CD Fits Your Team?
- Turn Off Backup Encryption in iTunes?
- Shared VPS Hosting: Is It Better?
- Disk Defrag Pro: What It Does and Whether You Need It