ARTICLE - Dev Stack & Tools

Build and Verify a FastAPI Endpoint

FastAPI connects type declarations to request validation and API documentation; async boundaries, business errors, and resource cleanup still need explicit design and tests for each application.

2026-08-06 16IDC 62 views
Advertisement

A 422 response may originate in a path, query parameter, or request body, not just malformed JSON. This runnable FastAPI example distinguishes framework validation from business errors, then tests dependency overrides. Its sample data does not use a database.

Prepare the local environment

Use an empty directory, Python 3.10 or later, pip, and a virtual environment. The example uses Pydantic v2. These commands are for macOS/Linux; on Windows, activate with .venv\Scripts\activate. Install fastapi[standard] as described in the official FastAPI tutorial; it includes the development server. pytest runs the tests below.

python3 -m venv .venv
source .venv/bin/activate
python -m pip install "fastapi[standard]" "pydantic>=2,<3" pytest
python -m pip show fastapi pydantic

Verify: the last command should show both packages, with Pydantic major version 2. If installation fails, check the Python version and package-index connection. For production, lock the tested dependency versions instead of resolving fresh versions on each deployment.

Create the endpoint and dependency

The diagram separates validation by input source. Business decisions occur after valid input reaches the endpoint; dependencies can also declare and validate their own parameters.

FastAPI request validation layers Client request Path parameter Query parameter Body model Valid input to endpoint Invalid input defaults to 422 Illustration: dependencies can declare and validate inputs too
Figure 1: FastAPI request validation layers (Source: request parameters in this example)

Save the following as main.py in the current directory. The repository is a fixed demonstration object and does not persist orders; quantities above 50 merely simulate a stock conflict.

from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Query
from pydantic import BaseModel, Field

app = FastAPI()

class OrderIn(BaseModel):
    sku: str = Field(min_length=3, max_length=32)
    quantity: int = Field(gt=0, le=99)

class OrderOut(BaseModel):
    id: str
    status: str

class OrderRepo:
    def create(self, sku: str, quantity: int) -> OrderOut:
        if quantity > 50:
            raise HTTPException(status_code=409, detail="stock unavailable")
        return OrderOut(id="ord_1", status="created")

def get_repo() -> OrderRepo:
    return OrderRepo()

@app.post("/orders", status_code=201, response_model=OrderOut)
def create_order(
    payload: OrderIn, repo: Annotated[OrderRepo, Depends(get_repo)]
) -> OrderOut:
    return repo.create(payload.sku, payload.quantity)

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

Verify: after saving, start the server below. POST /orders returns the fields in OrderOut, while an out-of-range quantity produces 422 before the create operation runs. Depends(get_repo) supplies the repository and response_model declares the output contract; a real service still needs persistence, transactions, and authorization.

fastapi dev main.py

Verify: when the terminal reports that the server is listening on http://127.0.0.1:8000, open /docs and /openapi.json in a browser. Both /orders and /items/{item_id} should be listed. On import failure, check that main.py is in the current directory and the virtual environment is active. Leave the server running and send requests from another terminal:

curl -i -X POST http://127.0.0.1:8000/orders \
  -H 'Content-Type: application/json' \
  -d '{"sku":"ABC-1","quantity":2}'
curl -i -X POST http://127.0.0.1:8000/orders \
  -H 'Content-Type: application/json' \
  -d '{"sku":"ABC-1","quantity":0}'
curl -i 'http://127.0.0.1:8000/items/7?limit=101'

Verify: expect 201, 422, and 422 respectively. The first returns ord_1; the other detail fields identify body/quantity and query/limit. If a request returns 404, check the path and the running application. When finished, press Ctrl+C in the server terminal.

Test the contract

Save the following as test_main.py alongside main.py:

from fastapi.testclient import TestClient
from main import OrderOut, app, get_repo

client = TestClient(app)

def test_create_and_validation():
    response = client.post("/orders", json={"sku": "ABC-1", "quantity": 2})
    assert response.status_code == 201
    assert response.json() == {"id": "ord_1", "status": "created"}
    invalid = client.post("/orders", json={"sku": "ABC-1", "quantity": 0})
    assert invalid.status_code == 422
    assert invalid.json()["detail"][0]["loc"][-1] == "quantity"

def test_business_conflict_and_schema():
    response = client.post("/orders", json={"sku": "ABC-1", "quantity": 51})
    assert response.status_code == 409
    assert "/orders" in client.get("/openapi.json").json()["paths"]

def test_override():
    class FakeRepo:
        def create(self, sku, quantity):
            return OrderOut(id="test_order", status="created")
    app.dependency_overrides[get_repo] = lambda: FakeRepo()
    try:
        response = client.post("/orders", json={"sku": "ABC-1", "quantity": 2})
        assert response.json()["id"] == "test_order"
    finally:
        app.dependency_overrides.clear()

Verify: the following command should pass three tests. The override test clears its override afterward so other tests are unaffected. If imports fail, check file locations and the active virtual environment.

python -m pytest -q

Verify: passing confirms these three tested paths and the asserted schema path, not every business, authentication, or database scenario. The official testing guide describes TestClient.

Diagnose 422 and choose async boundaries

Request validation errors normally return 422 by default. Inspect loc in detail for path, query, or body, then compare the field type and constraints with /openapi.json. An unmatched route also returns 404; application code can raise HTTPException for 404 or 409. Applications can customize status codes and exception handlers, so status alone does not establish the source.

According to FastAPI's concurrency guide (checked 2026-11-28), an I/O library supporting await can be used in async def; a blocking library can be used in a normal def endpoint or dependency, which the framework runs in a thread pool. Calling a blocking function directly inside async def still blocks the event loop. For CPU-heavy work, evaluate processes or a task queue; a thread pool does not guarantee parallel CPU speedup.

A yield dependency can acquire a database connection and close it in finally. Design commit, rollback, and cleanup timing around the transaction and response type; see the official yield dependency guide.

Limitations

  • The example listens locally; its in-memory demonstration does not save orders and provides no authentication, authorization, database transaction, or idempotency. Do not use it as a production payment flow.
  • fastapi dev is a development server. In production, disable auto-reload, configure HTTPS, process management, logs, and health checks for the deployment, and assess whether interactive docs should be public.
  • Pydantic may coerce inputs; annotations do not imply strict type checking. Configure strict mode explicitly and test it when required.

FAQ

Why does an invalid path parameter also return 422?

Path parameters are validated too. item_id is declared as an integer, so an input that cannot be converted fails default request validation after the route matches. Check whether detail.loc points to path and item_id; do not inspect only the JSON body. A custom handler can change the response format.

Does async def make a synchronous database call asynchronous?

No. Calling a synchronous driver directly still blocks the event loop. Use an async-capable driver or let the framework run blocking operations in a normal def endpoint or dependency. Assess concurrency with the connection pool size and load tests as well.

How can a test replace the database dependency?

Map the original dependency function to a test implementation using app.dependency_overrides, then clear the override after the test. This example uses FakeRepo to verify injection; real database tests should also cover rollback, concurrency, and cleanup on failure.

Related Providers

  • Docker: package the application and locked dependencies into a consistent runtime environment.
  • GitHub Actions: run API tests automatically when code changes.

Community & Resources

Original source: 16IDC ↗