Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Fundamentals

Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes

FastAPI reads your routes and type hints and writes an OpenAPI contract at /openapi.json. Take the real contract of a small Book API apart block by block, see where each word comes from, and how Swagger UI draws it.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Explain what OpenAPI is and where FastAPI serves it
  • Read the four main blocks of an OpenAPI document: openapi, info, paths and components
  • Trace a title, a tag description, a summary and a type hint from the code into the contract
  • Explain how Swagger UI draws the contract and sends real requests

Before you start

  • A first FastAPI route
  • JSON basics

Somebody who has never seen your code wants to use your API. Picture a developer building a phone app. Which URLs can they call? Which methods does each URL accept? What comes back? They never see your code, so they need a description that both sides can read.

FastAPI already writes that description for you, in a standard format called OpenAPI, and serves a page called Swagger UI that draws it. This article takes the real contract of a small Book API apart. If you haven't built a first FastAPI app yet, start with FastAPI hello world.

The code writes the description

Our code, the routes and type hints in books.py, is read by FastAPI at startup. FastAPI writes the OpenAPI contract as JSON at /openapi.json. Swagger UI at /docs draws that contract. Our code routes, type hints FastAPI reads them at startup The contract /openapi.json Swagger UI /docs We write code, and the description writes itself.
Code in, contract out, page drawn from the contract.

We don't write the description. FastAPI reads our routes and their type hints as the app starts, writes the contract as JSON and serves it at /openapi.json. Swagger UI is a page that draws that contract, at /docs.

Nothing to install

The project's requirements.txt:

fastapi==0.162.0
uvicorn==0.54.0

No documentation library. Yet both addresses answer. From the run log:

INFO:     127.0.0.1:49270 - "GET /openapi.json HTTP/1.1" 200 OK
INFO:     127.0.0.1:49271 - "GET /docs HTTP/1.1" 200 OK

The code that fills the contract

library/main.py gives the app a title, a version and a description for the Books tag:

from fastapi import FastAPI

from library.routers import books


app = FastAPI(
    title="Library API",
    version="1",
    openapi_tags=[{"name": "Books", "description": "Read the books of the library"}],
)
app.include_router(books.router)

library/routers/books.py has two routes, each with a summary and type hints:

router = APIRouter(prefix="/api/books", tags=["Books"])

...

@router.get("", summary="List all books", operation_id="list")
def list_books() -> list[Book]:
    return books


@router.get("/{book_id}", summary="One book", operation_id="one")
def get_book(book_id: int) -> Book:
    for book in books:
        if book.id == book_id:
            return book
    raise HTTPException(status_code=404, detail="Book not found")

And library/schemas.py describes a book:

class Book(BaseModel):
    id: int
    title: str
    author: str
    pages: int

The contract, taken apart

Here's the real /openapi.json from the run (1,730 bytes), formatted and shortened: the 200 responses and the two validation-error schemas are cut down.

{
  "openapi": "3.1.0",
  "info": {"title": "Library API", "version": "1"},
  "paths": {
    "/api/books": {
      "get": {
        "tags": ["Books"],
        "summary": "List all books",
        "operationId": "list",
        "responses": {"200": {...}}
      }
    },
    "/api/books/{book_id}": {
      "get": {
        "tags": ["Books"],
        "summary": "One book",
        "operationId": "one",
        "parameters": [
          {"name": "book_id", "in": "path", "required": true,
           "schema": {"type": "integer", "title": "Book Id"}}
        ],
        "responses": {
          "200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Book"}}}},
          "422": {"description": "Validation Error", ...}
        }
      }
    }
  },
  "components": {
    "schemas": {
      "Book": {
        "properties": {
          "id": {"type": "integer", "title": "Id"},
          "title": {"type": "string", "title": "Title"},
          "author": {"type": "string", "title": "Author"},
          "pages": {"type": "integer", "title": "Pages"}
        },
        "type": "object",
        "required": ["id", "title", "author", "pages"],
        "title": "Book"
      },
      "HTTPValidationError": {...},
      "ValidationError": {...}
    }
  },
  "tags": [{"name": "Books", "description": "Read the books of the library"}]
}
  • openapi: which standard it follows, OpenAPI 3.1.0.
  • info: who it is. The title and the version.
  • paths: what you can ask. For /api/books/{book_id} the contract says book_id goes in the path, is required and is an integer.
  • components: what comes back. A Book with four required fields, plus two schemas FastAPI adds for validation errors.
  • tags: the group names and their descriptions.

It's just JSON in a standard shape, so any tool can read it.

Where each word comes from

In the codeIn the contract
title="Library API", version="1"info
openapi_tags=[{"name": "Books", "description": ...}]tags
tags=["Books"] on the router"tags": ["Books"] on each operation
summary="One book", operation_id="one"summary, operationId of that path
book_id: intparameter book_id, in: path, type: integer
-> Book200 response $ref to #/components/schemas/Book
class Book(BaseModel)components.schemas.Book

The 422 response on the second path is FastAPI's own addition. That route has a parameter to check (book_id must be an integer), so the contract also lists a validation-error answer, using the two schemas FastAPI adds to components.

Every part of the page comes from the contract

Four contract keys map to four areas of the Swagger UI page: info to the title and version at the top, tags to the Books group and its description, paths to each method row with its address and summary, components to the Schemas area at the bottom. info tags paths components Library API, version 1 Books: Read the books of the library GET /api/books List all books GET /api/books/{book_id} One book Schemas: Book, HTTPValidationError, ...
Nothing on the Swagger page is invented. Each area is one block of the contract.

The HTML served at /docs is tiny (1,010 bytes). It loads the Swagger UI script and points it at the contract:

const ui = SwaggerUIBundle({
    url: '/openapi.json',
    ...

The title of the page is Library API - Swagger UI. Everything else is drawn from the contract in the browser: the title and version from info, the Books group from tags, each row (method, address, summary) from paths, and the Schemas area from components.

Swagger UI sends real requests

The page does more than show. Open the "One book" row, click Try it out, type 2 for book_id and click Execute. The page sends a real request to the running app:

INFO:     127.0.0.1:49268 - "GET /api/books/2 HTTP/1.1" 200 OK
{"id":2,"title":"Dune","author":"Frank Herbert","pages":412}

The status and the body show right there on the page. A book that doesn't exist, /api/books/99, comes back as 404 with {"detail":"Book not found"}.

One contract, many readers

The contract is a plain file in a standard format. Think of a menu: customers read it, cooks read it, delivery apps read it.

  • Swagger UI reads it to give you a page where you try the API.
  • ReDoc shows the same contract as a page to read.
  • A client generator reads it and writes the code for the phone app (see generating a TypeScript client with Orval).
  • A test tool can read it and check every endpoint.

Because the contract is made from the code, it stays in step with the code. If you need to move /docs or /openapi.json to other addresses, the Book API contract for a React client shows how.

Common mistakes

  • Leaving out return types. Without -> Book (or response_model), the contract can't say what comes back.
  • No summaries or tag descriptions. The page still works, but readers get bare function names instead of words.
  • Treating Swagger UI as a mock. Execute sends a real request to the running app, so a DELETE there really deletes.

Quick recap

PieceWhereMade from
OpenAPI contract/openapi.jsonroutes, type hints, titles, summaries
Swagger UI/docsdraws the contract, sends real requests
Extra packages needednoneboth come with FastAPI

Try it yourself

Change the summary of one route and the description of the Books tag, restart the app, and find both new texts in /openapi.json and on /docs.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 10 of 26

Previous
Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
Next post
POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

FastAPI Hello World: Routes, uvicorn and the Free Swagger Page

The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.

RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes

An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.

Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose

One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.

One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask

The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.

On this page

  • The code writes the description
  • Nothing to install
  • The code that fills the contract
  • The contract, taken apart
  • Where each word comes from
  • Every part of the page comes from the contract
  • Swagger UI sends real requests
  • One contract, many readers
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.