0
0
FastAPIframework~5 mins

Automatic API documentation (Swagger UI) in FastAPI

Choose your learning style9 modes available
Introduction

Automatic API documentation helps you see and test your API easily without writing extra docs.

You want to quickly check what API endpoints your app has.
You want to test API calls directly from a web page.
You want to share API details with teammates or users without extra work.
You want to keep API docs updated automatically as you change code.
Syntax
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
FastAPI automatically creates Swagger UI docs at /docs URL.
You do not need to add extra code for basic API docs.
Examples
This simple API has one GET endpoint. Swagger UI will show it automatically.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
async def say_hello():
    return {"message": "Hello World"}
FastAPI uses the Item model to show input fields in Swagger UI for POST requests.
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
async def create_item(item: Item):
    return item
Sample Program

This API has a POST endpoint to create a user. Swagger UI will show the input form for username and email automatically.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    username: str
    email: str

@app.post("/users/")
async def create_user(user: User):
    return {"message": f"User {user.username} created", "email": user.email}
OutputSuccess
Important Notes

You can also access ReDoc docs at /redoc URL for a different style.

Swagger UI updates automatically when you change your API code and restart the server.

Summary

FastAPI provides automatic API docs with Swagger UI at /docs.

You do not need to write extra documentation code for basic API docs.

Swagger UI lets you test API endpoints interactively in the browser.