AI Prompt: Generate Complete FastAPI Documentation for Docusaurus
You are an expert technical documentation writer. Your task is to generate a complete, production-quality FastAPI learning reference following the gold-standard patterns used in the existing tmux/ module of this Docusaurus project.
Context
- Target platform: Docusaurus (MDX files)
- Reference standard: See
../tmux/for the exact structural and quality patterns to replicate - Output location:
/home/rezriz/github/brain-donnyaw-cf-pages/fastapi/ - Audience: Developers and operators who know Python basics and want to build production APIs with FastAPI
- Technical target: Python 3.11+, FastAPI current stable, Pydantic v2, SQLAlchemy 2.x, pytest, HTTPX, Docker, Nginx
- Rendering requirement: All generated files must build cleanly in Docusaurus v3 with MDX enabled
Non-Negotiable Output Rules
- Generate documentation files only. Do not generate unrelated app source code outside the requested docs tree.
- Keep all docs under
/home/rezriz/github/brain-donnyaw-cf-pages/fastapi/. - Use the existing
tmux/docs as the style reference, but make the FastAPI track deeper and more comprehensive. - Prefer modern FastAPI patterns:
Annotated, Pydantic v2model_config, SQLAlchemy 2 style, lifespan handlers instead of legacy startup/shutdown unless teaching migration. - Avoid deprecated patterns unless the lesson explicitly labels them as legacy and explains the modern replacement.
- Make examples copy-paste runnable where practical.
- Do not invent APIs or package behavior. If uncertain, use conservative, documented FastAPI patterns.
- Optimize for a learner who will later build real APIs, not for toy snippets only.
Directory & File Structure
Create the following directory tree under fastapi/. Every subdirectory gets a _category_.json. Every lesson is a .mdx file. Every .mdx file gets frontmatter and the full lesson template.
fastapi/
_category_.json # {"label": "FastAPI", "position": <N>, "link": {"type": "doc", "id": "index"}}
index.mdx # Track overview — what, why, architecture diagram, quick start, learning path table, prerequisites, success criteria, next step
01-introduction/
_category_.json
what-is-fastapi.mdx
installation-and-setup.mdx
first-endpoint.mdx
async-fundamentals.mdx
02-routing-and-parameters/
_category_.json
path-operations-and-decorators.mdx
path-parameters.mdx
query-parameters.mdx
request-body-and-validation.mdx
03-pydantic-models/
_category_.json
base-models-and-field-types.mdx
nested-models.mdx
model-config-and-aliases.mdx
04-response-handling/
_category_.json
response-model-and-status-codes.mdx
custom-responses.mdx
error-handling-and-http-exceptions.mdx
05-dependency-injection/
_category_.json
dependencies-basics.mdx
reusable-dependencies.mdx
global-and-path-dependencies.mdx
06-database-integration/
_category_.json
sqlalchemy-setup.mdx
crud-operations.mdx
migrations-with-alembic.mdx
async-database-engines.mdx
07-authentication-and-authorization/
_category_.json
oauth2-and-jwt.mdx
api-key-security.mdx
role-based-access-control.mdx
08-middleware-and-cors/
_category_.json
custom-middleware.mdx
cors-configuration.mdx
trust-and-proxy-headers.mdx
09-file-handling-and-static-files/
_category_.json
file-uploads.mdx
static-file-serving.mdx
streaming-responses.mdx
10-background-tasks-and-websockets/
_category_.json
background-tasks.mdx
websocket-basics.mdx
websocket-chat-example.mdx
11-testing/
_category_.json
testclient-basics.mdx
async-testing.mdx
mocking-dependencies.mdx
12-deployment/
_category_.json
docker-and-docker-compose.mdx
nginx-reverse-proxy.mdx
production-config-and-gunicorn.mdx
13-advanced-topics/
_category_.json
rate-limiting-and-caching.mdx
openapi-customization.mdx
lifespan-and-startup-shutdown.mdx
14-real-world-project-structure/
_category_.json
layered-architecture.mdx
service-layer-pattern.mdx
environment-and-settings-management.mdx
15-troubleshooting/
_category_.json
common-import-and-type-errors.mdx
async-and-blocking-issues.mdx
database-connection-errors.mdx
16-cheatsheet/
_category_.json
core-decorator-and-parameter-reference.mdx
pydantic-field-reference.mdx
dependency-patterns-cheatsheet.mdx
deployment-and-docker-commands.mdx
Every _category_.json File
Root fastapi/_category_.json
Use this exact structure:
{
"label": "FastAPI",
"position": 5,
"link": {
"type": "doc",
"id": "index"
}
}
If another sidebar position is required by the repository, preserve the local convention.
Module _category_.json
Use generated index pages for module categories so Docusaurus can render category landing pages without requiring extra index.mdx files inside every module:
{
"label": "Module Name",
"position": <module_number>,
"link": {
"type": "generated-index",
"description": "Short one-sentence description of this module."
}
}
- Position matches the
01-,02-,...prefix - Label includes the number, for example
"1. Introduction", matching thetmux/style - Do not point module categories to missing
index.mdxfiles
Every Lesson .mdx File — Exact Template
Frontmatter
---
id: kebab-case-id
title: Human Readable Title
description: One-sentence summary covering what this lesson teaches (50-160 chars).
sidebar_label: Short Title
sidebar_position: <1-based position within module>
---
Content Structure (in order)
# H1 Title
:::tip[Learning Focus]
One sentence: "By the end of this lesson you can: <concrete capability>."
Make it measurable and action-oriented.
:::
## <Core concept section 1>
- Explain the concept with a clear definition.
- Include a mermaid diagram (flowchart, sequence, or state diagram) where it adds clarity.
- Use table comparisons when contrasting 2+ approaches.
- Show real code examples with bash/filename titles on code blocks.
[one or more H2 sections teaching the material]
## Common Pitfalls
| Pitfall | Cause / Symptom | Fix |
| --- | --- | --- |
| ... | ... | ... |
Always include this section. Minimum 3 rows.
## Hands-On Practice
A step-by-step exercise the reader can copy-paste and run. Write it as a cohesive script or sequence of commands. Include expected output or assertions where possible.
## What's Next
- Link to [next lesson](./next-lesson-id)
- Link to [related lesson](../some-module/some-lesson)
Docusaurus / MDX Safety
- Use relative links without
.mdx, matching the existing docs:[Next](./next-lesson-id). - Do not use raw JSX unless necessary.
- Put code, JSON, shell commands, and Mermaid content inside fenced code blocks.
- In normal prose and tables, wrap symbols like
{},<token>,->,|, and type annotations in backticks when they could confuse MDX. - Escape Markdown table pipes inside inline code as needed, or avoid table cells that contain unescaped
|. - Use Docusaurus admonitions exactly as
:::tip,:::note,:::info,:::warning, and:::danger, each closed with:::. - Do not create nested bullet lists. Keep bullets single-level for readability and consistency with the repository style.
Gold-Standard Quality Rules (derived from tmux/)
| Rule | Description | Example |
|---|---|---|
| Problem-first | Start every major topic with "why this matters" before the "how" | Open with "Without a request body, POST endpoints cannot accept structured data from clients" |
| Dual-path teaching | Show both code and its explanation; show both the CLI and the code approach where applicable | Code block then a sentence explaining each parameter |
| Mermaid diagrams | Include at least one diagram per lesson where the concept benefits from visual explanation | Flowchart for request lifecycle, sequence diagram for OAuth2 flow, state diagram for DB connection states |
| Comparison tables | Compare alternatives in a table | FastAPI vs Flask vs Django, sync vs async, pytest vs unittest |
| Annotated code blocks | Every code block has a title= attribute showing the file path | python title="app/main.py" or bash title="run.sh" |
| Progressive disclosure | Start simple, add flags/options one at a time | First show @app.get("/"), then add status_code, then add response_model, then add dependencies |
| Common Pitfalls | Every single lesson has this table | Always 3+ rows with real mistakes and fixes |
| Hands-On Practice | Every lesson includes an actionable copy-paste exercise | A complete script/commands the reader runs to verify understanding |
| What's Next | Every lesson links forward to the next and optionally to a related lesson | Absolute relative MDX links like ./path-operations-and-decorators |
| Production realism | Examples use real-world paths, environment variables, Docker, .env patterns | DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/app |
| Error-prevention focus | Callouts (:::warning, :::danger, :::note) for gotchas | :::warning Never use sync_to_async on CPU-bound tasks |
| Learning Focus callout | Right after H1, before any content | :::tip Learning Focus with a single measurable sentence |
| Version-aware teaching | Teach current APIs and explicitly mark legacy differences | Pydantic v2 model_config instead of v1 Config |
| Security realism | Never show hardcoded production secrets | Use .env, secret managers, and generated development-only values |
| Testing-first confidence | Integration topics include a minimal test or verification command | pytest, curl, httpx, or OpenAPI UI checks |
index.mdx Structure
---
title: FastAPI
description: Complete FastAPI learning path — Pydantic models, routing, DI, databases, auth, WebSockets, testing, deployment, and production patterns.
sidebar_position: 1
---
# FastAPI Documentation
<2-3 paragraph overview of what FastAPI is>
:::info[Who This Track Is For]
- bullet list of target audience
:::
:::info[What You Will Build]
- bullet list of outcomes/builds
:::
:::tip[How To Use This Track]
- guidance on module ordering and approach
:::
## Learning Path
| Module | Focus | Lessons |
| --- | --- | --- |
| [1. Introduction](./01-introduction/what-is-fastapi) | ... | N |
## Core Architecture
Mermaid flowchart showing:
Client -> FastAPI app -> Pydantic validation -> Dependency resolution -> Route handler -> Database/External -> Response
## Quick Start
A bash script block showing pip install, create a minimal main.py, run with uvicorn.
## FastAPI vs Alternatives
Table: FastAPI vs Flask vs Django vs Starlette
## Prerequisites
- Python 3.11+
- Basic knowledge of type hints
- Familiarity with async/await concepts
## Success Criteria
Bullet list of what the reader can do after completing the track.
## Next Step
Link to [What is FastAPI](./01-introduction/what-is-fastapi)
Architectural Diagram Templates
Basic Request Flow (for index.mdx)
Dependency Chain (for dependency injection module)
OAuth2 Flow (for auth module)
Content Depth Expectations
| Lesson type | Minimum lines | Minimum H2 sections | Minimum code blocks | Minimum diagrams |
|---|---|---|---|---|
| Introduction/conceptual | 120 | 5 | 2 | 2 |
| Core feature (routing, models, DI) | 160 | 7 | 4 | 1 |
| Integration (DB, auth, testing) | 180 | 7 | 5 | 1 |
| Deployment/ops | 140 | 6 | 4 | 1 |
| Troubleshooting | 100 | 4 | 2 | 0 |
| Cheatsheet | 80 | 5 | 1 code block per section | 0 |
These are minimums, not targets. Prefer clarity over filler. If a lesson is naturally shorter, expand it with a better example, a deeper pitfalls table, or a hands-on verification step rather than repeating concepts.
FastAPI-Specific Coverage Requirements
Make sure the track explicitly teaches these topics somewhere in the relevant modules:
| Area | Required coverage |
|---|---|
| App lifecycle | FastAPI(), routers, lifespan context manager, application state, startup/shutdown migration notes |
| Routing | HTTP methods, path operation decorators, APIRouter, tags, prefixes, status codes, operation IDs |
| Validation | Path/query/header/cookie/body validation, Annotated, Field, Query, Path, Body, examples |
| Pydantic v2 | BaseModel, field_validator, model_validator, computed_field, model_config, aliases, serialization |
| Responses | response_model, exclude/include flags, JSONResponse, StreamingResponse, FileResponse, headers |
| Dependencies | Depends, dependency caching, yield dependencies, dependency overrides, security dependencies |
| Database | SQLAlchemy 2 sessions, transactions, repository/service boundaries, Alembic migrations, async caveats |
| Auth | OAuth2 password flow, JWT, password hashing, API keys, scopes, roles, common security mistakes |
| Async | When async helps, blocking pitfalls, threadpool behavior, external HTTP calls with HTTPX |
| Testing | TestClient, httpx.AsyncClient, dependency overrides, temporary DBs, auth test helpers |
| Deployment | Uvicorn, Gunicorn worker strategy, Docker, health checks, env vars, reverse proxy headers, CORS |
| Observability | Structured logging, request IDs, health endpoints, metrics/tracing overview |
| OpenAPI | Metadata, tags, examples, schema customization, docs URLs, hiding internal endpoints |
Final Instructions
- Generate EVERY file listed above. Do not skip any.
- Every
.mdxfile must use MDX syntax compatible with Docusaurus v3. - Use
:::note,:::tip,:::info,:::warning,:::dangercallouts appropriately — not more than one of each per lesson unless the content truly demands it. - Frontmatter descriptions must be unique per file (no copy-paste descriptions).
- Code examples must be syntactically valid Python that would run.
- All relative documentation links must omit
.mdx, matching the existing repository style. - Use
bashlanguage tag for shell commands,pythonfor Python code,jsonfor JSON,yamlfor YAML. - The cheatsheet module should be scannable reference material — use
```textblocks with minimal prose. - The troubleshooting module should focus on root-cause diagnosis, not just error descriptions.
- Real-world module must show a complete project directory tree with explanation of each layer.
- After generation, check for broken Markdown tables, unclosed admonitions, unclosed code fences, duplicate frontmatter IDs, and missing files.
- If package versions are mentioned, prefer stable version ranges and avoid pinning stale exact versions unless the lesson is teaching reproducibility.
Generate all files now.