Skip to Content
Course content

276: Working with API Authentication and Headers

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're trying to get into a high-security office building. You can't just walk through the front door; there's a security guard who needs to know who you are and if you're allowed to be there. You don't just shout your name from the sidewalk—that would be insecure. Instead, you walk up and show your employee badge. The badge itself is your credential, and the act of holding it up for the guard to see is the method of delivery.

In the world of APIs, authentication works exactly the same way. The server is the security guard. Your API key or Token is the badge. And the HTTP Headers are the specific way you "hold up" that badge so the server recognizes it. If you put your badge in your pocket (forget the header) or hold it upside down (wrong header key), the guard is going to give you a 401 Unauthorized error and send you packing.

Packing Your Request Headers

When we use the requests library in Python, we don't just send a URL. We can send a dictionary of headers. Think of headers as the "metadata" of your request—info about the request that isn't the actual data you're sending or receiving. While some APIs let you put a key directly in the URL (which I strongly advise against because URLs get logged in plain text), the professional way is to use the headers parameter.

import requests

# This is our "badge"
api_key = "your_secret_api_key_here"

# We package it into a dictionary
# Most APIs expect a specific key name, like 'X-API-Key' or 'Authorization'
my_headers = {
    "X-API-Key": api_key,
    "Content-Type": "application/json",
    "User-Agent": "MyPythonApp/1.0"
}

response = requests.get("https://api.example.com/v1/data", headers=my_headers)
print(response.status_code)

Bearer Tokens and the Authorization Header

You'll notice a lot of modern APIs (like GitHub, Stripe, or Twitter) don't use a custom header like X-API-Key. Instead, they use a standard called Bearer Authentication. The name is literal: the server grants access to the "bearer" of this token.

The catch here is that the value in the header must start with the word Bearer followed by a space. If you forget that word, the server will reject the token even if the string of characters is perfectly correct. I've wasted an hour of my life debugging this exact mistake, so don't be like me.

import requests

token = "ghp_123456789abcdefghijk" # Example GitHub token

# Note the 'Bearer ' prefix inside the string
headers = {
    "Authorization": f"Bearer {token}",
    "Accept": "application/vnd.github+json"
}

response = requests.get("https://api.github.com/user", headers=headers)
print(response.json())

Keeping Your Keys Out of Version Control

Here is a piece of professional advice: never, ever hardcode your API keys directly into your Python file. If you push that code to GitHub, bots will scrape your key within seconds. I've seen people lose thousands of dollars in cloud credits because they committed an AWS key to a public repo.

Instead, use environment variables. You store the key in your operating system or a .env file, and Python reads it at runtime. It keeps your credentials separate from your logic.

import os
import requests

# Pull the key from the environment instead of typing it here
api_key = os.getenv("MY_API_SERVICE_KEY")

if not api_key:
    raise ValueError("No API key found in environment variables!")

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



📋 Practical Task

Exercise: Fetching Your GitHub Profile Data via Personal Access Token

Your goal is to write a script that securely fetches your own GitHub profile information using a Personal Access Token (PAT). This will require you to implement both header-based authentication and environment variable handling.

  • Setup: Generate a "Fine-grained personal access token" (or a classic token) from your GitHub Developer Settings with read:user permissions.
  • Environment: Set an environment variable on your system named GITHUB_TOKEN and assign your token as the value.
  • The Code:
    • Use os.getenv to retrieve the token.
    • Create a headers dictionary using the Authorization: Bearer <token> format.
    • Perform a GET request to https://api.github.com/user.
    • Print only your GitHub login name and your public_repos count from the JSON response.

Hint: If you get a 401 error, double-check that you included the word "Bearer" followed by a space before your token in the header string.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.