Lesson 3 / 26

A First FastAPI App

Type hints become validation.

Path and query parameters

In FastAPI, a decorated function is an endpoint; its type-annotated parameters define path and query parameters, converted and validated automatically. A path parameter declared as int rejects non-numeric input with 422 Unprocessable Entity and a structured error explaining what was wrong. Return dicts or Pydantic models and FastAPI serialises them to JSON. Run it with an ASGI server such as uvicorn (uvicorn main:app --reload) and open /docs for interactive documentation.

Typed parameters and automatic validation, run

I ran this with Python 3.12, FastAPI 0.142.2, Pydantic 2.13 and Starlette 1.7, calling the app through FastAPI's TestClient (no server needed). A default query parameter, an overridden one, and a 422 error when "seven" cannot be parsed as an integer.

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/products/{product_id}")
def get_product(product_id: int, currency: str = "INR"):   # path + query params, typed
    return {"id": product_id, "currency": currency}

client = TestClient(app)          # calls the app in-process, no server needed
for url in ["/products/7", "/products/7?currency=USD", "/products/seven"]:
    r = client.get(url)
    print(r.status_code, r.json())

Output:

200 {'id': 7, 'currency': 'INR'}
200 {'id': 7, 'currency': 'USD'}
422 {'detail': [{'type': 'int_parsing', 'loc': ['path', 'product_id'], 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'seven'}]}

Use TestClient while learning

TestClient calls your app in-process, perfect for experiments and tests without starting a server.

Quick check: What status does FastAPI return when a typed parameter cannot be parsed?

  • 301 Moved
  • 500 Internal Server Error
  • 200 OK
  • 422 Unprocessable Entity
Answer

422 Unprocessable Entity — Validation errors are 422 by default.