Skip to content
devtoolbox.cc

FastAPI · Chapter 1 of 6

FastAPI tutorial: first app, routes, path and query parameters

13 min study · Examples checked with FastAPI 0.163 on Python 3.14 ·

FastAPI is a Python framework for building HTTP APIs. You write ordinary functions, annotate their parameters with types, and FastAPI turns each function into an endpoint: it reads values from the request, converts and validates them, calls your function, and turns the return value into JSON. From the same annotations it generates interactive documentation. This chapter builds a small study-tracker API and covers routes, path and query parameters, validation errors, and how to test endpoints without starting a server.

Install and run a first application

FastAPI needs Python 3.11 or newer; this track was checked with Python 3.14. In a new project folder with a virtual environment (see the Python setup chapter), install it with the optional standard extras, which add the development server and its command-line tool:

python -m pip install "fastapi[standard]"

Save this as main.py:

from typing import Annotated

from fastapi import FastAPI, Path, Query

app = FastAPI(title="Study Tracker API", version="1.0.0")


@app.get("/")
def home():
    return {"message": "Study Tracker API", "docs": "/docs"}


@app.get("/lessons/latest")
def latest_lesson():
    return {"id": 21, "title": "asyncio"}


@app.get("/lessons/{lesson_id}")
def read_lesson(lesson_id: Annotated[int, Path(gt=0, le=10_000)]):
    return {"id": lesson_id, "title": f"Lesson {lesson_id}"}


@app.get("/search")
def search(
    q: Annotated[str, Query(min_length=2, max_length=50)],
    limit: Annotated[int, Query(ge=1, le=50)] = 10,
    tag: Annotated[list[str] | None, Query()] = None,
    published: bool | None = None,
):
    return {"q": q, "limit": limit, "tags": tag or [], "published": published}

Start it with fastapi dev main.py and open http://127.0.0.1:8000/docs. You get a page listing every endpoint, with a “Try it out” button that sends real requests; /openapi.json holds the same description in the machine-readable OpenAPI format, which client generators and API tools read. fastapi dev reloads on every file change, which is convenient while writing code. In production you run fastapi run main.py or another ASGI server without the reloader.

How a request reaches your function

app is an ASGI application, the standard interface between Python web frameworks and servers. The server (Uvicorn, started by the fastapi command) accepts connections and hands each HTTP request to app. FastAPI then compares the request’s method and path with the registered routes. @app.get("/lessons/{lesson_id}") registers read_lesson for GET requests whose path matches that pattern; @app.post, @app.put, @app.patch and @app.delete work the same way for other methods.

For GET /lessons/3, FastAPI extracts "3" from the path, converts it to the declared int, checks the constraints (gt=0, le=10_000), calls read_lesson(lesson_id=3) and serializes the returned dictionary as JSON with status 200. Routes are checked in the order they were declared, which is why /lessons/latest comes before /lessons/{lesson_id}: in the other order, latest would match the pattern and fail integer validation. The handler only invents a title here. Whether lesson 3 actually exists is a question for a database and a 404 response, both in later chapters.

Path parameters and query parameters

A path parameter is part of the address and identifies a resource: /lessons/3. A query parameter comes after ? and adjusts the request: /search?q=py&limit=5. FastAPI decides which is which from the function signature. A name that appears in the path pattern is a path parameter; any other simple parameter is a query parameter.

Annotated[int, Query(ge=1, le=50)] combines the Python type with FastAPI metadata: ge/le and gt/lt bound numbers, min_length/max_length and pattern constrain strings. A parameter without a default, like q, is required. One with a default is optional. A list[str] declared with Query() collects repeated parameters, so ?tag=web&tag=api arrives as ["web", "api"]. Booleans accept true/false, 1/0, yes/no and on/off. Note the difference between “may be null” and “may be left out”: published: bool | None = None is both, but a parameter typed str | None with no default must still be sent.

What the client sees when validation fails

Requests that break the declared rules never reach your function. FastAPI answers with status 422 and a list of problems. These are real responses from the application above:

GET /lessons/abc   -> 422
{"detail": [{"type": "int_parsing", "loc": ["path", "lesson_id"],
  "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "abc"}]}

GET /lessons/0     -> 422
{"detail": [{"type": "greater_than", "loc": ["path", "lesson_id"],
  "msg": "Input should be greater than 0", "input": "0", "ctx": {"gt": 0}}]}

GET /search?limit=5 -> 422
{"detail": [{"type": "missing", "loc": ["query", "q"], "msg": "Field required", "input": null}]}

GET /search?q=py&tag=web&tag=api&published=yes -> 200
{"q": "py", "limit": 10, "tags": ["web", "api"], "published": true}

Each error says where the bad value was (loc: path, query, body or header, then the name), what was wrong and what was received. Clients can show these messages next to the right form field. Other status codes mean other things: an unknown path returns 404 {"detail": "Not Found"}, and a known path with the wrong method returns 405 Method Not Allowed with an Allow header naming the methods that do work. Unknown query parameters are silently ignored, so a typo like ?limt=5 leaves limit at its default; that is worth knowing when a client reports that a setting “does nothing”.

def or async def?

Both work as handlers. Use async def when the function awaits asynchronous libraries, such as an async HTTP client or database driver. Use plain def when it calls ordinary blocking code; FastAPI runs those handlers in a thread pool so they don’t stall other requests. The mistake to avoid is calling a blocking library (like requests or a synchronous database driver) inside async def, which freezes the event loop for every client (asyncio chapter). The handlers here do no I/O, so plain def is the simple choice.

Test endpoints with TestClient

You don’t need a running server to check an API. TestClient sends requests directly to the application object; with pytest installed, save this next to main.py as test_main.py and run python -m pytest:

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def test_read_lesson():
    response = client.get("/lessons/3")
    assert response.status_code == 200
    assert response.json() == {"id": 3, "title": "Lesson 3"}


def test_fixed_route_wins():
    assert client.get("/lessons/latest").json()["id"] == 21


def test_rejects_bad_id():
    response = client.get("/lessons/0")
    assert response.status_code == 422
    assert response.json()["detail"][0]["loc"] == ["path", "lesson_id"]


def test_repeated_query_parameters():
    data = client.get("/search", params={"q": "py", "tag": ["web", "api"]}).json()
    assert data["tags"] == ["web", "api"] and data["limit"] == 10

Each test sends a request and checks both the status code and the body. Testing the error responses is as important as the happy path, because clients depend on them. params builds the query string, including repeated keys from a list.

Practice

Add GET /topics/{slug} where slug is lowercase letters and hyphens only, 2 to 30 characters (Path(pattern=r"^[a-z-]+$", min_length=2, max_length=30)), plus an optional level query parameter that must be one of beginner, intermediate or advanced. Write tests for a valid request, an uppercase slug and an unknown level.

Answer check: declare level with a Literal["beginner", "intermediate", "advanced"] | None = None type, from the typing module, and FastAPI lists the allowed values in its 422 error and in /docs. /topics/Python returns 422 with loc ["path", "slug"] and type string_pattern_mismatch. A request for /topic/python (singular) returns 404, because no route matches at all.

Summary

A FastAPI route maps a method and a path to a function. Path parameters identify resources and query parameters adjust requests; types and Annotated constraints validate both before your code runs, and failures come back as 422 with exact locations. Declare fixed paths before patterns, pick def or async def by the libraries you call, and test with TestClient.

All FastAPI chapters