Swagger UI & ReDoc in FastAPI 🚀
FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc. These tools help developers test APIs, explore endpoints, and understand request/response formats.
🔹 What is Swagger UI?
Swagger UI provides an interactive interface where developers can:
✅ View API endpoints
✅ Send requests (GET, POST, PUT, DELETE)
✅ See request & response formats
✅ Authenticate APIs using tokens
📌 Access Swagger UI in FastAPI
When you run a FastAPI app, visit:
👉 http://127.0.0.1:8000/docs
🔹 What is ReDoc?
ReDoc is an alternative documentation tool that provides a clean, structured API reference.
✅ Better readability
✅ Supports Markdown descriptions
✅ Great for large APIs
📌 Access ReDoc in FastAPI
👉 http://127.0.0.1:8000/redoc
🔹 Example: FastAPI with Swagger UI & ReDoc
Let's create a simple FastAPI app.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# Request body model
class Item(BaseModel):
name: str
price: float
@app.get("/items/{item_id}")
async def get_item(item_id: int):
return {"item_id": item_id, "name": "Sample Item"}
@app.post("/items/")
async def create_item(item: Item):
return {"message": "Item created", "item": item}
Running the App
uvicorn main:app --reload
Open API Docs
🔹 Swagger UI → http://127.0.0.1:8000/docs
🔹 ReDoc → http://127.0.0.1:8000/redoc
🔹 Customizing Swagger UI & ReDoc
FastAPI allows customization of Swagger UI & ReDoc.
📌 Custom API Title & Description
app = FastAPI(
title="My FastAPI App",
description="A simple API with Swagger & ReDoc documentation",
version="1.0.0"
)
📌 Disabling Swagger UI or ReDoc
Disable Swagger UI:
app = FastAPI(openapi_url="/openapi.json", docs_url=None)
Disable ReDoc:
app = FastAPI(redoc_url=None)
🎯 Summary
- Swagger UI → Best for interactive API testing.
- ReDoc → Best for detailed API documentation.
- FastAPI automatically generates both at
/docs&/redoc. - Customization is possible via FastAPI parameters.
Comments
Post a Comment