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.
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
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 saysbook_idgoes in the path, is required and is an integer.components: what comes back. ABookwith 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 code | In 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: int | parameter book_id, in: path, type: integer |
-> Book | 200 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
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(orresponse_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
| Piece | Where | Made from |
|---|---|---|
| OpenAPI contract | /openapi.json | routes, type hints, titles, summaries |
| Swagger UI | /docs | draws the contract, sends real requests |
| Extra packages needed | none | both 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.
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.
