Building APIs with FastAPI

Published by Brayan K

FastAPI is a modern, high-performance web framework that builds typed APIs from ordinary Python type hints. You get automatic validation, interactive OpenAPI docs, async support, and dependency injection — with very little boilerplate.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Test an HTTP contract without opening a network port

An API route is more than a function that returns a dictionary. Its contract includes the HTTP method, parameter location, validation, status code and response shape. We will test each of those with FastAPI’s in-process TestClient, so the examples make no external requests and do not start a listening server.

Use a local virtual environment with python -m pip install fastapi==0.162.5 httpx==0.28.1 pydantic==2.13.4. FastAPI and HTTPX are not included in this site’s browser runtime. Data Validation with Pydantic owns runtime model validation; REST API Clients & External Service Integrations owns calling external services.

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/status")
def status():
    return {"ready": True}

with TestClient(app) as client:
    response = client.get("/status")
    print(response.status_code, response.json())
    print(client.post("/status").status_code)
    print(client.get("/missing").status_code)

# ✅ Expected output:
# 200 {'ready': True}
# 405
# 404

Calling status() directly would skip routing and serialization. TestClient sends the request through the ASGI application in the same process. The context manager also runs application lifespan setup and teardown. A passing test here does not test a reverse proxy, TLS, deployment configuration or a real database.

Path, query and body values arrive through different boundaries

from typing import Annotated
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/items/{item_id}")
def item(item_id: int, limit: Annotated[int, Query(ge=1, le=5)] = 2):
    return {"item_id": item_id, "limit": limit}

with TestClient(app) as client:
    print(client.get("/items/7", params={"limit": 3}).json())
    for path in ["/items/no", "/items/7?limit=0"]:
        response = client.get(path)
        issue = response.json()["detail"][0]
        print(response.status_code, issue["loc"], issue["msg"])

# ✅ Expected output:
# {'item_id': 7, 'limit': 3}
# 422 ['path', 'item_id'] Input should be a valid integer, unable to parse string as an integer
# 422 ['query', 'limit'] Input should be greater than or equal to 1

The name in the route makes item_id a path parameter. limit is a query parameter with a default and bounds. These wire values start as text; FastAPI parses them according to the declarations. A 422 response describes invalid input, not an absent database record. The error location tells you whether the problem came from path, query or body.

from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field

class Purchase(BaseModel):
    model_config = ConfigDict(extra="forbid")
    count: int = Field(gt=0, strict=True)

app = FastAPI()
accepted = []

@app.post("/purchases", status_code=201)
def purchase(request: Purchase):
    accepted.append(request.count)
    return {"count": request.count}

with TestClient(app) as client:
    good = client.post("/purchases", json={"count": 2})
    bad = client.post("/purchases", json={"count": True})
    print(good.status_code, good.json())
    issue = bad.json()["detail"][0]
    print(bad.status_code, issue["loc"], issue["msg"])
    print(accepted)

# ✅ Expected output:
# 201 {'count': 2}
# 422 ['body', 'count'] Input should be a valid integer
# [2]

The Pydantic model is read from the JSON body. The invalid request never enters this handler, so it does not append anything. Strict integer validation rejects a boolean even though bool is a subclass of int in Python. A real purchase also needs authorization and transactional storage; this list is only an observable test fixture.

Raise an HTTP error; returning an exception is not the same thing

from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient

app = FastAPI()
catalog = {1: "Notebook"}

@app.get("/catalog/{item_id}")
def lookup(item_id: int):
    if item_id not in catalog:
        raise HTTPException(status_code=404, detail="item not found")
    return {"name": catalog[item_id]}

with TestClient(app) as client:
    for path in ["/catalog/1", "/catalog/8"]:
        response = client.get(path)
        print(response.status_code, response.json())
    print(client.get("/catalog/invalid").status_code)

# ✅ Expected output:
# 200 {'name': 'Notebook'}
# 404 {'detail': 'item not found'}
# 422

Raise HTTPException to stop the handler and produce the selected HTTP response. A missing valid identifier gets 404; an identifier that cannot be parsed gets 422 before the handler. Do not wrap every exception in 200 with an error-shaped dictionary: callers need the status to distinguish success from failure.

Route order can turn a fixed word into an invalid parameter

from fastapi import FastAPI
from fastapi.testclient import TestClient

wrong = FastAPI()

@wrong.get("/items/{item_id}")
def by_id(item_id: int):
    return {"id": item_id}

@wrong.get("/items/latest")
def latest():
    return {"id": 9}

right = FastAPI()
right.get("/items/latest")(latest)
right.get("/items/{item_id}")(by_id)

with TestClient(wrong) as client:
    print(client.get("/items/latest").status_code)
with TestClient(right) as client:
    response = client.get("/items/latest")
    print(response.status_code, response.json())

# ✅ Expected output:
# 422
# 200 {'id': 9}

Routes are evaluated in registration order. In the first app, the parameter route matches the path and then tries to parse latest as an integer. A validation failure does not make routing continue to another candidate. Put the specific route first, or design paths that cannot overlap.

An output model is a public contract, not authorization

from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel

class PublicProfile(BaseModel):
    name: str

app = FastAPI()

@app.get("/profile", response_model=PublicProfile)
def profile():
    return {"name": "Ada", "internal_note": "review pending"}

with TestClient(app) as client:
    response = client.get("/profile")
    print(response.json())
    print("internal_note" in response.json())

# ✅ Expected output:
# {'name': 'Ada'}
# False

The response model validates and filters the returned data to the declared public fields. It does not decide who may request the profile. Keep access control separate, and avoid collecting or returning secrets unnecessarily in the first place.

from fastapi import FastAPI
from fastapi.testclient import TestClient
from fastapi.exceptions import ResponseValidationError
from pydantic import BaseModel

class Result(BaseModel):
    count: int

app = FastAPI()

@app.get("/result", response_model=Result)
def result():
    return {"count": "many"}

with TestClient(app) as client:
    try:
        client.get("/result")
    except ResponseValidationError as problem:
        issue = problem.errors()[0]
        print(issue["loc"], issue["msg"])
with TestClient(app, raise_server_exceptions=False) as client:
    print(client.get("/result").status_code)

# ✅ Expected output:
# ('response', 'count') Input should be a valid integer, unable to parse string as an integer
# 500

TestClient normally re-raises server exceptions so tests expose the defect. Disabling that behavior lets this example inspect the HTTP 500 status. Do not turn this into a client validation error: the server violated its own declared response contract.

Inject a dependency and replace it only for the test

from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

def get_catalog():
    return {"pen": 3}

@app.get("/stock/{name}")
def stock(name: str, catalog: Annotated[dict, Depends(get_catalog)]):
    return {"count": catalog.get(name, 0)}

def test_catalog():
    return {"pen": 8}

app.dependency_overrides[get_catalog] = test_catalog
try:
    with TestClient(app) as client:
        print(client.get("/stock/pen").json())
finally:
    app.dependency_overrides.clear()
with TestClient(app) as client:
    print(client.get("/stock/pen").json())

# ✅ Expected output:
# {'count': 8}
# {'count': 3}

Depends receives get_catalog, not get_catalog(). FastAPI resolves the dependency during the request. The override maps the original callable to its replacement, and cleanup prevents it leaking into another test. Use an app factory and owned fixtures when tests need independent state.

Choose async def when the handler awaits asynchronous I/O. A normal def route is run in a thread pool by FastAPI; calling a blocking library directly inside async def can block the event loop. Neither spelling makes CPU-heavy work free. Advanced Async & Await Patterns owns coroutine execution and waiting.

Complete a route with a bounded query parameter

Limit a preview count to the inclusive range 1–3. Fill the Query lower bound and the status code for an explicitly missing entry. The client calls check both cases.

from typing import Annotated
from fastapi import FastAPI, HTTPException, Query
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/preview")
def preview(count: Annotated[int, Query(ge=___, le=3)] = 1):
    return {"count": count}

@app.get("/absent")
def absent():
    raise HTTPException(status_code=___, detail="entry not found")

with TestClient(app) as client:
    print(client.get("/preview?count=0").status_code)
    print(client.get("/absent").status_code)

# 👉 replace ___ with 1
# 👉 replace ___ with 404

# ✅ Expected output:
# 422
# 404

Build a reservation endpoint with observable failure behavior

Create an app with three pens in a local fixture. POST /reserve/{name} accepts a strictly typed positive quantity. Return 404 for an unknown item, 409 for insufficient stock, and a response containing remaining stock after success. Test an invalid boolean quantity, an oversized reservation and one successful reservation. Print the final state to prove the failures did not change it.

from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field

class Reservation(BaseModel):
    quantity: int = Field(gt=0, strict=True)

def make_app():
    app = FastAPI()
    stock = {"pen": 3}

    @app.post("/reserve/{name}")
    def reserve(name: str, request: Reservation):
        if name not in stock:
            raise HTTPException(status_code=404, detail="item not found")
        if request.quantity > stock[name]:
            raise HTTPException(status_code=409, detail="insufficient stock")
        stock[name] -= request.quantity
        return {"remaining": stock[name]}

    return app, stock

app, stock = make_app()
with TestClient(app) as client:
    print(client.post("/reserve/pen", json={"quantity": True}).status_code)
    print(client.post("/reserve/pen", json={"quantity": 4}).status_code)
    print(client.post("/reserve/unknown", json={"quantity": 1}).status_code)
    good = client.post("/reserve/pen", json={"quantity": 2})
    print(good.status_code, good.json())
print(stock)

# ✅ Expected output:
# 422
# 409
# 404
# 200 {'remaining': 1}
# {'pen': 1}

This fixture is deliberately single-process test state. A real concurrent reservation service needs a transaction or another atomic storage operation, persistence, authentication and authorization. The check-then-decrement sequence here is not a production stock-control design.

Practice quiz

What does TestClient exercise that a direct handler call skips?

  • Routing, validation and response serialization
  • A public network connection
  • A production database automatically
  • TLS certificates

Answer: Routing, validation and response serialization. It invokes the application through its in-process ASGI transport.

An integer path parameter receives "no". Which response occurs before the handler?

  • 200
  • 422
  • 404
  • 201

Answer: 422. The path matched, but the value failed parsing.

How should a handler stop with an intentional 404?

  • Return HTTPException(...)
  • Return None
  • Raise HTTPException(status_code=404, ...)
  • Print 404

Answer: Raise HTTPException(status_code=404, ...). Raising stops normal handler execution and selects the HTTP error response.

Why register /items/latest before /items/{item_id}?

  • It makes all requests asynchronous
  • It disables validation
  • It sorts database results
  • The earlier matching parameter route can consume the fixed word

Answer: The earlier matching parameter route can consume the fixed word. Routing does not retry after parameter validation fails.

What does response_model provide?

  • Response validation and filtering
  • Automatic user authorization
  • Database transactions
  • A guarantee that every route is secure

Answer: Response validation and filtering. Output shape and access control are different responsibilities.

What belongs inside Depends(...) for a dependency function?

  • Its already computed result
  • The callable itself
  • A client response
  • The string name of the app

Answer: The callable itself. FastAPI calls the dependency while resolving the request.

Why clear dependency_overrides after a test?

  • To change the route URL
  • To enable JSON parsing
  • To prevent a test replacement leaking into later requests
  • To delete a production database

Answer: To prevent a test replacement leaking into later requests. Overrides are mutable app state and need a defined lifetime.

Why is the brief’s dictionary insufficient for production reservations?

  • Dictionaries cannot hold integers
  • HTTP cannot send JSON
  • Pydantic never validates inputs
  • The check and update are not a persistent, atomic concurrent operation

Answer: The check and update are not a persistent, atomic concurrent operation. Use appropriate transactional storage and access control for a real service.

Continue this course

Related lessons