Velamuvi AIAcademy

Lesson 8 of 12 · Data on the Wire

API Keys and Authentication

Learn authentication vs authorization, API keys, bearer tokens and the Authorization header, and how to keep keys secret with environment variables. With Python examples.

  • 8 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • The difference between authentication and authorization
  • What API keys and bearer tokens are
  • How to send a key in the Authorization header
  • How to keep keys out of your code with environment variables
  • What to do if a key leaks

Who are you, and what may you do?

Many APIs are free and open, like the weather API you have been using. But most serious APIs, including every AI model API, need to know who is calling. They need it to charge the right account, to stop abuse and to protect private data.

The two status codes match: 401 Unauthorized really means "not authenticated: I do not know who you are", and 403 Forbidden means "I know who you are, but you are not allowed to do this".

API keys

You usually create a key on the provider's website, in a page called something like "API keys" or "Developer settings". Treat it exactly like a password.

Sending a key: the Authorization header

Remember, HTTP is stateless, so the key must travel with every request. The most common place is the Authorization header:

Try it yourselfPython
api_key = "sk-test-1234567890abcdef"     # a fake key for this example

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}
print(headers)

Some APIs use their own header name instead, such as x-api-key: <key>. The API's documentation always tells you which one to use.

Here is httpbin's /bearer endpoint, which checks for a bearer token. First without one, then with a made-up token:

Try it yourselfPython
import requests

url = "https://httpbin.org/bearer"

response = requests.get(url, timeout=10)
print("No token:  ", response.status_code)

response = requests.get(url, headers={"Authorization": "Bearer my-practice-token"}, timeout=10)
print("With token:", response.status_code, response.json())

Keep keys out of your code

The biggest danger with API keys is putting them inside your code. Code gets copied, shared, pasted into chats and pushed to GitHub. Automated bots scan GitHub around the clock for leaked keys, and a leaked AI key can run up a large bill within hours.

Try it yourselfPython
import os

api_key = os.environ.get("WEATHER_API_KEY")

if api_key is None:
    print("WEATHER_API_KEY is not set. Add it to your environment first.")
else:
    print("Key loaded, starting with", api_key[:4])

os.environ.get() returns None when the variable does not exist, so your program can explain the problem instead of crashing. On your own computer you set the variable in the terminal before running Python:

# macOS and Linux
export WEATHER_API_KEY="your-key-here"

# Windows PowerShell
$env:WEATHER_API_KEY = "your-key-here"

To keep a .env file out of Git, add the line .env to your project's .gitignore file.

Encoding is not encryption

Some older APIs use basic authentication, which sends a username and password joined together and encoded with base64. It looks scrambled, but anyone can turn it back:

Try it yourselfPython
import base64

secret = "ada:my-password"
encoded = base64.b64encode(secret.encode()).decode()
print("Looks scrambled:", encoded)

decoded = base64.b64decode(encoded).decode()
print("Easily reversed:", decoded)

This is why keys and passwords must only travel over HTTPS, which really does encrypt the whole message.

Safe habits with keys

  • Keep keys in environment variables or a .env file, never in your code.
  • Never share a key in a screenshot, chat or support ticket.
  • When showing a key in logs, show only the first few characters.
  • Use separate keys for testing and for your live app, and give each key only the permissions it needs.
  • Never put a secret key inside a website's JavaScript or a phone app: users can read it. Call the API from your own server instead.
  • If a key leaks, revoke it on the provider's website at once and create a new one. Deleting it from your code is not enough, because Git keeps old versions.

Common mistakes

Practice exercise

Write the small helper every API project needs: a function that hides most of a key before it is printed.

Your solutionPython
# Write a function mask(key) for printing keys safely in logs.
# - Keep the first 4 and the last 4 characters.
# - Replace every character in between with *.
# - If the key has 8 characters or fewer, return all stars instead (same length).


print(mask("sk-live-1234567890abcdef"))
print(mask("abcd1234"))
print(mask("key-0000-9999"))

# Output must be exactly:
# sk-l****************cdef
# ********
# key-*****9999
Knowledge check

Where is the safest place to keep an API key for a Python script?

Summary

  • Authentication proves who you are. Authorization decides what you may do.
  • An API key identifies your account. Treat it like a password.
  • Keys usually travel in the Authorization: Bearer ... header, with every request, over HTTPS only.
  • Keep keys in environment variables or a .env file, never in code.
  • If a key leaks, revoke it immediately and create a new one.

You have finished the second module. Next: the requests library in detail.

Finished reading? Tick it off to track your progress.