What is Swagger UI?¶
FastAPI natively uses Swagger UI as its API documentation tool. It visualizes your API endpoints, enabling developers to easily test and understand interface parameters and return results. However, the default interface may appear monotonous and not align with your project’s style. Customizing Swagger UI can make your API documentation more professional, visually appealing, and even incorporate brand elements to enhance the user experience.
1. Modify Basic Information: Personalize Your Documentation¶
The most basic aesthetic enhancement involves customizing Swagger UI’s title, description, version, and other details. These parameters are set directly when creating your FastAPI application.
Example Code:
from fastapi import FastAPI
app = FastAPI(
title="My Online Book API", # Title displayed at the top of Swagger UI
description="This is an API for managing book information, supporting CRUD operations.\n**Document Update Date**: 2023-10-01", # Description (supports line breaks)
version="1.0.0", # API version
terms_of_service="https://example.com/terms", # Link to terms of service
contact={ # Contact information
"name": "Development Team",
"email": "dev@example.com"
}
)
@app.get("/books")
def get_books():
return [{"id": 1, "title": "Python Basics", "author": "Zhang San"}]
Effect: After accessing /docs, the Swagger UI will display your custom title, description, and version at the top. Contact information and terms of service links will appear on the right.
2. Customize Theme Styles: Make the Interface “Look Good”¶
The default Swagger UI uses a blue-and-white color scheme. You can modify the background, button colors, fonts, etc., using CSS to create a unique style. Here are two simple methods:
Method 1: Inject CSS Directly (Quick Modifications)¶
Inject custom CSS during Swagger UI page loading using middleware, without creating additional files.
Example Code:
from fastapi import Request, FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.middleware("http")
async def custom_swagger_css(request: Request, call_next):
response = await call_next(request)
# Apply only to the Swagger UI page
if request.url.path == "/docs" and response.status_code == 200:
# Inject custom CSS
custom_css = """
<style>
/* Background color */
body {
background-color: #f8f9fa;
font-family: "Microsoft YaHei", sans-serif; /* Change font */
}
/* Top navigation bar color */
.swagger-ui .topbar {
background-color: #2c3e50;
}
/* Button color */
.btnTry {
background-color: #3498db;
color: white;
border-color: #2980b9;
}
/* Button hover effect */
.btnTry:hover {
background-color: #2980b9;
}
/* Title color */
h2 {
color: #2c3e50;
}
</style>
"""
# Insert CSS into the HTML <head> tag
body = response.body.decode()
head_start = body.find("<head>")
if head_start != -1:
new_body = body[:head_start+5] + custom_css + body[head_start+5:]
response.body = new_body.encode()
return response
Effect: The background turns light gray, the top navigation bar turns black, and button/title colors are adjusted.
Method 2: Inject CSS via Static Files (Complex Styles)¶
For more complex styles (e.g., custom logos, background images), place CSS in static files.
- Create a Static Directory: In your project root, create a
staticfolder and addcustom.css:
/* static/custom.css */
/* Replace default Swagger logo */
.swagger-ui .topbar .link img {
content: url('/static/logo.png'); /* Replace with your logo path */
height: 30px;
width: auto;
}
/* Modify button color */
.btnExecute {
background-color: #4CAF50 !important;
border-color: #45a049 !important;
}
/* Adjust font size */
.swagger-ui .opblock .section {
font-size: 14px;
}
- Associate Static Files with FastAPI:
from fastapi.staticfiles import StaticFiles
app.mount("/static", StaticFiles(directory="static"), name="static")
- Inject CSS into Swagger UI: Add a
<link>tag in the HTML template (e.g., via middleware or template injection).
3. Hide Sensitive Information: Enhance Professionalism¶
By default, Swagger UI displays all fields. To hide sensitive data (e.g., passwords, tokens), use these techniques:
1. Hide Pydantic Model Fields¶
Exclude fields in Pydantic models using Field(exclude=True):
from pydantic import BaseModel, Field
class User(BaseModel):
id: int
name: str
password: str = Field(..., exclude=True) # Hide the password field
2. Hide Response Model Fields¶
Exclude fields in API responses with response_model_exclude:
@app.get("/user", response_model_exclude=["password"])
def get_user():
return {"id": 1, "name": "Alice", "password": "secret"}
4. Advanced Tips: Deeper Customization¶
- Modify Page Layout: Adjust maximum width (e.g.,
max-width: 1200px) or hide the sidebar via CSS. - Add Custom Instructions: Use Markdown in descriptions (FastAPI supports Markdown rendering) to include “usage tips.”
- Replace “Try it out” Button: Customize the button icon/text using CSS and icon fonts (e.g., Font Awesome).
Summary¶
Customizing Swagger UI relies on basic information configuration, CSS injection, and field/parameter control. Beginners can start with simple changes like modifying titles or button colors, then gradually experiment with complex styles. Note that CSS selectors may change with Swagger UI versions—test compatibility for your specific version.
With these techniques, your API documentation will not only clearly display endpoints but also become part of your project’s brand identity, offering a smoother developer experience!