Gavin Wiggins


Docstrings for a FastAPI App

Published on April 26, 2026

FastAPI automatically generates Swagger docs for your application using docstrings and other information. The docstring content must be written as Markdown because Swagger does not understand Google, NumPy, or reST docstring styles. Pydantic models can utilize docstrings and Field attributes which are used in the Swagger docs too. Application information such as title, summary, description, and contact info can be assigned to the FastAPI object. All of this is demonstrated in the example code given below.

# app.py

from fastapi import FastAPI

from models import Fruit

app = FastAPI(
    title="My FastAPI",
    version="0.9",
    summary="Short summary of my app.",
    description="The description supports **markdown** text.",
    contact={
        "name": "Homer Simpson",
        "email": "homer@springfield.com",
        "url": "https://springfield.com",
    },
)

all_fruits: list[Fruit] = [
    Fruit(name="apples", quantity=1),
    Fruit(name="oranges", quantity=2),
]


@app.get("/fruits")
async def get_fruits() -> list[Fruit]:
    """Get a list of fruits.

    This docstring must be Markdown text because Swagger/OpenAPI does not
    understand Google, NumPy, or reST docstring styles.

    Each fruit item has the following attributes:
    - **name**: Name of the fruit.
    - **quantity**: Number of fruit items.
    """
    return all_fruits


@app.post("/fruit/")
async def add_fruit(item: Fruit) -> list[Fruit]:
    """Add a fruit to the list of fruits.

    The fruit item must have the following attributes:
    - **name**: Name of the fruit.
    - **quantity**: Number of fruit items.
    """
    all_fruits.append(item)
    return all_fruits
# models.py

from pydantic import BaseModel, Field


class Fruit(BaseModel):
    """Fruit model."""

    name: str = Field("", description="Name of the fruit")
    quantity: int = Field(0, description="Quantity of the fruit")

Gavin Wiggins © 2026
Made on a Mac with Genja. Hosted on GitHub Pages.