Build real applications. Verify every step.
In the last post we made a working API call. The script loaded an API key from the environment and sent a request. That was the minimum. Today we treat the key the way a real application must treat it: as a secret that can leak, rotate, expire, or be revoked, and as a value that must reach the process without ever appearing in source control, screenshots, or log files.
I learned this the hard way years ago. I had a tidy little Python script that worked perfectly on my laptop. I pushed it to a private repo “just for backup.” A week later I rotated the key because the usage dashboard looked odd. The old key still worked for another forty-eight hours. By the time I noticed, the key had been scraped from the git history of a machine I no longer controlled. No drama, no public leak, just an avoidable mess and a few hours of cleanup. Since then I treat every new model integration the same way: the key never lives in the code, and the loading path is explicit and testable.
This post covers the practical patterns I use for GPT-6.1 Sol (and any similar API) in local development, FastAPI services, Docker, and simple deployment environments. No cloud-vendor lock-in, no elaborate secret managers yet—just solid habits that scale when you later add them.
Why Environment Variables Are the Default
An API key is a bearer credential. Anyone who possesses it can spend your quota and, depending on the account permissions, potentially do more. The safest place for it in most application processes is an environment variable that is injected at runtime and never written to disk by the application itself.
Environment variables give you three immediate advantages:
The value never appears in the source tree.
Different environments (local, staging, production) can supply different keys without code changes.
Process managers, container runtimes, and CI systems already know how to inject them.
They are not perfect. A compromised process can still read its own environment. Logging libraries can accidentally dump os.environ. But they are the right starting point, and every more advanced secret system (Vault, cloud secret managers, sealed secrets) ultimately delivers the value into the process as an environment variable or a short-lived file.
Local Development: The .env File Pattern

For day-to-day work I use a .env file that is explicitly ignored by git.
Create .env in the project root (never commit it).
Add the key:
Bash
OPENAI_API_KEY=sk-...Add .env to .gitignore if it is not already there.
Load it only in development.
A minimal loader that stays out of production code looks like this:
Python
import os
from pathlib import Path
def load_dotenv_if_present() -> None:
env_path = Path(".env")
if not env_path.is_file():
return
for line in env_path.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
key = key.strip()
value = value.strip().strip("'").strip('"')
if key and key not in os.environ: # do not override existing vars
os.environ[key] = valueCall it once at startup in your local scripts or in the FastAPI lifespan when ENV=development. In any other environment the function does nothing, so production never depends on a .env file existing on disk.
I deliberately avoid the popular python-dotenv package in the smallest examples so the loading logic stays visible. Once the team agrees on the pattern, switching to the library is fine.
Reading the Key Safely in Application Code
Never do this:
Python
client = OpenAI(api_key="sk-...") # hard-codedDo this:
Python
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise RuntimeError(
"OPENAI_API_KEY is not set. "
"Export it in your shell or provide it via the process environment."
)
client = OpenAI(api_key=api_key)The explicit check turns a silent None into an immediate, readable failure. When this error appears in a container log or a CI run, the fix is obvious.
I also keep the variable name consistent across every project: OPENAI_API_KEY. If a future client library expects a different name, I map it once at the edge rather than scattering aliases.
FastAPI Integration
In a FastAPI service the key should be read once at startup and stored on the application state or in a dependency that cannot be accidentally logged.
Python
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from openai import OpenAI
@asynccontextmanager
async def lifespan(app: FastAPI):
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise RuntimeError("OPENAI_API_KEY environment variable is required")
app.state.openai_client = OpenAI(api_key=api_key)
yield
# no explicit close needed for the official client in current versions
app = FastAPI(lifespan=lifespan)
def get_openai_client(request: Request) -> OpenAI:
return request.app.state.openai_clientRoutes then depend on get_openai_client instead of creating their own client. This gives you a single place to add timeouts, custom headers, or logging wrappers later.
Docker and Process Managers

When you move to containers, pass the key at runtime:
Bash
docker run --rm -e OPENAI_API_KEY="$OPENAI_API_KEY" my-imageOr in Compose:
YAML
services:
api:
image: my-image
environment:
OPENAI_API_KEY: ${OPENAI_API_KEY}Never bake the key into the image with an ENV instruction in the Dockerfile. Images get cached, pushed, and sometimes shared. The key must arrive after the image is built.
The same rule applies to systemd units, Kubernetes secrets (which ultimately become environment variables or mounted files), and any PaaS that injects configuration.
Rotation and Least Privilege
Treat the key as rotatable from day one.
Create a dedicated key for the application rather than reusing a personal key.
Give it the minimum permissions the model and endpoints require.
Store the creation date and a short note about where it is used.
When you rotate, deploy the new value first, then revoke the old one after a short overlap window.
I keep a simple text file (outside the repo) that lists key identifiers, creation dates, and the services that use them. It is not sophisticated, but it prevents the “which key is this?” conversation three months later.
What Never to Do
Commit a key to git, even in a private repository.
Log the value of OPENAI_API_KEY or any variable that contains it.
Put the key in a frontend environment variable or any code that ships to a browser.
Share keys in chat, email, or screenshots.
Rely on a single long-lived key for both local development and production.
If you need to debug a request, log a masked version (sk-...abcd) or simply log that a key was present. Never log the full secret.
A Quick Verification Checklist for Keys
Before you call the model for the first time in a new environment, confirm:
OPENAI_API_KEY is present in the process environment.
The value starts with the expected prefix and has a plausible length.
A test request succeeds and returns the model you expect.
Revoking or rotating the key in the dashboard produces an authentication error on the next request.
No .env file, Docker layer, or CI log contains the plaintext key.
These five checks take two minutes and catch the majority of key-related failures before they reach users.
Looking Ahead
In the next post we will read and log a full GPT-6.1 Sol response, including the fields that matter for cost and debugging. The key-loading pattern from this article stays unchanged. Once the secret is handled correctly, everything else becomes ordinary application data.
Until then, put the key in the environment, keep it out of the repository, and make the absence of the key a loud, early failure. That single discipline removes an entire class of production surprises.
Build real applications. Verify every step.