0
0
FastapiHow-ToBeginner · 3 min read

How to Use Swagger UI in FastAPI: Simple Guide

FastAPI automatically provides Swagger UI at /docs endpoint to interact with your API. Just create a FastAPI app and run it; visit http://localhost:8000/docs to see the Swagger UI with your API endpoints.
📐

Syntax

FastAPI includes Swagger UI by default. You just need to create a FastAPI app instance. The /docs URL serves the Swagger UI automatically. You can customize or disable it if needed.

  • FastAPI(): Creates the app.
  • /docs: Default path for Swagger UI.
  • /openapi.json: JSON schema used by Swagger UI.
python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}
💻

Example

This example shows a simple FastAPI app with one GET endpoint. When you run it, open http://localhost:8000/docs in your browser to see the Swagger UI. It lists the endpoint and lets you test it interactively.

python
from fastapi import FastAPI
from typing import Optional

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

# Run with: uvicorn filename:app --reload
Output
Visit http://localhost:8000/docs to see Swagger UI with the /items/{item_id} endpoint.
⚠️

Common Pitfalls

1. Not running the app with an ASGI server like uvicorn: Swagger UI won't appear if the app isn't running.

2. Trying to access Swagger UI on a different path: By default, Swagger UI is at /docs. Customizing requires extra parameters.

3. Disabling docs accidentally: Passing docs_url=None disables Swagger UI.

python
from fastapi import FastAPI

# Wrong: disables Swagger UI
app = FastAPI(docs_url=None)

@app.get("/")
async def root():
    return {"msg": "No docs here"}

# Right: default docs enabled
app = FastAPI()

@app.get("/")
async def root():
    return {"msg": "Docs available at /docs"}
📊

Quick Reference

  • Default Swagger UI URL: /docs
  • OpenAPI JSON URL: /openapi.json
  • Disable Swagger UI: Use FastAPI(docs_url=None)
  • Use ReDoc UI: Available at /redoc by default

Key Takeaways

FastAPI provides Swagger UI automatically at /docs without extra setup.
Run your FastAPI app with uvicorn to access Swagger UI in the browser.
Do not disable docs_url unless you want to hide Swagger UI.
Swagger UI lets you test API endpoints interactively and see request/response details.
You can also access ReDoc UI at /redoc for alternative API docs.