3 Build and run your first complete service
The client sends JSON containing one text field and an Idempotency-Key header. A configured bearer token identifies its tenant. The API validates the input, inserts a job in a transaction, and returns HTTP 202 with an ID. A worker processes the job.
Outcome: submit a durable job and retrieve its result. Prerequisites: Python basics and terminal navigation. Environment: your laptop, Python 3.12 and uv, from the included ~/playground/automation-service directory. Cost: no paid API calls. Proof: API and worker tests are recorded in the companion verification report.
Start with the contract
The client sends JSON containing one text field and an Idempotency-Key header. A configured bearer token identifies its tenant. The API validates the input, inserts a job in a transaction, and returns HTTP 202 with an ID. A worker processes the job. The client polls GET /jobs/{id} until it succeeds or fails.
The same tenant and idempotency key identify the same request. Reusing the key with identical input returns the existing job. Reusing it with different input returns 409. Another tenant cannot read the first tenant's job, even with its UUID. This is authorization in the database query, not secrecy based on an unguessable identifier.
The sample result counts words and characters. It performs no external writes, sends no messages, and calls no AI provider. That makes worker retries safe while you learn the lifecycle.
Understand the files
| File | Responsibility |
|---|---|
app.py | Configuration, validation, API routes, persistence model, job claim/complete logic |
worker.py | Polling process and graceful stop handling |
mcp_adapter.py | Read-only local MCP access to jobs |
setup_lab.py | Creates fresh local credentials without printing them |
pyproject.toml and uv.lock | Runtime requirements and exact dependency resolution |
tests/ | Behavioral, access-control, concurrency and failure tests |
Dockerfile and compose.yaml | Container packaging and local PostgreSQL environment |
deploy/Caddyfile | HTTPS proxy recipe for a domain you control |
Read the source next to each lesson. The repository is the complete example; the PDF explains its decisions. Do not retype abbreviated excerpts and assume they contain the entire application.
Install and initialize
Install Python and uv using their official instructions if absent. Verify python3 --version and uv --version. Then, local terminal from the example directory:
setup_lab.py uses exclusive file creation: a second run refuses to overwrite .env. That is expected. Reuse the existing file for your current lab. Source only files you trust; sourcing a shell file executes its content. This generated file contains locally generated values, not downloaded instructions.
Alembic creates or upgrades the versioned schema; the seed command installs the generated tenant credential. Review Chapter 15 before upgrading an existing v2 database. Uvicorn starts the HTTP process and keeps that terminal occupied. Leave it running. 127.0.0.1 keeps the local exercise off the public network.
In terminal 2, enter the same example directory, load the same .env, and start the worker:
In terminal 3, load .env again and submit a job:
Copy the returned UUID into JOB_ID and read it:
Expect queued briefly, then succeeded with words: 3 and characters: 20. If it remains queued, verify that the worker is running and both processes use the same database URL and working directory. A relative SQLite path in different directories means different databases.
Shell expansion puts a bearer value into curl's arguments while it runs. Use only the disposable lab token here. For sensitive operational automation prefer a client that reads secrets internally, or a protected curl configuration supplied through a file descriptor; avoid command tracing and shared terminal recordings.
Explain the implementation
JobInput rejects unknown fields and limits text length. The middleware bounds the request body to 64 KiB. The token map is configured by the operator, so the request cannot choose its tenant. The unique database constraint enforces (tenant, request_key) even when two requests arrive concurrently. A Python-only check before insertion would have a race.
The API returns a response model containing only the ID, status, attempts, and result. It does not return stored input, tenant IDs, or credential information. Readiness queries the jobs table to detect a missing schema or unavailable database; liveness does not.
The database-backed limiter coordinates120 authenticated requests per minute per tenant across API processes. Chapter 15 explains fixed-window bursts, daily admission and retention. Edge controls are still required for unauthenticated abuse.
Run the tests
Tests create disposable databases and generated credentials. They do not need your live .env values. Read a failed assertion before editing the application: it tells you which contract changed. A successful test run proves the tested scenarios, not all possible inputs or workloads.
Failure exercises
Stop only the lab worker with Ctrl-C. Submit a new key, confirm the job remains queued, restart the worker, and confirm completion. Repeat the original submission and check that the ID remains unchanged. Change its text while retaining its key and expect a conflict. Remove the Authorization header and expect 401.
Create a second tenant token in a disposable configuration and prove its GET request for the first tenant's job returns 404. Never accept a client-supplied tenant field as proof of identity. Extend the test suite before changing the permission logic.
Exit and cleanup
You pass when you can explain why 202 precedes completion, why duplicate submissions do not create duplicate jobs, and why persistence survives a worker restart. Stop your API and worker with Ctrl-C. The SQLite file remains for your next session. Keep .env private and excluded from source control. Deleting that file or database is optional lab cleanup, not a required repair step.
Known limits: this reference app adds API login, scoped credentials, monitoring examples and pre-issued JWT remote MCP. It has no billing, browser UI, arbitrary code execution or complete OAuth authorization server. See Chapters 15–18 for implemented boundaries and remaining deployment work.
Lock in what you just learned (3 quick questions)
/health endpoint verify to be useful without causing cascading outages?