Bearer Token Authentication Headers Rules

🏷️ APIs and HTTP Requests / Passing Parameters and Headers

🧠 Context Introduction

When working with APIs that require authentication, Bearer Token Authentication is one of the most common and secure methods used. Instead of sending a username and password with every request, you obtain a token once (usually from a login endpoint) and then include that token in the headers of all subsequent requests. This token acts like a digital key — as long as you have it, the server knows who you are and whether you're allowed to access the data.

For engineers new to Python and API interactions, understanding how to properly format and attach a Bearer Token in your request headers is essential. A small mistake — like missing the word Bearer or forgetting a space — will result in an immediate 401 Unauthorized response.


🔑 What is a Bearer Token?

  • A Bearer Token is a string (often a long, random-looking sequence of characters) issued by an authentication server.
  • It is placed in the Authorization header of an HTTP request.
  • The word Bearer (capital B) must precede the token, separated by a single space.
  • The server validates the token and grants or denies access based on its validity and permissions.

⚙️ The Correct Header Format

The Authorization header for Bearer Token authentication must follow this exact structure:

  • Header Name: Authorization
  • Header Value: Bearer <your_token_here>

Example of a correctly formatted header: - Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c


🛠️ How to Attach the Bearer Token in Python

When making HTTP requests in Python (using the requests library), you create a dictionary for your headers and include the Authorization key.

Step-by-step approach:

  1. Store your token in a variable (e.g., my_token).
  2. Create a headers dictionary with the key "Authorization".
  3. Set the value to the string "Bearer " followed by your token variable.
  4. Pass the headers dictionary to the headers parameter of your request method (like get() or post()).

Example of building the headers dictionary: - my_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." - headers = {"Authorization": f"Bearer {my_token}"}

Example of using it in a GET request: - response = requests.get("https://api.example.com/data", headers=headers)


🕵️ Common Mistakes to Avoid

Even experienced engineers make these errors. Watch out for:

  • Missing the word "Bearer": Sending just the token without the prefix will be rejected.
  • Incorrect capitalization: bearer (lowercase) or BEARER (uppercase) may not be accepted by all servers. Always use Bearer with a capital B.
  • Missing or extra spaces: Bearer<token> (no space) or Bearer <token> (two spaces) will fail.
  • Storing tokens in plain text in code: For production, use environment variables or secret managers.

📊 Comparison Table: Correct vs. Incorrect Headers

Scenario Header Value Result
✅ Correct Authorization: Bearer eyJhbGciOiJIUzI1NiIs... Request succeeds (200 OK)
❌ Missing Bearer Authorization: eyJhbGciOiJIUzI1NiIs... 401 Unauthorized
❌ Wrong case Authorization: bearer eyJhbGciOiJIUzI1NiIs... 401 Unauthorized (most servers)
❌ No space Authorization: BearereyJhbGciOiJIUzI1NiIs... 401 Unauthorized
❌ Double space Authorization: Bearer eyJhbGciOiJIUzI1NiIs... 401 Unauthorized

📝 Practical Tips for Engineers

  • Always test with a simple GET request first to verify your token and header format are correct before building complex logic.
  • Use environment variables to store tokens securely. In Python, you can access them with os.getenv("API_TOKEN").
  • Check token expiration: Bearer tokens often expire after a set time. If you start getting 401 errors suddenly, the token may have expired and needs to be refreshed.
  • Log headers cautiously: Never print or log the full Authorization header in production logs, as it exposes your token. Log only the status code or a masked version.

✅ Summary

Bearer Token Authentication is straightforward once you understand the header format rules. Remember these three key points:

  • The header name is always Authorization.
  • The value always starts with Bearer (capital B) followed by a space and then your token.
  • In Python, build your headers as a dictionary and pass it to the request method.

Mastering this pattern will allow you to securely interact with most modern REST APIs, from cloud services to internal microservices.


Bearer Token Authentication sends a token in the HTTP request header to verify identity without requiring a username and password on every request.

🔑 Example 1: Basic Bearer Token Header Structure

This shows the simplest format of a Bearer Token header using a dictionary.

headers = {
    "Authorization": "Bearer abc123token"
}

📤 Output: {'Authorization': 'Bearer abc123token'}


🔑 Example 2: Sending a Bearer Token with a GET Request

This demonstrates how to attach a Bearer Token to a GET request using the requests library.

import requests

token = "my_secret_token_456"
headers = {
    "Authorization": f"Bearer {token}"
}
response = requests.get("https://api.example.com/data", headers=headers)

📤 Output: (if token is valid)


🔑 Example 3: Bearer Token with a POST Request and JSON Body

This shows sending a Bearer Token in a POST request that also includes JSON data.

import requests

token = "eyJhbGciOiJIUzI1NiJ9.token"
headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}
payload = {"name": "sensor_1", "value": 42}
response = requests.post("https://api.example.com/upload", json=payload, headers=headers)

📤 Output: (if created successfully)


🔑 Example 4: Handling Token Expiration with a Refresh

This demonstrates checking for a 401 status and refreshing the token before retrying.

import requests

def get_data_with_token(token):
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get("https://api.example.com/secure", headers=headers)
    if response.status_code == 401:
        new_token = refresh_token()
        headers = {"Authorization": f"Bearer {new_token}"}
        response = requests.get("https://api.example.com/secure", headers=headers)
    return response

def refresh_token():
    return "new_valid_token_789"

result = get_data_with_token("expired_token_123")

📤 Output: (after refresh succeeds)


🔑 Example 5: Storing Bearer Token in Environment Variable

This shows a practical pattern for engineers to keep tokens out of source code using environment variables.

import os
import requests

token = os.environ.get("API_BEARER_TOKEN")
if token is None:
    raise ValueError("API_BEARER_TOKEN environment variable not set")

headers = {
    "Authorization": f"Bearer {token}"
}
response = requests.get("https://api.example.com/status", headers=headers)

📤 Output: (if token exists and is valid)


Comparison Table: Bearer Token Header Rules

Rule Description Example
Format Always use "Bearer " followed by the token "Authorization": "Bearer abc123"
Placement Token goes in the Authorization header headers["Authorization"]
Case sensitivity "Bearer" must be capitalized "Bearer" not "bearer"
Token storage Never hardcode — use environment variables os.environ.get("TOKEN")
Expiration handling Check for 401 status and refresh if needed if response.status_code == 401:

🧠 Context Introduction

When working with APIs that require authentication, Bearer Token Authentication is one of the most common and secure methods used. Instead of sending a username and password with every request, you obtain a token once (usually from a login endpoint) and then include that token in the headers of all subsequent requests. This token acts like a digital key — as long as you have it, the server knows who you are and whether you're allowed to access the data.

For engineers new to Python and API interactions, understanding how to properly format and attach a Bearer Token in your request headers is essential. A small mistake — like missing the word Bearer or forgetting a space — will result in an immediate 401 Unauthorized response.


🔑 What is a Bearer Token?

  • A Bearer Token is a string (often a long, random-looking sequence of characters) issued by an authentication server.
  • It is placed in the Authorization header of an HTTP request.
  • The word Bearer (capital B) must precede the token, separated by a single space.
  • The server validates the token and grants or denies access based on its validity and permissions.

⚙️ The Correct Header Format

The Authorization header for Bearer Token authentication must follow this exact structure:

  • Header Name: Authorization
  • Header Value: Bearer <your_token_here>

Example of a correctly formatted header: - Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c


🛠️ How to Attach the Bearer Token in Python

When making HTTP requests in Python (using the requests library), you create a dictionary for your headers and include the Authorization key.

Step-by-step approach:

  1. Store your token in a variable (e.g., my_token).
  2. Create a headers dictionary with the key "Authorization".
  3. Set the value to the string "Bearer " followed by your token variable.
  4. Pass the headers dictionary to the headers parameter of your request method (like get() or post()).

Example of building the headers dictionary: - my_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." - headers = {"Authorization": f"Bearer {my_token}"}

Example of using it in a GET request: - response = requests.get("https://api.example.com/data", headers=headers)


🕵️ Common Mistakes to Avoid

Even experienced engineers make these errors. Watch out for:

  • Missing the word "Bearer": Sending just the token without the prefix will be rejected.
  • Incorrect capitalization: bearer (lowercase) or BEARER (uppercase) may not be accepted by all servers. Always use Bearer with a capital B.
  • Missing or extra spaces: Bearer<token> (no space) or Bearer <token> (two spaces) will fail.
  • Storing tokens in plain text in code: For production, use environment variables or secret managers.

📊 Comparison Table: Correct vs. Incorrect Headers

Scenario Header Value Result
✅ Correct Authorization: Bearer eyJhbGciOiJIUzI1NiIs... Request succeeds (200 OK)
❌ Missing Bearer Authorization: eyJhbGciOiJIUzI1NiIs... 401 Unauthorized
❌ Wrong case Authorization: bearer eyJhbGciOiJIUzI1NiIs... 401 Unauthorized (most servers)
❌ No space Authorization: BearereyJhbGciOiJIUzI1NiIs... 401 Unauthorized
❌ Double space Authorization: Bearer eyJhbGciOiJIUzI1NiIs... 401 Unauthorized

📝 Practical Tips for Engineers

  • Always test with a simple GET request first to verify your token and header format are correct before building complex logic.
  • Use environment variables to store tokens securely. In Python, you can access them with os.getenv("API_TOKEN").
  • Check token expiration: Bearer tokens often expire after a set time. If you start getting 401 errors suddenly, the token may have expired and needs to be refreshed.
  • Log headers cautiously: Never print or log the full Authorization header in production logs, as it exposes your token. Log only the status code or a masked version.

✅ Summary

Bearer Token Authentication is straightforward once you understand the header format rules. Remember these three key points:

  • The header name is always Authorization.
  • The value always starts with Bearer (capital B) followed by a space and then your token.
  • In Python, build your headers as a dictionary and pass it to the request method.

Mastering this pattern will allow you to securely interact with most modern REST APIs, from cloud services to internal microservices.

Interactive Views

You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.

Bearer Token Authentication sends a token in the HTTP request header to verify identity without requiring a username and password on every request.

🔑 Example 1: Basic Bearer Token Header Structure

This shows the simplest format of a Bearer Token header using a dictionary.

headers = {
    "Authorization": "Bearer abc123token"
}

📤 Output: {'Authorization': 'Bearer abc123token'}


🔑 Example 2: Sending a Bearer Token with a GET Request

This demonstrates how to attach a Bearer Token to a GET request using the requests library.

import requests

token = "my_secret_token_456"
headers = {
    "Authorization": f"Bearer {token}"
}
response = requests.get("https://api.example.com/data", headers=headers)

📤 Output: (if token is valid)


🔑 Example 3: Bearer Token with a POST Request and JSON Body

This shows sending a Bearer Token in a POST request that also includes JSON data.

import requests

token = "eyJhbGciOiJIUzI1NiJ9.token"
headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}
payload = {"name": "sensor_1", "value": 42}
response = requests.post("https://api.example.com/upload", json=payload, headers=headers)

📤 Output: (if created successfully)


🔑 Example 4: Handling Token Expiration with a Refresh

This demonstrates checking for a 401 status and refreshing the token before retrying.

import requests

def get_data_with_token(token):
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get("https://api.example.com/secure", headers=headers)
    if response.status_code == 401:
        new_token = refresh_token()
        headers = {"Authorization": f"Bearer {new_token}"}
        response = requests.get("https://api.example.com/secure", headers=headers)
    return response

def refresh_token():
    return "new_valid_token_789"

result = get_data_with_token("expired_token_123")

📤 Output: (after refresh succeeds)


🔑 Example 5: Storing Bearer Token in Environment Variable

This shows a practical pattern for engineers to keep tokens out of source code using environment variables.

import os
import requests

token = os.environ.get("API_BEARER_TOKEN")
if token is None:
    raise ValueError("API_BEARER_TOKEN environment variable not set")

headers = {
    "Authorization": f"Bearer {token}"
}
response = requests.get("https://api.example.com/status", headers=headers)

📤 Output: (if token exists and is valid)


Comparison Table: Bearer Token Header Rules

Rule Description Example
Format Always use "Bearer " followed by the token "Authorization": "Bearer abc123"
Placement Token goes in the Authorization header headers["Authorization"]
Case sensitivity "Bearer" must be capitalized "Bearer" not "bearer"
Token storage Never hardcode — use environment variables os.environ.get("TOKEN")
Expiration handling Check for 401 status and refresh if needed if response.status_code == 401: