Day 9: Web Service – shorturl
Goal: Build a tested mini URL shortener
shorturlwith FastAPI, SQLite and a Dockerfile · Duration: approx. 120 min · Prerequisite: Day 8
Briefing
- FastAPI builds routing, validation and OpenAPI docs from type hints; uvicorn is the ASGI server.
- pydantic models are the API contract:
HttpUrlonly letshttp/httpsthrough. - SQLite is enough for a service with a single instance; the connection comes in via a dependency.
TestClienttests the app in-process, without a server and without a port.- The Dockerfile is only checked statically
(
docker build --check), not built.
curl POST /api/links {"url": ...} --> pydantic LinkIn --> db.create() --> 201 + code
curl GET /<code> ------------------> db.hit() (hits+1) --> 307 Location: <url>
curl GET /api/links/<code> --------> db.get() ----------> LinkOut (stats)
Drill 1: Project and first route
cd ~/py-lab
uv init -q --package --name shorturl tag09-shorturl
cd tag09-shorturl && mkdir tests
uv add -q fastapi uvicorn
uv add -q --dev pytest ruff httpx2
cat > src/shorturl/__init__.py <<'EOF'
"""shorturl – Mini-URL-Shortener mit FastAPI und SQLite."""
EOF
cat > src/shorturl/app.py <<'EOF'
from fastapi import FastAPI
app = FastAPI(title="shorturl")
@app.get("/healthz")
def healthz() -> dict[str, str]:
return {"status": "ok"}
EOFIn a second terminal, start the server with auto-reload and leave it running:
cd ~/py-lab/tag09-shorturl && uv run uvicorn shorturl.app:app --reloadExpected (abridged):
INFO: Will watch for changes in these directories: [...]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Application startup complete.
Back in the first terminal:
curl -s http://127.0.0.1:8000/healthz; echo
curl -s http://127.0.0.1:8000/openapi.json | jq -c '.paths | keys'Expected:
{"status":"ok"}
["/healthz"]
Why? FastAPI generates an OpenAPI description from the code. Open
http://127.0.0.1:8000/docs in your browser: interactive
docs, without a single extra line.
Tip: The
TestClientneedshttpx2in current Starlette versions (older ones usehttpx). It is a dev dependency and does not end up in the container.
Save your progress? Sign up for free
Drill 2: The SQLite layer
cat > src/shorturl/db.py <<'EOF'
"""SQLite-Schicht: Schema, Anlegen, Auflösen, Statistik."""
import secrets
import sqlite3
from datetime import UTC, datetime
SCHEMA = """
CREATE TABLE IF NOT EXISTS links (
code TEXT PRIMARY KEY,
url TEXT NOT NULL,
created TEXT NOT NULL,
hits INTEGER NOT NULL DEFAULT 0
)
"""
def connect(path: str) -> sqlite3.Connection:
conn = sqlite3.connect(path, check_same_thread=False)
conn.row_factory = sqlite3.Row # Zugriff per Spaltenname
conn.execute("PRAGMA journal_mode=WAL") # Lesen blockiert Schreiben nicht
conn.execute(SCHEMA)
return conn
def create(conn: sqlite3.Connection, url: str) -> str:
for _ in range(5):
code = secrets.token_urlsafe(6) # 8 Zeichen, nicht erratbar
try:
with conn:
conn.execute(
"INSERT INTO links (code, url, created) VALUES (?, ?, ?)",
(code, url, datetime.now(UTC).isoformat(timespec="seconds")),
)
return code
except sqlite3.IntegrityError: # Kollision: neuer Versuch
continue
raise RuntimeError("kein freier Code gefunden")
def get(conn: sqlite3.Connection, code: str) -> sqlite3.Row | None:
return conn.execute("SELECT * FROM links WHERE code = ?", (code,)).fetchone()
def hit(conn: sqlite3.Connection, code: str) -> str | None:
"""Zählt einen Aufruf und gibt die Ziel-URL zurück."""
with conn:
row = conn.execute(
"UPDATE links SET hits = hits + 1 WHERE code = ? RETURNING url", (code,)
).fetchone()
return row["url"] if row else None
EOF
uv run python - <<'EOF'
from shorturl import db
conn = db.connect(":memory:")
code = db.create(conn, "https://docs.python.org/3/")
print(code, db.hit(conn, code), db.hit(conn, "gibtsnicht"))
print(dict(db.get(conn, code)))
EOFExpected (code and time are random):
9moxVx4w https://docs.python.org/3/ None
{'code': '9moxVx4w', 'url': 'https://docs.python.org/3/', 'created': '2026-10-...
Why? secrets.token_urlsafe(6) returns 8 URL-safe
characters from a cryptographic random number generator – sequential IDs
would make all links enumerable. UPDATE ... RETURNING
counts and reads in one statement, so there is no race between two
requests.
Save your progress? Sign up for free
Drill 3: Models and endpoints
cat > src/shorturl/models.py <<'EOF'
"""API-Verträge: was rein darf und was rausgeht."""
from pydantic import BaseModel, Field, HttpUrl
class LinkIn(BaseModel):
url: HttpUrl = Field(max_length=2048) # nur http/https, kein javascript:
class LinkOut(BaseModel):
code: str
short_url: str
url: str
hits: int
created: str
EOF
cat > src/shorturl/app.py <<'EOF'
"""FastAPI-App: JSON-API unter /api, Redirect unter /{code}."""
import os
import sqlite3
from collections.abc import Iterator
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Path, status
from fastapi.responses import RedirectResponse
from shorturl import db
from shorturl.models import LinkIn, LinkOut
BASE_URL = os.environ.get("SHORTURL_BASE", "http://127.0.0.1:8000")
DB_PATH = os.environ.get("SHORTURL_DB", "shorturl.db")
Code = Annotated[str, Path(pattern=r"^[A-Za-z0-9_-]{8}$")]
app = FastAPI(title="shorturl", version="0.1.0")
def get_conn() -> Iterator[sqlite3.Connection]:
conn = db.connect(DB_PATH)
try:
yield conn
finally:
conn.close()
Conn = Annotated[sqlite3.Connection, Depends(get_conn)]
def to_out(row: sqlite3.Row) -> LinkOut:
return LinkOut(short_url=f"{BASE_URL}/{row['code']}", **dict(row))
@app.get("/healthz")
def healthz() -> dict[str, str]:
return {"status": "ok"}
@app.post("/api/links", status_code=status.HTTP_201_CREATED)
def create_link(link: LinkIn, conn: Conn) -> LinkOut:
code = db.create(conn, str(link.url))
return to_out(db.get(conn, code))
@app.get("/api/links/{code}")
def link_stats(code: Code, conn: Conn) -> LinkOut:
row = db.get(conn, code)
if row is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "unbekannter Code")
return to_out(row)
@app.get("/{code}")
def follow(code: Code, conn: Conn) -> RedirectResponse:
url = db.hit(conn, code)
if url is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "unbekannter Code")
return RedirectResponse(url, status_code=status.HTTP_307_TEMPORARY_REDIRECT)
EOFWhy? Depends(get_conn) opens one connection per request
and closes it in the finally – even on exceptions. The
return type LinkOut makes FastAPI validate the response and
deliver only the declared fields. Code with
pattern rejects nonsense like /x before it
ever reaches the database. The configuration comes from environment
variables (12-factor), so the same code runs locally and in the
container.
Save your progress? Sign up for free
Drill 4: Play it through with curl
In the second terminal, uvicorn reports
StatReload detected changes in 'src/shorturl/app.py'. Reloading...
– the new app is already running.
B=http://127.0.0.1:8000
curl -s -X POST $B/api/links -H 'Content-Type: application/json' \
-d '{"url": "https://docs.python.org/3/library/sqlite3.html"}' | tee resp.json | jq .
CODE=$(jq -r .code resp.json)
curl -s -o /dev/null -w '%{http_code} -> %{redirect_url}\n' $B/$CODE
curl -s $B/api/links/$CODE | jq -c '{code, hits}'
curl -s -X POST $B/api/links -H 'Content-Type: application/json' \
-d '{"url": "javascript:alert(1)"}' | jq -c '.detail[0].msg'
curl -s -o /dev/null -w '%{http_code}\n' $B/nichtda1Expected (code and time are random):
{
"code": "DvV5IC0X",
"short_url": "http://127.0.0.1:8000/DvV5IC0X",
"url": "https://docs.python.org/3/library/sqlite3.html",
"hits": 0,
"created": "2026-10-10T06:55:09+00:00"
}
307 -> https://docs.python.org/3/library/sqlite3.html
{"code":"DvV5IC0X","hits":1}
"URL scheme should be 'http' or 'https'"
404
Why? The 422 with a precise error message comes for free from
pydantic. 307 instead of 301: browsers cache a 301 permanently – then
hits stops counting and a changed link never takes
effect.
Security: A shortener is an open redirector. The scheme check blocks
javascript:anddata:links; for internal services, add an allowlist of permitted target domains as well.
Save your progress? Sign up for free
Drill 5: Tests with TestClient
dependency_overrides swaps the database dependency for a
test DB in tmp_path – the rest of the app stays real.
cat > tests/test_api.py <<'EOF'
from collections.abc import Iterator
import pytest
from fastapi.testclient import TestClient
from shorturl import db
from shorturl.app import app, get_conn
@pytest.fixture
def client(tmp_path) -> Iterator[TestClient]:
def test_conn():
conn = db.connect(str(tmp_path / "test.db"))
try:
yield conn
finally:
conn.close()
app.dependency_overrides[get_conn] = test_conn # eigene DB pro Test
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
def test_healthz(client):
assert client.get("/healthz").json() == {"status": "ok"}
def test_create_redirect_and_count(client):
resp = client.post("/api/links", json={"url": "https://example.org/a?b=1"})
assert resp.status_code == 201
code = resp.json()["code"]
assert len(code) == 8
for _ in range(2):
hop = client.get(f"/{code}", follow_redirects=False)
assert hop.status_code == 307
assert hop.headers["location"] == "https://example.org/a?b=1"
stats = client.get(f"/api/links/{code}").json()
assert stats["hits"] == 2
assert stats["short_url"].endswith(f"/{code}")
@pytest.mark.parametrize(
"url", ["javascript:alert(1)", "ftp://example.org", "kein-url", "https://x/" * 300]
)
def test_rejects_bad_urls(client, url):
assert client.post("/api/links", json={"url": url}).status_code == 422
def test_unknown_and_invalid_codes(client):
assert client.get("/AAAAAAAA").status_code == 404
assert client.get("/api/links/AAAAAAAA").status_code == 404
assert client.get("/x").status_code == 422 # passt nicht aufs Muster
EOF
cat >> pyproject.toml <<'EOF'
[tool.ruff.lint]
extend-select = ["E501", "B", "UP", "SIM"]
[tool.pytest.ini_options]
testpaths = ["tests"]
EOF
uv run pytest -q && uv run ruff check . && uv run ruff format --check .Expected:
....... [100%]
7 passed in 0.19s
All checks passed!
6 files already formatted
Why? follow_redirects=False checks the redirect itself
instead of following it. The parametrized test covers the attack and
error cases in four lines – including a 3000-character URL against
max_length.
Save your progress? Sign up for free
Drill 6: Start script and Dockerfile
First a console script, so the container only has to call
shorturl. Now stop the --reload server in the
second terminal with Ctrl-C.
cat > src/shorturl/cli.py <<'EOF'
"""Startet den Server: shorturl [--host 127.0.0.1] [--port 8000]"""
import argparse
import uvicorn
def main() -> None:
parser = argparse.ArgumentParser(description="Mini-URL-Shortener")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8000)
args = parser.parse_args()
uvicorn.run("shorturl.app:app", host=args.host, port=args.port)
EOF
cat > src/shorturl/__init__.py <<'EOF'
"""shorturl – Mini-URL-Shortener mit FastAPI und SQLite."""
from shorturl.cli import main
__all__ = ["main"]
EOF
cat > src/shorturl/__main__.py <<'EOF'
from shorturl import main
main()
EOF
cat > Dockerfile <<'EOF'
# Build stage: install dependencies and project into a venv
FROM python:3.14-slim AS build
COPY --from=ghcr.io/astral-sh/uv:0.9 /uv /bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=never
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --locked --no-dev --no-install-project
COPY README.md ./
COPY src ./src
RUN uv sync --locked --no-dev --no-editable
# Runtime stage: only Python + venv, no uv, no source code, no root
FROM python:3.14-slim
RUN useradd --system --uid 10001 app && mkdir /data && chown app /data
COPY --from=build /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH" SHORTURL_DB=/data/shorturl.db
USER app
EXPOSE 8000
VOLUME /data
HEALTHCHECK --interval=30s --timeout=3s CMD python -c \
"import urllib.request as u; u.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"
CMD ["shorturl", "--host", "0.0.0.0", "--port", "8000"]
EOF
cat > .dockerignore <<'EOF'
.venv
.git
**/__pycache__
.pytest_cache
.ruff_cache
tests
*.db*
EOF
docker build --check .Expected (abridged):
#2 [internal] load metadata for ghcr.io/astral-sh/uv:0.9
#3 [internal] load metadata for docker.io/library/python:3.14-slim
Check complete, no warnings found.
Why? Two stages: the build stage has uv and first installs only the
dependencies (a separate, easily cacheable layer), then the project as a
regular package (--no-editable). The runtime stage gets
only the finished venv – no uv, no dev tools, no source code – and runs
as user app instead of root. --check only
loads metadata for the base images and checks the build rules without
building anything.
You can see what --check finds with two typical
mistakes:
sed 's/^CMD .*/CMD shorturl --host 0.0.0.0/; s/ AS build/ as build/' Dockerfile \
> Dockerfile.bad
docker build --check -f Dockerfile.bad . 2>&1 | grep WARNING
rm Dockerfile.badExpected:
WARNING: FromAsCasing - https://docs.docker.com/go/dockerfile/rule/from-as-casing/
WARNING: JSONArgsRecommended - https://docs.docker.com/go/dockerfile/rule/json-args...
CMD in shell form starts a shell as PID 1 – it does not
forward SIGTERM, and the container only dies after the kill
timeout.
Even without a Docker build, you can reproduce the build stage’s installation:
rm -rf ~/py-lab/shorturl-sim && mkdir ~/py-lab/shorturl-sim
cp -R pyproject.toml uv.lock README.md src ~/py-lab/shorturl-sim/
cd ~/py-lab/shorturl-sim && uv sync -q --locked --no-dev --no-editable && rm -rf src
.venv/bin/python -c 'import shorturl.app; print("ok ohne Quellcode")'
ls .venv/bin | grep -E 'shorturl|pytest|ruff'
cd - >/dev/null && rm -rf ~/py-lab/shorturl-simExpected:
ok ohne Quellcode
shorturl
The project is installed, pytest and ruff
are missing – exactly how the runtime venv should look.
Save your progress? Sign up for free
Drill 7: The tool is done
In the second terminal, start the service the way it runs in the container – via the console script and with environment variables:
cd ~/py-lab/tag09-shorturl
SHORTURL_DB=$PWD/links.db SHORTURL_BASE=http://127.0.0.1:8000 uv run shorturlIn the first terminal:
B=http://127.0.0.1:8000
CODE=$(curl -s -X POST $B/api/links -H 'Content-Type: application/json' \
-d '{"url": "https://github.com/astral-sh/uv"}' | jq -r .code)
for i in 1 2 3; do curl -s -o /dev/null $B/$CODE; done
curl -s $B/api/links/$CODE | jq -c '{code, hits, url}'
sqlite3 links.db 'SELECT code, hits FROM links'
uv run pytest -q && uv run ruff check . && uv run ruff format --check .Expected (code is random):
{"code":"pT3x_9Qa","hits":3,"url":"https://github.com/astral-sh/uv"}
pT3x_9Qa|3
....... [100%]
7 passed in 0.19s
All checks passed!
7 files already formatted
The data lives in links.db and survives a restart – in
the container, that corresponds to the /data volume.
Save your progress? Sign up for free
Checkpoint
#!/usr/bin/env bash
check() { if eval "$2" >/dev/null 2>&1; then echo "✔ $1"; else echo "✘ $1"; fi; }
cd ~/py-lab/tag09-shorturl
B=http://127.0.0.1:8000
check "Tests grün" "uv run pytest -q"
check "ruff sauber" "uv run ruff check . && uv run ruff format --check ."
check "Dienst gesund" "curl -sf $B/healthz | grep -q ok"
check "javascript: abgelehnt" "test \$(curl -s -o /dev/null -w '%{http_code}' \
-X POST $B/api/links -H 'Content-Type: application/json' \
-d '{\"url\": \"javascript:alert(1)\"}') = 422"
check "Dockerfile ohne Warnungen" "docker build --check . 2>&1 | grep -q 'no warnings'"
check "Container läuft nicht als root" "grep -q '^USER app' Dockerfile"Expected:
✔ Tests grün
✔ ruff sauber
✔ Dienst gesund
✔ javascript: abgelehnt
✔ Dockerfile ohne Warnungen
✔ Container läuft nicht als root
Cleanup: stop the server in the second terminal with Ctrl-C.
Challenge
Anyone can create links. Protect POST /api/links with an
API key from SHORTURL_API_KEY in the X-API-Key
header; redirects stay public.
Hint: A dependency with Header(),
attached via dependencies=[Depends(...)] on the decorator;
compare with secrets.compare_digest.
Solution
In src/shorturl/app.py, add import secrets
and Header, then:
def require_key(x_api_key: Annotated[str, Header()] = "") -> None:
expected = os.environ.get("SHORTURL_API_KEY", "")
if not expected or not secrets.compare_digest(x_api_key, expected):
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "API-Key fehlt/falsch")
@app.post(
"/api/links",
status_code=status.HTTP_201_CREATED,
dependencies=[Depends(require_key)],
)
def create_link(link: LinkIn, conn: Conn) -> LinkOut:In tests/test_api.py, adjust the fixture and append a
test:
@pytest.fixture
def client(tmp_path, monkeypatch) -> Iterator[TestClient]:
monkeypatch.setenv("SHORTURL_API_KEY", "lab-key-123") # Lab-Wert
...
with TestClient(app, headers={"X-API-Key": "lab-key-123"}) as c:
...
def test_post_needs_api_key(client):
body = {"url": "https://example.org"}
wrong = client.post("/api/links", json=body, headers={"X-API-Key": "falsch"})
assert wrong.status_code == 401uv run pytest -qExpected:
........ [100%]
8 passed in 0.19s
Why compare_digest? A plain == stops at the
first wrong character; the runtime then reveals how many characters are
correct (timing attack). Without a key set, the dependency rejects
everything – fail closed.
Save your progress? Sign up for free
Enterprise Note
- SQLite means: exactly one instance. For multiple replicas, use
PostgreSQL (e.g.
psycopgor SQLAlchemy) and migrations with Alembic. - Behind an Ingress/load balancer, TLS terminates there; start uvicorn
with
--proxy-headersand--forwarded-allow-ipsso client IPs and scheme are correct. - Pin base images by digest
(
python:3.14-slim@sha256:...), build in CI, scan (Trivy/Grype), sign (cosign) and generate an SBOM. - In Kubernetes, use
readOnlyRootFilesystem,runAsNonRootand probes on/healthz; API keys come from a secret store (Vault/OpenBao), never from the image. - Rate limiting and abuse detection (phishing links!) belong in front of a public shortener – or it stays internal.