Bird
Raised Fist0
FastAPIframework~10 mins

Automatic API documentation (Swagger UI) in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Automatic API documentation (Swagger UI)
Define FastAPI app
↓
Create API endpoints
↓
Run FastAPI server
↓
Access /docs URL
↓
Swagger UI loads
↓
View interactive API docs
↓
Try API calls from UI
This flow shows how FastAPI automatically generates interactive API docs using Swagger UI when you run the server and visit /docs.
Execution Sample
FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
Defines a FastAPI app with one GET endpoint that returns the item_id passed in the URL.
Execution Table
StepActionEvaluationResult
1Define FastAPI appapp = FastAPI()App instance created
2Define GET endpoint /items/{item_id}Function read_item registeredEndpoint ready
3Run FastAPI serverServer starts listeningAPI available at localhost
4Open browser at /docsRequest Swagger UI pageSwagger UI loads
5Swagger UI reads OpenAPI schemaAuto-generated from appInteractive docs shown
6User tries GET /items/5 in UIRequest sent to serverResponse {"item_id":5} shown
7User tries GET /items/abc in UIInvalid int parameterError response shown
8ExitUser closes browser or stops serverDocs no longer accessible
💡 User stops server or closes docs page, ending interaction
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 6Final
appundefinedFastAPI instanceFastAPI instance with endpointRunning server instanceRunning server instanceStopped or running depending on user
item_idundefinedundefinedundefinedundefined5 (from UI request)undefined
Key Moments - 3 Insights
Why does the /docs page show the API without extra code?
FastAPI automatically generates OpenAPI schema from your endpoint definitions, which Swagger UI uses to build the docs (see execution_table step 5).
What happens if I enter a wrong type like a string instead of int for item_id?
FastAPI validates parameters and returns an error response automatically (see execution_table step 7).
Do I need to write any HTML or JavaScript for the docs?
No, FastAPI includes Swagger UI by default and serves it at /docs (see execution_table steps 4 and 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result of step 5?
AServer starts listening for requests
BUser tries GET /items/5 in UI
CSwagger UI loads and shows interactive API docs
DFunction read_item registered
💡 Hint
Check the 'Result' column in step 5 of the execution_table
At which step does the server start listening for requests?
AStep 2
BStep 3
CStep 6
DStep 1
💡 Hint
Look at the 'Action' and 'Result' columns in the execution_table
If you change the endpoint path to /products/{item_id}, which step changes in the execution table?
AStep 2 - Defining the GET endpoint
BStep 6 - Trying GET /items/5
CStep 4 - Opening /docs URL
DStep 7 - Invalid parameter error
💡 Hint
Changing the endpoint path affects the endpoint registration step
Concept Snapshot
FastAPI auto-generates API docs at /docs using Swagger UI.
Define endpoints with decorators like @app.get.
Run server, visit /docs to see interactive docs.
Docs show all endpoints and allow trying calls.
No extra code needed for docs.
Parameter validation and errors shown automatically.
Full Transcript
This visual execution shows how FastAPI creates automatic API documentation using Swagger UI. First, you define a FastAPI app and add endpoints with decorators. When you run the server, it listens for requests. Visiting the /docs URL loads Swagger UI, which reads the OpenAPI schema generated from your endpoints. This displays interactive API documentation where you can try API calls. FastAPI also validates parameters and shows errors if inputs are wrong. No extra code is needed to get this documentation. The execution table traces each step from app creation to user interaction with the docs.

Practice

(1/5)
1. What is the default URL path where FastAPI serves the automatic API documentation using Swagger UI?
easy
A. /docs
B. /swagger
C. /api-docs
D. /documentation

Solution

  1. Step 1: Understand FastAPI default docs path

    FastAPI automatically provides Swagger UI documentation at the path '/docs' by default.
  2. Step 2: Compare options with default path

    Among the options, only '/docs' matches the default URL for Swagger UI in FastAPI.
  3. Final Answer:

    /docs -> Option A
  4. Quick Check:

    Default Swagger UI docs path = /docs [OK]
Hint: Remember: FastAPI docs are at /docs by default [OK]
Common Mistakes:
  • Confusing /swagger with /docs
  • Assuming /api-docs is default
  • Thinking documentation is at root /
2. Which of the following code snippets correctly imports and creates a FastAPI app that will have automatic Swagger UI documentation?
easy
A. import fastapi app = fastapi.App()
B. from fastapi import API app = API()
C. from fastapi import FastAPI app = FastAPI()
D. import FastAPI app = FastAPI()

Solution

  1. Step 1: Check correct import and app creation

    The correct import is 'from fastapi import FastAPI' and app is created by calling FastAPI().
  2. Step 2: Validate each option

    from fastapi import FastAPI app = FastAPI() matches the correct syntax. Options A, C, and D have wrong imports or class names.
  3. Final Answer:

    from fastapi import FastAPI\napp = FastAPI() -> Option C
  4. Quick Check:

    Correct import and app creation = from fastapi import FastAPI app = FastAPI() [OK]
Hint: FastAPI app is created by FastAPI() after correct import [OK]
Common Mistakes:
  • Using wrong import names like API or App
  • Trying to import FastAPI with capital letter as module
  • Calling wrong constructor names
3. Given this FastAPI code snippet, what will you see when you open http://localhost:8000/docs in your browser?
from fastapi import FastAPI
app = FastAPI()

@app.get("/hello")
def say_hello():
    return {"message": "Hello, world!"}
medium
A. A 404 Not Found error because /docs is not defined
B. A plain JSON response with {"message": "Hello, world!"}
C. A blank page with no content
D. An interactive Swagger UI showing the /hello GET endpoint with a Try it out button

Solution

  1. Step 1: Understand FastAPI automatic docs behavior

    FastAPI automatically generates Swagger UI at /docs showing all defined endpoints.
  2. Step 2: Analyze the given code

    The code defines a GET endpoint /hello. The docs page will list this endpoint with interactive testing.
  3. Final Answer:

    An interactive Swagger UI showing the /hello GET endpoint with a Try it out button -> Option D
  4. Quick Check:

    FastAPI auto docs show endpoints interactively at /docs [OK]
Hint: Open /docs to see interactive API docs with all endpoints [OK]
Common Mistakes:
  • Expecting JSON response at /docs instead of UI
  • Thinking /docs must be manually coded
  • Confusing /docs with endpoint paths
4. You wrote this FastAPI app but when you visit /docs, you get a 404 error. What is the likely cause?
from fastapi import FastAPI
app = FastAPI()

@app.get("/items")
def read_items():
    return [{"item_id": 1}]

# You run the app with: uvicorn main:app --port 8000 --host 0.0.0.0

# But /docs returns 404
medium
A. You are running the app with the wrong module or app name
B. The endpoint /items is missing
C. You need to add extra code to enable /docs
D. You forgot to import FastAPI

Solution

  1. Step 1: Check the run command and app reference

    The command 'uvicorn main:app' requires a file named main.py with an app variable.
  2. Step 2: Identify mismatch causing 404 on /docs

    If the file or app name is wrong, uvicorn won't serve the correct app, so /docs is missing.
  3. Final Answer:

    You are running the app with the wrong module or app name -> Option A
  4. Quick Check:

    Run command must match file and app names exactly [OK]
Hint: Match uvicorn run command module:app exactly [OK]
Common Mistakes:
  • Assuming /docs needs manual enabling
  • Forgetting to import FastAPI (but code shows import)
  • Thinking missing endpoint causes /docs 404
5. You want to customize the automatic API docs path from the default /docs to /api-docs. Which FastAPI app creation code achieves this?
hard
A. app = FastAPI(swagger_ui_url="/api-docs")
B. app = FastAPI(docs_url="/api-docs")
C. app = FastAPI(openapi_url="/api-docs")
D. app = FastAPI(docs_path="/api-docs")

Solution

  1. Step 1: Identify FastAPI parameter for docs path

    The parameter to change Swagger UI docs path is docs_url.
  2. Step 2: Match option with correct parameter

    app = FastAPI(docs_url="/api-docs") uses docs_url="/api-docs", which correctly changes the docs path.
  3. Final Answer:

    app = FastAPI(docs_url="/api-docs") -> Option B
  4. Quick Check:

    Change docs path with docs_url parameter [OK]
Hint: Use docs_url to set custom docs path [OK]
Common Mistakes:
  • Using swagger_ui_url which changes UI assets path
  • Changing openapi_url affects JSON schema, not docs UI
  • Using docs_path which is not a valid parameter
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard