API keys and environment variables
Many real programs need to talk to external services, and those services usually need to know who is calling them. This lesson exists to show how Python programs authenticate themselves safely when making HTTP requests. We focus on keeping secrets out of source code while still making them available at runtime.
Why API keys are required
An API key is a shared secret that identifies a client to an external service. It allows the service to track usage, apply limits, and control access. From our program’s point of view, an API key is just a value that must be supplied with a request.
The important idea is not the format of the key, but how it is handled. API keys should never be hard-coded into a Python file that might be shared, committed, or deployed.
Storing secrets outside of source code
Instead of embedding secrets in code, we store them in environment variables. An environment variable is a value managed by the operating system and made available to programs at runtime.
This keeps secrets separate from source files and allows different keys to be used in different environments without changing code.
A typical way to define an environment variable from the command line looks like this:
export PLANET_API_KEY="example-secret-value"
Reading environment variables in Python
Python exposes environment variables through the standard library. Once defined, an environment variable can be read like any other configuration value.
Here is a minimal example of loading an API key into a Python program:
import os
api_key = os.environ.get("PLANET_API_KEY")
At this point, api_key holds the secret value and can be passed to other parts of the program.
Supplying API keys in HTTP requests
Most APIs expect keys to be supplied as HTTP headers or query parameters. The exact format depends on the service, but the pattern is consistent.
Here is a representative example using a request header:
import os
import requests
api_key = os.environ.get("PLANET_API_KEY")
headers = {
"Authorization": f"Bearer {api_key}"
}
response = requests.get(
"https://api.example.com/planets",
headers=headers
)
The request library handles the mechanics, while the API key is injected from the environment at runtime.
Verifying that credentials are loaded correctly
Before relying on an API key, it is common to confirm that it is present. This is usually done with a simple check at program startup.
A minimal verification looks like this:
import os
api_key = os.environ.get("PLANET_API_KEY")
print(api_key is not None)
This confirms that the program can see the credential without revealing its value.
Conclusion
We now know why API keys exist, how to keep them out of source code, and how to supply them safely in HTTP requests. With this pattern in place, our programs can authenticate to external services without exposing sensitive information.