API Documentation Format
Detailed Fumadocs MDX format for module and submodule API documentation.
API Documentation Format
Use this format for every module and submodule API page. The generated page must be accurate to the current codebase and must not invent endpoints, DTO fields, guards, permissions, response shapes, errors, or examples.
Required Source References
Before writing an API doc, inspect and cite the exact source files used.
| Source | Required Use |
|---|---|
docs/api doc format.md | Primary API documentation structure and endpoint-detail baseline. |
| Existing Fumadocs module docs | Use existing module docs such as apps/fumadocs/content/docs/developer/banners/api.mdx, backend.mdx, and feature.mdx as local style references. If an order module Fumadocs page exists in the current repo, use it as the first cross-module reference. |
| Controllers | Required source of routes, HTTP methods, guards, decorators, Swagger tags, params, and status codes. |
| DTOs | Required source of request bodies, query params, validation decorators, examples, and nested objects. |
| Services | Required source of behavior, side effects, validation rules, idempotency, cache behavior, async writes, and response mapping. |
| Error registry | Required source of all module error codes and response meanings. |
| Tests | Required source of confirmed edge cases and examples when tests exist. |
Cross-Document Contract
Every generated API doc must link to the sibling docs for the same module:
| Sibling Doc | Link Purpose |
|---|---|
| Backend doc | For service architecture, persistence, cache, jobs, and internal invariants. |
| Features and flows doc | For user-facing flows, actors, state transitions, and feature rules. |
| TDD | For technical behavior, state model, lifecycle, anti-abuse, and tests. |
Add a See Also section at the bottom with all three links.
Frontmatter
---
title: MODULE_NAME API Reference
description: Complete API contracts for MODULE_NAME, including routes, auth, DTOs, responses, errors, examples, and integration notes.
---Page Header
# MODULE_NAME - API Reference
**Audience:** Frontend engineers, mobile engineers, backend engineers, QA, and API consumers.
**Scope:** Admin, public, mobile, internal, webhook, worker-triggered, and integration-facing APIs owned by MODULE_NAME.1. Documentation Evidence
List every file inspected. The doc is not complete if this table is missing.
| Area | Files Inspected | What Was Verified |
|---|---|---|
| Controllers | apps/api/src/modules/MODULE_PATH/...controller.ts | Routes, methods, guards, decorators, status codes. |
| DTOs | apps/api/src/modules/MODULE_PATH/dto/*.ts | Request, query, response, validation, examples. |
| Services | apps/api/src/modules/MODULE_PATH/...service.ts | Behavior, side effects, response mapping, errors. |
| Schema | packages/db/src/schema/... | IDs, enums, persisted fields, constraints. |
| Jobs/cache/realtime | packages/jobs, @happy-shop/redis files if used | Async events, cache keys. |
| Existing docs | docs/api doc format.md, Fumadocs examples | Format and style baseline. |
2. Module Summary
Document the module in plain terms.
| Field | Value |
|---|---|
| Module name | MODULE_NAME |
| Module slug | MODULE_SLUG |
| Primary actors | guest, customer, admin, worker, internal system |
| API surfaces | public, mobile, admin, internal, webhook |
| Base route prefixes | /api/... |
| Auth model | Public, GuestOrUser, JWT, Admin JWT, service token, or exact local guard names |
| Persistence | PostgreSQL, MongoDB, Redis, BullMQ, realtime, external APIs |
| Runtime source of truth | DB tables, cache, external provider, or service state |
| Sibling docs | Backend, features/flows, TDD |
3. Concepts and Terminology
Every domain term used by routes must be defined.
| Term | Meaning | Source File | Used By |
|---|---|---|---|
TERM_NAME | Exact meaning in this module. | path/to/file.ts | Endpoint, DTO, schema, or flow. |
Include:
- Entity names and public identifiers.
- Status and lifecycle terms.
- Actor terms.
- Cache, job, event, or realtime names when exposed through API behavior.
- Any user-visible scoring, timing, ranking, or eligibility terminology.
4. API Surface Map
List every endpoint owned by the module or submodule.
| Surface | Method | Path | Actor | Auth/Guard | Permission | Controller | Purpose |
|---|---|---|---|---|---|---|---|
| Public | GET | /api/MODULE/... | Guest/user | @Public() | N/A | ControllerName | Describe exactly. |
| Mobile | POST | /api/mobile/MODULE/... | User | JwtAuthGuard | N/A | ControllerName | Describe exactly. |
| Admin | PATCH | /api/admin/MODULE/:id | Admin | JwtAuthGuard, RoleGuard | MODULE_UPDATE | ControllerName | Describe exactly. |
Rules:
- Do not omit aliases, nested routes, restore endpoints, action endpoints, or list endpoints.
- Include route prefixes from module composition, not only controller decorators.
- If a route exists in Swagger but is composed through a parent module, document both the runtime path and the controller-local path.
5. Auth, Identity, and Permissions
Document exactly how identity reaches the service.
| Surface | Guard/Decorator | Identity Shape | Permission | Guest Allowed | Notes |
|---|---|---|---|---|---|
| Public | @Public() | None or optional request metadata | N/A | Yes | Describe rate limit and abuse protection. |
| Guest/user | GuestOrUserGuard | req.user and/or guestSessionId | N/A | Yes | Explain persistence limits. |
| Admin | JwtAuthGuard, RoleGuard | req.user.id | MODULE_ACTION | No | Include permission source. |
Explain:
- Which endpoints are public.
- Which endpoints support guests.
- Which endpoints require login.
- Which endpoints require admin permissions.
- Whether auth is optional or mandatory.
- Whether headers are parsed but not trusted.
6. DTO and Model Reference
Repeat this section for every request, query, response, and nested DTO.
6.x DTO_NAME
| Field | Type | Required | Default | Validation | Example | Source |
|---|---|---|---|---|---|---|
fieldName | string | Yes | N/A | @IsString, max 120 | "example" | create.dto.ts |
Include:
- Query DTOs.
- Body DTOs.
- Param DTOs if present.
- Response DTOs.
- Nested DTOs and arrays.
- Enum fields with every allowed value.
- Defaults from DTOs, services, schema, or DB.
- Server-generated fields and read-only fields.
- Fields accepted by DTO but ignored or overwritten by service.
7. Enum Reference
Every enum must be exhaustive.
| Enum | Value | Meaning | Runtime Effect | Source |
|---|---|---|---|---|
ENUM_NAME | value | Meaning. | How service treats it. | path/to/enums.ts |
8. Endpoint Reference
Repeat for every endpoint.
8.x METHOD /api/path
Purpose
Write 40-100 words explaining when the frontend, mobile app, admin panel, worker, or integration should call this endpoint.
Source Evidence
| Evidence | Path |
|---|---|
| Controller | apps/api/src/modules/...controller.ts |
| DTO | apps/api/src/modules/.../dto/...dto.ts |
| Service | apps/api/src/modules/...service.ts |
| Schema | packages/db/src/schema/... |
| Tests | path/to/spec.ts or N/A |
Auth and Permissions
- Auth:
- Guard chain:
- Permission:
- Guest support:
- Rate limit:
- Idempotency:
Request
| Part | Required | Details |
|---|---|---|
| Headers | Yes/No | Exact header names and meanings. |
| Params | Yes/No | Exact URL params. |
| Query | Yes/No | Exact query fields and defaults. |
| Body | Yes/No | Exact body DTO. |
{
"field": "example"
}Response
Document status code, envelope, data object, pagination, and all nullable fields.
{
"success": true,
"message": "Example",
"data": {}
}Side Effects
List all side effects:
- Database writes.
- Cache reads/writes/invalidation.
- BullMQ jobs.
- Realtime events.
- Analytics events.
- Email/push notifications.
- Audit logs.
- External API calls.
Error Cases
| HTTP Status | Error Code | Condition | User-Facing Meaning | Source |
|---|---|---|---|---|
400 | ERROR_CODE | Exact service condition. | Client should fix request. | path/to/file.ts |
Edge Cases
Include all minor and major behavior:
- Empty input.
- Blank search.
- Invalid enum.
- Expired session.
- Duplicate request.
- Race condition.
- Cache miss.
- DB row missing.
- Guest trying a logged-in-only action.
- Unsupported filter or sort option.
- Rate-limit failure behavior.
Example Requests
POST /api/MODULE/path HTTP/1.1
Authorization: Bearer TOKEN
Content-Type: application/jsoncurl -X POST "$API_URL/api/MODULE/path" \
-H "Authorization: Bearer TOKEN" \
-H "Content-Type: application/json" \
-d '{"field":"example"}'9. Flow Diagrams
Include diagrams for every major route family and every important minor branch.
9.1 Route Ownership
9.2 Request Sequence
9.3 Error Branch
10. Pagination, Sorting, Filtering, and Search
Document every list endpoint.
| Endpoint | Pagination Type | Default Size | Max Size | Sort Fields | Filters | Result Cap |
|---|---|---|---|---|---|---|
/api/... | page/pageSize or cursor | 50 | 100 | createdAt, relevance | status, search | 1000 |
Include:
- Shared pagination utility used.
- Broad-search detection.
- Relevance scoring.
- Cache behavior per query.
- Empty result behavior.
11. Caching, Jobs, and External Integrations
| Integration | Used? | Details | Source |
|---|---|---|---|
| Redis cache | Yes/No | Key pattern, TTL, invalidation. | path |
| BullMQ | Yes/No | Queue, job names, payload, retry behavior. | path |
| External API | Yes/No | Provider, timeout, idempotency. | path |
13. Mandatory Deep API Documentation Pack
This section is required for every generated API doc. Do not summarize away small behavior. If a minor behavior exists in a controller, DTO, guard, interceptor, service, mapper, exception filter, cache layer, queue producer, or test, it must be documented.
13.1 Route-by-Route Completeness Matrix
Create one row for every concrete runtime route, including aliases and parent-module prefixes.
| Route | Controller Method | DTOs | Service Method | Guards | Permissions | Cache | Jobs | DB Touches | Errors | Tests | Documented? |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| METHOD /api/... | Controller.method | DtoName | Service.method | Guard list | Permission list | Key or N/A | Job or N/A | Event or N/A | Tables | Codes | Spec path | Yes/No |
Rules:
- Every
@Get,@Post,@Patch,@Put,@Delete, and custom route decorator must appear. - Every route-level, controller-level, and global guard that affects the route must appear.
- Every interceptor, pipe, decorator, and response-status override must appear if it changes behavior.
- Every service method called directly or indirectly by the route must be linked.
13.2 Request/Response Exhaustiveness
For every endpoint, include all examples below when applicable:
| Example Type | Required? | Notes |
|---|---|---|
| Minimal valid request | Always for body/query endpoints | Smallest valid payload. |
| Full valid request | Always when DTO has optional fields | Every field with realistic value. |
| Public/guest request | When supported | Include missing auth header behavior. |
| Authenticated request | When supported | Include auth header and identity effect. |
| Admin request | When admin-only | Include permission requirement. |
| Success response | Always | Include exact envelope and all nullable fields. |
| Empty-list response | For list/search endpoints | Include pagination metadata. |
| Validation error | Always | Include representative validation failure. |
| Domain error | When module errors exist | Include exact error code and condition. |
| Rate-limit/auth/permission error | When applicable | Include 401, 403, 429. |
13.3 API Diagram Pack
Every API doc must include diagrams that match the API surface.
| Diagram | Required When | Purpose |
|---|---|---|
| Route ownership graph | Always | Shows actors, controllers, services, and infrastructure. |
| Sequence diagram per major endpoint family | Always | Shows request, validation, service, persistence, and response. |
| Activity diagram per write/action flow | Every mutation/action route | Shows validation branches and side effects. |
| Error decision tree | Every route family | Shows validation/auth/not-found/conflict/error outcomes. |
| Auth and permission flow | Any protected route | Shows guard ordering and identity extraction. |
| Data contract map | Always | Shows request DTO to service command to response DTO. |
| Cache flow | Any cached route | Shows hit, miss, write, invalidation, and fallback. |
| Async/job flow | Any queued side effect | Shows producer, queue, processor, retry, and result. |
| Realtime/event flow | Any emitted event | Shows trigger, room/topic, payload, and consumer. |
Example activity diagram:
Example request/response data contract map:
13.4 Consumer Integration Notes
Document exactly how frontend, mobile, admin, QA, and external consumers should use the API.
| Consumer | Required Knowledge | Failure Handling | Contract Stability |
|---|---|---|---|
| Web frontend | Routes, query params, cache-sensitive behavior | How to display errors and retry. | Stable/experimental. |
| Mobile app | Auth, guest support, pagination, offline retry | Token expiry, network retry, conflict handling. | Stable/experimental. |
| Admin panel | Permissions, destructive mutations, audit states | Validation and permission errors. | Stable/experimental. |
| QA | Test cases, edge cases, fixtures | How to reproduce errors. | Stable/experimental. |
| Internal service | Idempotency, retries, event semantics | Retryable vs non-retryable errors. | Stable/experimental. |
13.5 API Tradeoffs and Rationale
Every non-trivial API design choice needs a short rationale.
| Decision | Chosen Behavior | Alternatives Considered | Why This Tradeoff | Risk | Mitigation |
|---|---|---|---|---|---|
| Pagination style | Page or cursor | Other style | Reason. | Risk. | Mitigation. |
| Auth mode | Public/guest/JWT/admin | Alternative | Reason. | Risk. | Mitigation. |
| Error shape | Existing envelope | Alternative | Reason. | Risk. | Mitigation. |
Include tradeoffs for:
- Route shape and nesting.
- Public vs authenticated access.
- Guest vs logged-in behavior.
- Pagination and result caps.
- Cacheability.
- Idempotency.
- Async vs synchronous side effects.
- Response DTO shape.
- Backward compatibility.
13.6 API Change Impact
Document what breaks if the API changes.
| Change | Affected Consumers | Backend Impact | Data Impact | Migration Needed? | Compatibility Plan |
|---|---|---|---|---|---|
| Field rename | Web/mobile/admin | Mapper/DTO update | None/table update | Yes/No | Versioning/deprecation plan. |
14. Zero-Omission API Checklist
Use this as the final gate before publishing.
- Every controller route is documented.
- Every parent route prefix and runtime URL is documented.
- Every DTO field, nested field, enum, default, transform, and validator is documented.
- Every response field, nullable field, generated field, and omitted raw entity field is documented.
- Every auth, guard, permission, role, public decorator, and guest identity branch is documented.
- Every success, validation, auth, permission, not-found, conflict, rate-limit, and server-error branch is documented.
- Every database read/write, cache hit/miss/write/invalidation, queue job, realtime event, notification, audit log, and external call is documented.
- Every route has examples for minimal request, full request, success response, and representative failures.
- Every endpoint family has route, sequence, activity, and error diagrams.
- Every tradeoff and compatibility risk is documented.
- The API doc links to backend, features/flows, and TDD.
15. Integration Checklist
- Every route from controllers is documented.
- Every DTO field is documented.
- Every enum value is documented.
- Every response envelope is documented.
- Every error code is documented.
- Every auth guard and permission is documented.
- Every cache key, queue job, realtime event, and external call is documented.
- Every diagram matches the current code.
- The API doc links to backend, features/flows, and TDD.
See Also
- Backend doc:
/docs/developer/MODULE_SLUG/backend - Features and flows doc:
/docs/developer/MODULE_SLUG/feature - TDD:
/docs/developer/MODULE_SLUG/tdd