FastAPI Documentation Best Practices: Using Swagger, Redoc, and Scalar for Production-Ready APIs
How to write and automate API documentation for AI apps.
APIs (Application Programming Interfaces) are critical interfaces that power everything from mobile apps to AI systems, facilitating cross-solution communications. For AI engineers, APIs have become indispensable—they act as bridges for exchanging data, abstracting complex AI model inference, and deploying cutting-edge solutions, such as fine-tuned large language models (LLMs).
But here’s the catch: an API is only as good as its documentation. Without clear, accessible documentation, even the most brilliant API can become a source of frustration for developers and users alike.
FastAPI is a modern Python framework that not only makes building APIs fast and intuitive but also comes with powerful, self-documenting features. By leveraging the OpenAPI standard, FastAPI automatically generates interactive documentation that developers can easily explore and test.
In this article, we’ll dive into how you can use tools like Swagger, Redoc, and Scalar to create professional, production-ready API documentation with FastAPI. Whether you’re new to programming or an experienced developer, this guide will walk you through the essentials, sprinkle in some advanced insights, and provide hands-on examples to get you started.
If you are new to FastAPI, read this article to learn the basics of how to create and host FastAPIs for free.
Why APIs Matter and Why Documentation Is Non-Negotiable
An API is like a waiter in a restaurant that allows you to interact with external tools/solutions:
It takes your order (a request),
Delivers it to the kitchen (the system), and
Brings back your food (the response).
For AI developers, APIs play three critical roles:
Data Exchange: APIs allow AI systems to send and receive data from storage solutions or even paid services (e.g., web extraction APIs, Twitter API).
Abstracting AI Models: They provide a simple interface to interact with complex AI logic, hiding the messy details of model inference (e.g., predicting outcomes from trained models).
Deploying LLM Tools: APIs make it possible to serve fine-tuned language models (like ChatGPT-style systems) to applications worldwide.
But now imagine having to order meals from that waiter(API) without a menu, or worse, with a menu that’s confusing and incomplete. That’s where API documentation comes in. Good documentation ensures that developers (and even non-technical stakeholders) can effectively understand how to use the API. It reduces guesswork, speeds up integration, and minimizes the need for constant support.
FastAPI shines here because it’s designed to be self-documenting. As you write your code, it generates documentation automatically using the OpenAPI standard—a widely adopted format for describing APIs.
55% of API providers use documentation tools to create high-quality APIs. These tools help ensure clarity and consistency, making APIs more reliable and user-friendly.
69% of organizations rely on the OpenAPI Specification in their API development. OpenAPI’s structured approach has become a gold standard for describing APIs, and it’s the backbone of FastAPI’s documentation system.
—Smart Bear’s State of API Report 2019 (Surveyed over 3,000 API practitioners)
FastAPI’s Built-In Documentation
FastAPI isn’t just fast—it’s smart. It offers numerous features that make documentation easy to implement, especially for beginners. Let’s break down its key tools and how they work with OpenAPI.
Key Features of FastAPI Documentation
Pydantic Models
Pydantic is a library that FastAPI uses to define data structures, enforcing consistency of data types and structure (such as“User”
or“Item”
). It ensures data is valid and automatically generates documentation for request and response formats.
Example: Define a Pydantic model“User”
with variables ID, name, and email, and FastAPI documents it for you.class User(BaseModel): """ Represents a user in the system. """ id: int = Field(..., example=1, description="Unique identifier for the user") name: str = Field(..., example="Alice", description="Full name of the user") email: str = Field(..., example="alice@example.com", description="User's email address")
Parameters and Examples
Use Python’s type hints (e.g., int, str) to specify inputs like IDs or query terms. Add examples to show what valid data looks like.@router.get( "/", response_model=list[User], summary="List all users", description="Retrieve a list of all registered users.", responses={ 200: { "description": "Successful Response", "content": { "application/json": { "example": [ {"id":1, "name":"Alice", "email":"alice@example.com"} ] } } } } )
Docstrings
Write descriptions in your code using Python docstrings. FastAPI pulls these into the documentation—perfect for explaining what an endpoint does.async def read_users(): """ Endpoint to fetch all users. """ return list_users()
Markdown Integration
Add rich formatting (like bold text or lists) to your descriptions using Markdown, making them more engaging.async def read_user(user_id: int): """ Get user by ID. - **user_id**: integer ID of the user to retrieve """ user = get_user(user_id) if not user: raise HTTPException(status_code=404, detail="User not found") return user
HTML Metadata
Customize how your documentation looks—like adding a logo or links—using HTML tweaks.
OpenAPI: The Standard Behind It All
FastAPI’s documentation is powered by OpenAPI, a specification that describes APIs in a structured way. Here’s what OpenAPI covers:
Resources: The “things” your API manages (e.g., users, items).
Properties: Details about those things (e.g., a user’s name or email).
Endpoints: The URLs you call (e.g., /users/1 to get a user).
Operations: Actions like GET (retrieve) or POST (create).
Parameters: Inputs like IDs or search terms.
Authentication: How to secure access (e.g., API keys).
Why does OpenAPI matter?
It’s universal—69% of organizations use it (Smart Bear)—and it ensures your API plays well with other tools and systems. FastAPI uses OpenAPI to generate a schema (a blueprint of your API), which Swagger, Redoc, and Scalar then turn into beautiful documentation.
If you're curious, learn more about OpenAPI here.
Defining Documentation in FastAPI
Here’s a simple example:
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
id: int = Field(..., example=1, description="Unique identifier")
name: str = Field(..., example="Book", description="Item name")
price: float = Field(..., example=12.99, description="Price in USD")
@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
"""Fetch an item by its ID."""
return {"id": item_id, "name": "Book", "price": 12.99}
Run this with uvicorn main:app --reload
, and FastAPI creates documentation automatically.
Let’s see how to enhance it with our three tools.
Tools for Automated API Documentation
1. Swagger UI
Key Features:
Interactive: Test endpoints right in your browser.
Shows parameters, models, and examples clearly.
Unique Selling Points:
Perfect for developers who want to experiment with the API live.
Supports authentication testing.
When to Use:
During development or when sharing with technical users.
How to Generate:
Visit
http://localhost:8000/docs
when your FastAPI app is running. It’s built-in!
2. Redoc
Key Features:
Clean, readable layout with dark mode support.
Responsive design for all devices.
Unique Selling Points:
Visually appealing—great for public-facing docs.
Simplifies complex APIs with a clear structure.
When to Use:
For polished documentation aimed at a broad audience.
How to Generate:
Access it at
http://localhost:8000/redoc
. Also built-in!
3. Scalar
Key Features:
Creates static HTML docs you can host anywhere.
Supports Markdown and custom branding.
Unique Selling Points:
Ideal for offline use or custom styling.
Flexible for unique project needs.
When to Use:
When you need standalone docs or heavy customization.
How to Generate:
Add the
scalar-fastapi
package and a custom endpoint (see below).
from scalar_fastapi import get_scalar_api_reference
@app.get("/scalar", include_in_schema=False)
async def scalar_html():
return get_scalar_api_reference(openapi_url=app.openapi_url, title=app.title)
Hands-On Tutorial: Building a Documented FastAPI Project
Let’s put it all together with a beginner-friendly project. We’ll create a small API with users and items, organized with routers and services, and generate rich documentation.
Project Setup
Install Dependencies:
pip install fastapi uvicorn scalar-fastapi pydantic
Project Structure:
codelab_6/ ├── app/ │ ├── main.py │ ├── routers/ │ │ ├── users.py │ │ └── items.py │ └── services/ │ ├── users_service.py │ └── items_service.py ├── requirements.txt └── README.md
Full Code
Visit this GitHub Repo to access the full code.
Running the Project
Save the files in the structure above.
Run the app:
uvicorn app.main:app --reload
Explore the documentation:
Swagger:
http://localhost:8000/docs
Redoc:
http://localhost:8000/redoc
Scalar:
http://localhost:8000/scalar
Conclusion
FastAPI’s integration with OpenAPI, paired with tools like Swagger, Redoc, and Scalar, empowers you to create documentation that’s both beginner-friendly and production-ready. Start small with the tutorial above, experiment with these tools, and watch your APIs become more accessible and impactful. Happy coding!