codejump

Your first FastAPI route

Build a small FastAPI endpoint and see how routes, path values, request bodies, and validation work together.

2 min readUpdated

3 exercises

Waiting at the end of this page.

Key takeaways

  • A method decorator such as @app.get registers a route; a name in the path is read from the URL.
  • Type annotations let FastAPI parse and validate incoming values before your handler runs.
  • Use a Pydantic model for a JSON body, an output model for the public response, and HTTPException for HTTP errors.

Start with one route

FastAPI is a Python framework for HTTP APIs. Create an application, register a route, and return a Python dictionary:

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
def health():
    return {"status": "ok"}

The decorator connects GET requests for /health to health. FastAPI turns the dictionary into a JSON response. When you run the app, the interactive API docs are available at /docs by default.

Read values from the URL

python
@app.get("/items/{item_id}")
def read_item(item_id: int, details: bool = False):
    return {"item_id": item_id, "details": details}

item_id is a path parameter because its name appears in the route. details is a query parameter because it is a simple value absent from the path. A request to /items/7?details=true passes the integer 7 and Boolean True to the function. If the path value cannot be parsed as an integer, FastAPI returns a validation error before calling the function.

Accept a JSON body

python
from pydantic import BaseModel

class ItemIn(BaseModel):
    name: str
    price: float

@app.post("/items", status_code=201)
def create_item(item: ItemIn):
    return {"name": item.name, "price": item.price}

A Pydantic model parameter describes JSON body data. FastAPI validates required fields and their types. The status_code on the decorator describes the normal success response; it does not save the item to a database. Add persistence yourself when the API needs it.

Keep the response public

Input and output often need different shapes. For an account endpoint, the input may contain a password while the output must never contain it. Declare a separate public model with response_model=...; FastAPI validates and filters the outgoing response through it. For a missing resource, raise HTTPException(status_code=404, detail="Item not found") so the client receives a real HTTP error.

Where to go next

Start with the beginner quiz to check routes and validation. Once those are comfortable, move to dependencies and API design. If Python itself is unfamiliar, review Python concepts first; FastAPI builds on ordinary functions, annotations, and decorators.

Now practice it

3 exercises

Reading this page is the cheap half. These are the exercises that make you use it.