Testing and Deploying Your Python API
Part 4 of the Python for Web & APIs track. Last updated: September 2026.
You can build APIs now. The final step is what separates hobby projects from real ones: prove it works with automated tests, harden it against bad input and crashes, and put it on the internet where anyone can call it. This post covers testing with pytest, error handling patterns, configuration, and deployment.
Testing Flask with pytest
Flask's test_client() fires requests at your app without starting a server — fast and perfect for tests:
pip install pytest
# test_books.py
from app import app # your Flask app from Part 2
def test_list_books():
client = app.test_client()
r = client.get("/books")
assert r.status_code == 200
assert r.get_json()["count"] == 2
def test_create_book():
client = app.test_client()
r = client.post("/books", json={"title": "Snow Crash",
"author": "Neal Stephenson"})
assert r.status_code == 201
assert r.get_json()["title"] == "Snow Crash"
def test_missing_book_returns_404_json():
client = app.test_client()
r = client.get("/books/999")
assert r.status_code == 404
assert "error" in r.get_json() # JSON error, not HTML
def test_create_book_rejects_bad_input():
client = app.test_client()
r = client.post("/books", json={"title": "No author"})
assert r.status_code == 400
Run with pytest -v. Aim for this coverage on every API you ship: the happy path, the 404s, and the 400s.
Testing FastAPI
FastAPI ships a TestClient (built on httpx) — same idea, same speed:
from fastapi.testclient import TestClient
from main import app # your FastAPI app from Part 3
client = TestClient(app)
def test_list_books():
r = client.get("/books")
assert r.status_code == 200
assert len(r.json()) == 2
def test_validation_rejects_bad_input():
r = client.post("/books", json={"title": "", "year": "not-a-number"})
assert r.status_code == 422 # FastAPI's automatic validation
def test_create_and_fetch_roundtrip():
created = client.post("/books", json={"title": "Dune",
"author": "Frank Herbert"}).json()
fetched = client.get(f"/books/{created['id']}").json()
assert fetched == created
Pro tip: run tests against a fresh in-memory store (reset the books dict in a pytest fixture) so tests never depend on each other's leftovers.
Error handling patterns that survive production
Three rules:
- Never leak tracebacks. Clients get a JSON error and a status code; stack traces go to your logs.
- Validate at the door. Every endpoint validates its input before touching logic (FastAPI does this for you; Flask needs the explicit validators from Part 2).
- Fail with the right code. 400 = client sent garbage, 404 = not found, 422 = valid JSON but failed business rules, 500 = your bug.
Catch the unexpected at the boundary in Flask:
import logging
from flask import request
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
@app.post("/books")
def create_book():
try:
... # your normal logic
except Exception:
log.exception("Unhandled error on POST /books body=%s", request.data)
return {"error": "Internal server error"}, 500
And in FastAPI, a global exception handler does the same job once for all routes:
from fastapi import Request
from fastapi.responses import JSONResponse
import logging
log = logging.getLogger(__name__)
@app.exception_handler(Exception)
async def catch_all(request: Request, exc: Exception):
log.exception("Unhandled error on %s %s", request.method, request.url.path)
return JSONResponse(status_code=500,
content={"error": "Internal server error"})
Configuration: never hardcode secrets
Ports, database URLs, API keys — read them from the environment, with safe defaults for local dev:
import os
DEBUG = os.getenv("DEBUG", "false").lower() == "true"
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///dev.db")
API_KEY = os.getenv("API_KEY") # None locally; required in prod
if not API_KEY and not DEBUG:
raise RuntimeError("API_KEY must be set in production")
Locally, a .env file plus pip install python-dotenv keeps secrets out of your code — and .env goes in .gitignore, always.
Serving it for real: no dev servers in production
Flask's app.run() and uvicorn's --reload are development tools. Production needs a real server:
# Flask -> gunicorn (sync workers) pip install gunicorn # gunicorn -w 4 app:app # 4 worker processes # FastAPI -> uvicorn (async, production mode) # uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
The -w 4 / --workers 4 runs multiple processes so one slow request never blocks the rest.
Deploying: your options
Simplest first:
- PaaS (Render, Railway, Fly.io) — connect your Git repo, it builds and runs your app, gives you a URL. Free tiers exist. For uvicorn apps the start command is literally
uvicorn main:app --host 0.0.0.0 --port $PORT. This is where most first APIs should live. - Docker — package the app so it runs identically everywhere. A minimal FastAPI Dockerfile:
# Dockerfile FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
- VPS (Hetzner, DigitalOcean) — full control, cheapest at scale; you manage updates, TLS, and restarts yourself. Graduate here when you outgrow PaaS.
Whichever you choose: set DEBUG=false, provide real secrets via the platform's environment variables (never in the repo), and confirm /docs (FastAPI) or a health endpoint responds before announcing the URL.
Add a health check endpoint
Platforms and load balancers need a cheap "are you alive?" URL — add it to every API:
@app.get("/health")
def health():
return {"status": "ok"}
Track complete: where to go next
- Python for Automation — schedule scripts, scrape the web, talk to the APIs you just learned to build.
- Python Interview Prep — the coding patterns interviewers actually test.
- Python for Java Developers — a bridge track for the blog's Java audience.
Key takeaways
- Test the happy path, the 404s, and the 400s —
test_client()(Flask) andTestClient(FastAPI) make it fast. - Validate at the door, never leak tracebacks, and always log server-side.
- Configuration comes from environment variables — secrets never go in code or git.
- Production serving = gunicorn (Flask) or uvicorn with workers (FastAPI); dev servers stay local.
- Deploy first on a PaaS (Render/Railway/Fly.io), Dockerize when you need portability, VPS when you outgrow both.
- Every API gets a
/healthendpoint.
That completes the Python for Web & APIs track — you can consume APIs, build them in Flask and FastAPI, test them, and deploy them. Pick your next track above and keep going.
Comments
Post a Comment