A small web service with FastAPI
Build the service you will containerise and deploy in later modules.
By Invicly Tech, , in Full DevOps with Python. About 12 minutes to read.
In short
FastAPI builds web APIs from plain Python functions with type hints. Pydantic models validate requests automatically, and this small service is what you will containerise and deploy later.
Explained simply
FastAPI is a Python framework for building web APIs. You write normal functions, put a decorator like @app.get("/health") above them, and FastAPI turns each one into a URL that returns JSON. It is fast, popular, and small enough to learn in an afternoon.
Its trick is type hints. When you write qty: int, FastAPI checks that the client really sent a number. Bad input gets an automatic, detailed error with status 422, so your function only ever sees clean data. Pydantic, a data validation library, does this checking.
FastAPI also writes documentation for you. Open /docs in a browser and you get an interactive page listing every endpoint, where you can try requests without any extra tools.
In this path, this app is what you will ship. So it needs what every production service needs: a health check that load balancers and Kubernetes can call, settings read from environment variables, and tests. Get those right now and Docker and Kubernetes become much easier later.
Press Play on a diagram to walk through it one step at a time.
- Client to FastAPI: POST /items with JSON body1POST /items with JSON body
- FastAPI to Pydantic: Validate body against Item model2Validate body against Item model
- Pydantic to FastAPI: Valid Item, or errors3Valid Item, or errors
- FastAPI to Client: 422 with details if invalid4422 with details if invalid
- FastAPI to Route function: Call create_item(item)5Call create_item(item)
- Route function to FastAPI: Return dict6Return dict
- FastAPI to Client: 201 Created with JSON7201 Created with JSON
- Path
- item_id: int
- Declared in /items/{item_id}
- Query
- limit: int = 10
- From ?limit=10, optional with a default
- Body
- item: Item
- JSON parsed into a Pydantic model
- Dependencies
- Header() for headers
- Depends(get_settings) for shared objects
- Step 1Container starts
Env vars set by Docker or Kubernetes
- Step 2Settings() created
Reads APP_ variables
- Step 3Validate types
Fail fast if missing or wrong
- Step 4Serve requests
Routes get settings via Depends
In depth
From the socket to your function
FastAPI does not listen on a port itself; a server such as uvicorn does that. uvicorn speaks ASGI (Asynchronous Server Gateway Interface), the standard way async Python web servers talk to apps. FastAPI is built on Starlette, which provides routing and the request and response objects; FastAPI adds validation, dependency injection and the docs.
Plain def endpoints run in a thread pool, so blocking calls inside them (a requests call, a slow file read) are fine. async def endpoints run directly on the event loop, which handles many concurrent requests efficiently, but one blocking call inside them freezes every request on that worker. Rule of thumb: use async def only when everything slow inside it is awaited (httpx.AsyncClient, asyncpg); otherwise use def.
uvicorn app.main:app --host 0.0.0.0 --port 8000 starts it. In a container, 0.0.0.0 is required, because 127.0.0.1 is not reachable from outside the container.
- 1Client
curl, a browser, another service
- 2uvicorn
Parses HTTP and calls the ASGI app
- 3Starlette
Routing, request and response objects
- 4FastAPI
Validation, dependencies, docs
- 5Your function
Business logic, returns data
Pydantic models, validation and responses
FastAPI decides where each function parameter comes from. Names in the path (/items/{item_id}) are path parameters, simple types not in the path are query parameters (?limit=10), and Pydantic models are read from the JSON body.
Field adds rules: name: str = Field(min_length=1, max_length=50) or qty: int = Field(gt=0). Pydantic v2 runs in lax mode by default, so the string "5" is accepted for an int field, but "abc" is not. When validation fails, FastAPI returns 422 with a detail list; each entry has loc (where, such as ["body", "qty"]), msg and type.
response_model controls what goes out. If you return a user record with a password_hash field but declare response_model=UserOut without that field, FastAPI filters it away. That makes accidental data leaks much less likely.
- Field(gt=0, le=1000) for numbers; min_length and max_length for strings
- Optional field: note: str | None = None
- item.model_dump() turns a model into a plain dict
Health checks that tell the truth
Two different questions hide behind "is the app healthy?". Liveness asks: is the process stuck? Readiness asks: can it serve traffic right now, for example is the database reachable? Kubernetes uses both: a failing liveness probe restarts the container, while a failing readiness probe only removes the pod from the Service's load balancing until it recovers.
Keep the liveness endpoint (often /health or /livez) cheap and free of dependencies. If it checked the database, a short database outage would make Kubernetes restart every pod at once, which makes things worse. Put dependency checks in the readiness endpoint (/ready or /readyz), give each check a short timeout, and return 503 when something is down.
Return something useful in the body, such as the version and git SHA, so you can see which build is running with a single curl.
- Is the process alive?
- No dependency checks
- Fails: the container is restarted
- Can it take traffic now?
- Checks the database and cache
- Fails: removed from load balancing
Settings from the environment
The same image should run in dev, staging and prod, with only configuration changing. That configuration comes from environment variables, as the twelve-factor app method recommends. The pydantic-settings package (a separate install since Pydantic v2) makes this tidy: subclass BaseSettings, declare typed fields, and it reads matching environment variables, case-insensitively by default.
A field without a default, such as database_url: str, is required, so the app fails at startup with a clear error instead of crashing on the first request. Values are converted and checked: APP_WORKERS=abc fails immediately for an int field. env_prefix="APP_" in model_config namespaces your variables, and env_file=".env" loads a local file for development (never commit it).
Create the settings once and share them, for example through a function decorated with functools.lru_cache and injected with Depends. Tests can then override that dependency with different values.
Testing endpoints and running for real
TestClient (it needs the httpx package installed) calls your app in-process, with no server and no port. client.get("/health") returns a response object much like requests does. To swap a real dependency, such as the database session or settings, set app.dependency_overrides[get_settings] = lambda: Settings(...) in the test and clear it afterwards.
Use the with TestClient(app) as client: form when your app has startup and shutdown logic (a lifespan function), because only then do those events run.
In production you can run uvicorn with several worker processes (--workers 4), or run one process per container and let Kubernetes scale the number of containers; the second is the common choice. The fastapi run command (from fastapi-cli, included with pip install "fastapi[standard]") starts uvicorn with production-style defaults, listening on 0.0.0.0 port 8000.
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Create a FastAPI app with routes~1h
- 2Validate requests with Pydantic models~1h
- 3Add a health check endpoint~1h
- 4Read settings from environment variables~1h
- 5Test endpoints with TestClient~1h
Key points
- Type hints on parameters drive validation and the automatic /docs page.
- A /health endpoint lets load balancers and Kubernetes check the app.
- Read settings from environment variables so one image runs in every environment.
- TestClient calls endpoints in tests without starting a real server.
Key terms
Tap a card to flip it. 0/5 known
Examples
import os
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
qty: int = 1
@app.get("/health")
def health(): return {"status": "ok", "env": os.getenv("APP_ENV", "dev")}
@app.post("/items", status_code=201)
def create_item(item: Item): return item
assert TestClient(app).post("/items", json={"name": "bolt"}).json()["qty"] == 1A health check, a validated POST route and a quick test.
Separate liveness and readiness endpoints
Step 1: /health answers instantly with the version, so it only fails if the process is broken. Step 2: /ready tries to open a TCP connection to the database host with a 1 second timeout. Step 3: if that fails, it returns 503, so Kubernetes stops sending traffic but does not restart the pod. Step 4: test it with curl -i localhost:8000/ready while the database is stopped and started. A real app would run a cheap query such as SELECT 1 instead of a bare socket check.
import os, socket
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
VERSION = os.getenv("APP_VERSION", "dev")
@app.get("/health")
def health():
return {"status": "ok", "version": VERSION}
@app.get("/ready")
def ready():
try:
socket.create_connection((os.getenv("DB_HOST", "localhost"), 5432), timeout=1).close()
except OSError:
return JSONResponse({"status": "db unreachable"}, status_code=503)
return {"status": "ready"}Typed settings with a test override
Step 1: Settings reads APP_ENV from the environment because of env_prefix. Step 2: get_settings is cached, so the environment is read once. Step 3: the route receives settings through Depends instead of a global. Step 4: the test replaces the dependency with app.dependency_overrides, so it controls the value without touching real environment variables. Install with pip install fastapi pydantic-settings httpx.
from functools import lru_cache
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="APP_")
env: str = "dev"
@lru_cache
def get_settings() -> Settings:
return Settings()
app = FastAPI()
@app.get("/info")
def info(s: Settings = Depends(get_settings)):
return {"env": s.env}
app.dependency_overrides[get_settings] = lambda: Settings(env="test")
assert TestClient(app).get("/info").json()["env"] == "test"Quick reference
- uvicorn app.main:app --reload for development; --host 0.0.0.0 inside containers
- /docs is the interactive Swagger UI; /openapi.json is the raw schema
- Path params come from the URL, simple types are query params, models are the body
- Field(gt=0, max_length=50) adds validation rules to a model field
- response_model=UserOut filters out fields you never want to return
- Liveness: cheap, no dependencies. Readiness: check dependencies, return 503 when down
- app.dependency_overrides[get_db] = fake_db swaps a dependency in tests
- Use def for blocking code; use async def only when everything slow inside is awaited
Common mistakes
- Hard-coding database URLs instead of reading them from environment variables.
- A health check that always returns ok even when the app is broken.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Add GET /version that returns the APP_VERSION environment variable (default "dev"), and write a TestClient test that sets it with monkeypatch.setenv.
- Exercise 2medium
Create POST /items that accepts an Item with name (1 to 50 characters) and qty (greater than 0) and returns 201. Prove with TestClient that a valid body gives 201 and an empty name with qty 0 gives 422.
- Exercise 3hard
Make /ready depend on a check_db dependency that returns True or False. Return 503 when it is False. Test both the 200 and 503 cases by overriding the dependency, and clean up the override afterwards.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use FastAPI or Flask?
- Both are solid. FastAPI gives you request validation, async support and automatic API docs out of the box; Flask is older, simpler and has a huge ecosystem. For a new JSON API, FastAPI is a common choice.
- What is the difference between uvicorn and gunicorn?
- uvicorn is an ASGI server that runs FastAPI. gunicorn is a process manager for Python web servers and can supervise several uvicorn worker processes. In Kubernetes, many teams simply run one uvicorn process per container.
- Where are the API docs FastAPI generates?
- At /docs (Swagger UI) and /redoc while the app is running. The raw OpenAPI schema is at /openapi.json.
- Why do I get 422 when I send an HTML form?
- A Pydantic model parameter expects a JSON body. For form fields, declare parameters with Form(), which also needs the python-multipart package installed.