Most FDE code is not a grand system; it is the glue that makes a customer's world work with yours: a script that pulls records nightly, a CLI that validates their data, a small service that exposes an internal system to an AI agent. That code has to be written fast, run reliably on machines you do not control, and be handed to someone else. This lesson covers the Python habits that make that possible: reproducible environments, configuration from the environment, HTTP clients that behave behind proxies, retries and idempotency, logs someone else can read, tests, and packaging that installs cleanly.
- Create reproducible Python projects with locked dependencies
- Load configuration and secrets from the environment, never from code
- Write HTTP clients with timeouts, retries with backoff, and proxy and CA support
- Produce structured logs and clear errors that a customer team can act on
- Test and package a tool so it installs and runs the same everywhere
Reproducible environments
"It works on my machine" is fatal at a customer site. Every project gets a pyproject.toml, a lock file and a pinned Python version. Tools such as uv create the virtual environment, resolve and lock dependencies, and run commands inside the environment in one step; pip with a requirements file and hashes works too. What matters is that a colleague or the customer can rebuild exactly what you ran.
uv init claims-sync && cd claims-sync
uv add httpx
uv add --dev pytest ruff
uv run python -c "import httpx; print(httpx.__version__)"
uv lock # commit pyproject.toml and uv.lock together- Pin the Python version you test on; customers' servers often have older system Pythons, which is one reason to ship a container or a self-contained environment.
- Keep dependencies few. Every package is something the customer's security team may ask about.
- Run a formatter and linter (ruff) and type hints from the first commit; code you hand over should look intentional.
Configuration from the environment
The same code must run on your laptop, the customer's staging server and production, against different URLs and credentials. Follow the twelve-factor rule: configuration comes from environment variables (or files mounted by the platform), with validation at start-up so a missing value fails immediately and clearly, not on the first nightly run.
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
api_url: str
api_token: str
batch_size: int = 500
timeout_s: float = 30.0
def load_config() -> Config:
missing = [k for k in ("CLAIMS_API_URL", "CLAIMS_API_TOKEN") if not os.environ.get(k)]
if missing:
raise SystemExit(f"missing required environment variables: {', '.join(missing)}")
return Config(
api_url=os.environ["CLAIMS_API_URL"].rstrip("/"),
api_token=os.environ["CLAIMS_API_TOKEN"],
batch_size=int(os.environ.get("CLAIMS_BATCH_SIZE", "500")),
timeout_s=float(os.environ.get("CLAIMS_TIMEOUT_S", "30")),
)Never commit tokens, never print them, and never put them in command-line arguments (they show up in process lists and shell history). Read them from the environment or a secrets file the platform mounts.
HTTP clients that survive enterprise networks
Calls to customer APIs fail in ordinary ways: timeouts, 429 rate limits, 502s from a load balancer during a deploy. Your client must set timeouts, retry the failures that are safe to retry with exponential backoff and jitter, and give up with a clear error. It must also honour the customer's proxy and private certificate authority: httpx reads HTTPS_PROXY, NO_PROXY and SSL_CERT_FILE from the environment by default.
import random
import time
import httpx
RETRYABLE = {429, 500, 502, 503, 504}
def get_json(client: httpx.Client, path: str, attempts: int = 5) -> dict:
for attempt in range(1, attempts + 1):
try:
r = client.get(path)
if r.status_code not in RETRYABLE:
r.raise_for_status()
return r.json()
reason = f"HTTP {r.status_code}"
except (httpx.TimeoutException, httpx.TransportError) as exc:
reason = type(exc).__name__
if attempt == attempts:
raise RuntimeError(f"GET {path} failed after {attempts} attempts: {reason}")
time.sleep(min(30, 2 ** attempt) * random.uniform(0.5, 1.0))
client = httpx.Client(base_url="https://claims.internal.example",
headers={"Authorization": "Bearer TOKEN_FROM_ENV"},
timeout=httpx.Timeout(30.0, connect=5.0))Retrying a GET is safe. Retrying a POST that creates a record can create it twice. Make writes idempotent: send an idempotency key the server deduplicates on, or upsert by a natural key, so a retry after a timeout does no harm. The integration lesson goes deeper.
Logs and errors for someone else
The person reading your logs at 3 a.m. may be the customer's operator who has never seen your code. Log one event per line, with a timestamp, a level, what happened, and identifiers (batch, record count, request ID), and avoid logging personal data or secrets. JSON lines are easy for any log system to parse.
import json
import logging
import sys
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
payload = {"ts": self.formatTime(record), "level": record.levelname,
"msg": record.getMessage(), **getattr(record, "ctx", {})}
return json.dumps(payload)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
log = logging.getLogger("claims_sync")
log.addHandler(handler)
log.setLevel(logging.INFO)
log.info("batch synced", extra={"ctx": {"batch": 12, "records": 500, "seconds": 4.2}})- Exit with a non-zero status on failure so schedulers and monitoring notice.
- Write error messages that say what to do: "CLAIMS_API_TOKEN expired or invalid (HTTP 401): rotate it in the vault", not a stack trace alone.
- Add a
--dry-runflag to anything that writes: customers love being able to see what would change first.
Tests and packaging for handover
You do not need exhaustive tests for a pilot, but you need enough that the next person can change the code without fear: unit tests for parsing and transformation logic, and a test that runs the client against a fake server. httpx's MockTransport lets you test retry logic without a network.
import httpx
from claims_sync.client import get_json
def test_retries_then_succeeds(monkeypatch):
monkeypatch.setattr("time.sleep", lambda s: None)
calls = {"n": 0}
def handler(request):
calls["n"] += 1
if calls["n"] < 3:
return httpx.Response(503)
return httpx.Response(200, json={"ok": True})
client = httpx.Client(base_url="https://x", transport=httpx.MockTransport(handler))
assert get_json(client, "/health") == {"ok": True}
assert calls["n"] == 3Package the tool so it installs one way everywhere: a wheel with a console-script entry point for Python environments, or, more often at customer sites, a container image with the Python version and dependencies baked in. Include a README with prerequisites, configuration variables, how to run, how to test, and how to roll back.