Skip to content

Declarative APIs

We have received data from paths, query parameters, and request bodies, and used response models to describe output. These examples share a pattern: declare the expected data, and FastAPI handles requests and responses according to those declarations. This is central to how FastAPI works.

Imperative and Declarative Styles

Two ways to express a program's behavior are imperative and declarative programming.

Imperative programming specifies what the computer should do, step by step. Like writing a recipe, it spells out the procedure and its order.

An imperative approach to validating a post ID might look like this:

main.py
from fastapi import HTTPException, Request


@app.get("/posts/{post_id}", summary="Get a post")
def get_post_handler(request: Request):
    raw_post_id = request.path_params["post_id"]

    try:
        post_id = int(raw_post_id)
    except ValueError:
        raise HTTPException(status_code=422, detail="The post ID must be an integer.")

    if not 1 <= post_id <= 2:
        raise HTTPException(status_code=422, detail="The post ID must be 1 or 2.")

    for post in posts:
        if post["id"] == post_id:
            return post

Declarative programming instead expresses the desired result or constraints. Think of ordering an omelet: you ask for the dish and let the cook decide the steps.

Similarly, declare the expected type and allowed range of a post ID, and FastAPI checks both:

main.py
@app.get("/posts/{post_id}", summary="Get a post")
def get_post_handler(
    post_id: int = Path(ge=1, le=2),
):
    for post in posts:
        if post["id"] == post_id:
            return post

This expresses the API's requirements concisely. FastAPI reads the expected types from Python annotations and uses Pydantic to validate the constraints.

How FastAPI Interprets Parameters

FastAPI examines parameter names and types to determine where input comes from. Let's use a post preview API to receive path, query, and body values in one request.

A preview shows how a post will look before saving or publishing. This API returns its title and content; when show_content is false, it returns an empty content string.

main.py
class PostPreviewRequest(BaseModel):
    title: str
    content: str


@app.post("/posts/{post_id}/preview")
def preview_post_handler(
    post_id: int,  # ①
    show_content: bool,  # ②
    body: PostPreviewRequest,  # ③
):
    return {
        "id": post_id,
        "title": body.title,
        "content": body.content if show_content else "",
    }

Suppose the request is POST /posts/1/preview?show_content=true with body {"title": "First post", "content": "Starting my blog"}.

  • ① post_id is a path parameter.

    Its name matches {post_id} in the route. FastAPI reads the path value and converts it to integer 1.

  • ② show_content is a query parameter.

    Its name is absent from the path, and its type is bool, so FastAPI reads it from the query string. With no default, it is required.

  • ③ body receives the request body.

    PostPreviewRequest is a Pydantic model, so FastAPI reads JSON from the body, validates it, and passes a model instance to body.

You can also explicitly declare where each value comes from:

main.py
from fastapi import Body, Path, Query


@app.post("/posts/{post_id}/preview")
def preview_post_handler(
    post_id: int = Path(ge=1),  # ①
    show_content: bool = Query(default=True),  # ②
    body: PostPreviewRequest = Body(),  # ③
):
    return {
        "id": post_id,
        "title": body.title,
        "content": body.content if show_content else "",
    }

Path(), Query(), and Body() designate the path, query string, and request body respectively.

  • ① Path(ge=1) requires an ID of at least 1. Adding lt=100 narrows it to values below 100.
  • ② Query(default=True) provides a default. If the client omits show_content, the preview includes the content.
  • ③ FastAPI already recognizes a Pydantic model as body data. Body() makes that source explicit.

Annotated

Since FastAPI 0.95.0, released on March 18, 2023, request parameters can also use Annotated.

Annotated attaches metadata to a type hint. The first item in brackets is the type; subsequent items add information about it.

from typing import Annotated

display_name: Annotated[str, "Name to display"] = "Alex"

Here display_name is a str, and the second item describes its purpose.

Putting Path(), Query(), or Body() in the metadata tells FastAPI where to read and how to validate a value. The preview API becomes:

main.py
from typing import Annotated


@app.post("/posts/{post_id}/preview")
def preview_post_handler(
    post_id: Annotated[int, Path(ge=1)],
    body: Annotated[PostPreviewRequest, Body()],
    show_content: Annotated[bool, Query()] = True,
):
    return {
        "id": post_id,
        "title": body.title,
        "content": body.content if show_content else "",
    }

The FastAPI documentation recommends Annotated for new code. It is optional, and the earlier parameter style remains supported.

Annotated separates source and validation metadata from the function's default value. In show_content: Annotated[bool, Query()] = True, Query() identifies the source and = True supplies an ordinary Python default.

Using Annotated repeatedly can make parameter declarations longer. For concise examples, this guide uses the earlier style in its exercises.

Check Your Understanding

Decide whether each statement is true or false.

  1. Declarative programming expresses desired results or constraints in code.
  2. FastAPI validates input according to declared parameter types and range constraints.
  3. A request parameter declared without a default can always be omitted.
  4. A Pydantic model parameter requires an explicit body declaration to receive body data.
  5. An annotated query parameter can use an ordinary Python parameter default.
Answers and Explanations
  1. True — The interpreting system performs the steps needed to satisfy the declaration.
  2. True — FastAPI checks conversion and constraints before calling the handler.
  3. False — A parameter without a default is generally required.
  4. False — FastAPI recognizes Pydantic models as body data; an explicit declaration is optional.
  5. True — Metadata describes the input, while = value supplies the default.