FastAPI: From Basics to Production · FastAPI Basics

Hello FastAPI

Install FastAPI, run the dev server and write your first endpoints.

FastAPI is a modern Python web framework built on Starlette (ASGI) and Pydantic. You declare endpoints with type hints, and FastAPI validates input, serializes output and generates OpenAPI docs automatically. Install fastapi[standard] to get Uvicorn and the fastapi CLI: fastapi dev main.py runs with auto-reload; fastapi run is the production mode.

# main.py
from fastapi import FastAPI

app = FastAPI(title="Bookstore API", version="1.0.0")


@app.get("/health")
async def health() -> dict[str, str]:
    return {"status": "ok"}


@app.get("/books/{book_id}")
async def get_book(book_id: int) -> dict:
    return {"id": book_id, "title": "Dune"}
python -m venv .venv && source .venv/bin/activate
pip install "fastapi[standard]"
fastapi dev main.py          # http://127.0.0.1:8000 and /docs

Common pitfalls

  • Running fastapi dev (auto-reload) in production.
  • Declaring book_id without a type — you lose validation and conversion.
  • Naming your file fastapi.py, shadowing the package.

Key points

  • Type hints drive validation and docs
  • fastapi dev for development, fastapi run for production
  • Interactive docs at /docs

Further reading: FastAPI tutorial: First steps

Practice questions

What happens if a client requests /books/abc when book_id: int?

Answer

FastAPI validates the path parameter and returns a 422 Unprocessable Entity response describing the error; your function isn't called.

What's the difference between fastapi dev and fastapi run?

Answer

fastapi dev enables auto-reload and listens on localhost for development; fastapi run runs without reload, listening on all interfaces, for production.

Open in the app to mark lessons complete, take notes and track your progress.