Skip to main content

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

  1. Generate documentation files only. Do not generate unrelated app source code outside the requested docs tree.
  2. Keep all docs under /home/rezriz/github/brain-donnyaw-cf-pages/fastapi/.
  3. Use the existing tmux/ docs as the style reference, but make the FastAPI track deeper and more comprehensive.
  4. Prefer modern FastAPI patterns: Annotated, Pydantic v2 model_config, SQLAlchemy 2 style, lifespan handlers instead of legacy startup/shutdown unless teaching migration.
  5. Avoid deprecated patterns unless the lesson explicitly labels them as legacy and explains the modern replacement.
  6. Make examples copy-paste runnable where practical.
  7. Do not invent APIs or package behavior. If uncertain, use conservative, documented FastAPI patterns.
  8. 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 the tmux/ style
  • Do not point module categories to missing index.mdx files

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/)

RuleDescriptionExample
Problem-firstStart 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 teachingShow both code and its explanation; show both the CLI and the code approach where applicableCode block then a sentence explaining each parameter
Mermaid diagramsInclude at least one diagram per lesson where the concept benefits from visual explanationFlowchart for request lifecycle, sequence diagram for OAuth2 flow, state diagram for DB connection states
Comparison tablesCompare alternatives in a tableFastAPI vs Flask vs Django, sync vs async, pytest vs unittest
Annotated code blocksEvery code block has a title= attribute showing the file pathpython title="app/main.py" or bash title="run.sh"
Progressive disclosureStart simple, add flags/options one at a timeFirst show @app.get("/"), then add status_code, then add response_model, then add dependencies
Common PitfallsEvery single lesson has this tableAlways 3+ rows with real mistakes and fixes
Hands-On PracticeEvery lesson includes an actionable copy-paste exerciseA complete script/commands the reader runs to verify understanding
What's NextEvery lesson links forward to the next and optionally to a related lessonAbsolute relative MDX links like ./path-operations-and-decorators
Production realismExamples use real-world paths, environment variables, Docker, .env patternsDATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/app
Error-prevention focusCallouts (:::warning, :::danger, :::note) for gotchas:::warning Never use sync_to_async on CPU-bound tasks
Learning Focus calloutRight after H1, before any content:::tip Learning Focus with a single measurable sentence
Version-aware teachingTeach current APIs and explicitly mark legacy differencesPydantic v2 model_config instead of v1 Config
Security realismNever show hardcoded production secretsUse .env, secret managers, and generated development-only values
Testing-first confidenceIntegration topics include a minimal test or verification commandpytest, 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 typeMinimum linesMinimum H2 sectionsMinimum code blocksMinimum diagrams
Introduction/conceptual120522
Core feature (routing, models, DI)160741
Integration (DB, auth, testing)180751
Deployment/ops140641
Troubleshooting100420
Cheatsheet8051 code block per section0

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:

AreaRequired coverage
App lifecycleFastAPI(), routers, lifespan context manager, application state, startup/shutdown migration notes
RoutingHTTP methods, path operation decorators, APIRouter, tags, prefixes, status codes, operation IDs
ValidationPath/query/header/cookie/body validation, Annotated, Field, Query, Path, Body, examples
Pydantic v2BaseModel, field_validator, model_validator, computed_field, model_config, aliases, serialization
Responsesresponse_model, exclude/include flags, JSONResponse, StreamingResponse, FileResponse, headers
DependenciesDepends, dependency caching, yield dependencies, dependency overrides, security dependencies
DatabaseSQLAlchemy 2 sessions, transactions, repository/service boundaries, Alembic migrations, async caveats
AuthOAuth2 password flow, JWT, password hashing, API keys, scopes, roles, common security mistakes
AsyncWhen async helps, blocking pitfalls, threadpool behavior, external HTTP calls with HTTPX
TestingTestClient, httpx.AsyncClient, dependency overrides, temporary DBs, auth test helpers
DeploymentUvicorn, Gunicorn worker strategy, Docker, health checks, env vars, reverse proxy headers, CORS
ObservabilityStructured logging, request IDs, health endpoints, metrics/tracing overview
OpenAPIMetadata, tags, examples, schema customization, docs URLs, hiding internal endpoints

Final Instructions

  1. Generate EVERY file listed above. Do not skip any.
  2. Every .mdx file must use MDX syntax compatible with Docusaurus v3.
  3. Use :::note, :::tip, :::info, :::warning, :::danger callouts appropriately — not more than one of each per lesson unless the content truly demands it.
  4. Frontmatter descriptions must be unique per file (no copy-paste descriptions).
  5. Code examples must be syntactically valid Python that would run.
  6. All relative documentation links must omit .mdx, matching the existing repository style.
  7. Use bash language tag for shell commands, python for Python code, json for JSON, yaml for YAML.
  8. The cheatsheet module should be scannable reference material — use ```text blocks with minimal prose.
  9. The troubleshooting module should focus on root-cause diagnosis, not just error descriptions.
  10. Real-world module must show a complete project directory tree with explanation of each layer.
  11. After generation, check for broken Markdown tables, unclosed admonitions, unclosed code fences, duplicate frontmatter IDs, and missing files.
  12. 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.