Happy House - Ecommerce Docs
Developer Resourcesdocumentation formats

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.

SourceRequired Use
docs/api doc format.mdPrimary API documentation structure and endpoint-detail baseline.
Existing Fumadocs module docsUse 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.
ControllersRequired source of routes, HTTP methods, guards, decorators, Swagger tags, params, and status codes.
DTOsRequired source of request bodies, query params, validation decorators, examples, and nested objects.
ServicesRequired source of behavior, side effects, validation rules, idempotency, cache behavior, async writes, and response mapping.
Error registryRequired source of all module error codes and response meanings.
TestsRequired 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 DocLink Purpose
Backend docFor service architecture, persistence, cache, jobs, and internal invariants.
Features and flows docFor user-facing flows, actors, state transitions, and feature rules.
TDDFor 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.
---
# 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.

AreaFiles InspectedWhat Was Verified
Controllersapps/api/src/modules/MODULE_PATH/...controller.tsRoutes, methods, guards, decorators, status codes.
DTOsapps/api/src/modules/MODULE_PATH/dto/*.tsRequest, query, response, validation, examples.
Servicesapps/api/src/modules/MODULE_PATH/...service.tsBehavior, side effects, response mapping, errors.
Schemapackages/db/src/schema/...IDs, enums, persisted fields, constraints.
Jobs/cache/realtimepackages/jobs, @happy-shop/redis files if usedAsync events, cache keys.
Existing docsdocs/api doc format.md, Fumadocs examplesFormat and style baseline.

2. Module Summary

Document the module in plain terms.

FieldValue
Module nameMODULE_NAME
Module slugMODULE_SLUG
Primary actorsguest, customer, admin, worker, internal system
API surfacespublic, mobile, admin, internal, webhook
Base route prefixes/api/...
Auth modelPublic, GuestOrUser, JWT, Admin JWT, service token, or exact local guard names
PersistencePostgreSQL, MongoDB, Redis, BullMQ, realtime, external APIs
Runtime source of truthDB tables, cache, external provider, or service state
Sibling docsBackend, features/flows, TDD

3. Concepts and Terminology

Every domain term used by routes must be defined.

TermMeaningSource FileUsed By
TERM_NAMEExact meaning in this module.path/to/file.tsEndpoint, 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.

SurfaceMethodPathActorAuth/GuardPermissionControllerPurpose
PublicGET/api/MODULE/...Guest/user@Public()N/AControllerNameDescribe exactly.
MobilePOST/api/mobile/MODULE/...UserJwtAuthGuardN/AControllerNameDescribe exactly.
AdminPATCH/api/admin/MODULE/:idAdminJwtAuthGuard, RoleGuardMODULE_UPDATEControllerNameDescribe 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.

SurfaceGuard/DecoratorIdentity ShapePermissionGuest AllowedNotes
Public@Public()None or optional request metadataN/AYesDescribe rate limit and abuse protection.
Guest/userGuestOrUserGuardreq.user and/or guestSessionIdN/AYesExplain persistence limits.
AdminJwtAuthGuard, RoleGuardreq.user.idMODULE_ACTIONNoInclude 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

FieldTypeRequiredDefaultValidationExampleSource
fieldNamestringYesN/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.

EnumValueMeaningRuntime EffectSource
ENUM_NAMEvalueMeaning.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

EvidencePath
Controllerapps/api/src/modules/...controller.ts
DTOapps/api/src/modules/.../dto/...dto.ts
Serviceapps/api/src/modules/...service.ts
Schemapackages/db/src/schema/...
Testspath/to/spec.ts or N/A

Auth and Permissions

  • Auth:
  • Guard chain:
  • Permission:
  • Guest support:
  • Rate limit:
  • Idempotency:

Request

PartRequiredDetails
HeadersYes/NoExact header names and meanings.
ParamsYes/NoExact URL params.
QueryYes/NoExact query fields and defaults.
BodyYes/NoExact 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 StatusError CodeConditionUser-Facing MeaningSource
400ERROR_CODEExact 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/json
curl -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

Document every list endpoint.

EndpointPagination TypeDefault SizeMax SizeSort FieldsFiltersResult Cap
/api/...page/pageSize or cursor50100createdAt, relevancestatus, search1000

Include:

  • Shared pagination utility used.
  • Broad-search detection.
  • Relevance scoring.
  • Cache behavior per query.
  • Empty result behavior.

11. Caching, Jobs, and External Integrations

IntegrationUsed?DetailsSource
Redis cacheYes/NoKey pattern, TTL, invalidation.path
BullMQYes/NoQueue, job names, payload, retry behavior.path
External APIYes/NoProvider, 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 TypeRequired?Notes
Minimal valid requestAlways for body/query endpointsSmallest valid payload.
Full valid requestAlways when DTO has optional fieldsEvery field with realistic value.
Public/guest requestWhen supportedInclude missing auth header behavior.
Authenticated requestWhen supportedInclude auth header and identity effect.
Admin requestWhen admin-onlyInclude permission requirement.
Success responseAlwaysInclude exact envelope and all nullable fields.
Empty-list responseFor list/search endpointsInclude pagination metadata.
Validation errorAlwaysInclude representative validation failure.
Domain errorWhen module errors existInclude exact error code and condition.
Rate-limit/auth/permission errorWhen applicableInclude 401, 403, 429.

13.3 API Diagram Pack

Every API doc must include diagrams that match the API surface.

DiagramRequired WhenPurpose
Route ownership graphAlwaysShows actors, controllers, services, and infrastructure.
Sequence diagram per major endpoint familyAlwaysShows request, validation, service, persistence, and response.
Activity diagram per write/action flowEvery mutation/action routeShows validation branches and side effects.
Error decision treeEvery route familyShows validation/auth/not-found/conflict/error outcomes.
Auth and permission flowAny protected routeShows guard ordering and identity extraction.
Data contract mapAlwaysShows request DTO to service command to response DTO.
Cache flowAny cached routeShows hit, miss, write, invalidation, and fallback.
Async/job flowAny queued side effectShows producer, queue, processor, retry, and result.
Realtime/event flowAny emitted eventShows 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.

ConsumerRequired KnowledgeFailure HandlingContract Stability
Web frontendRoutes, query params, cache-sensitive behaviorHow to display errors and retry.Stable/experimental.
Mobile appAuth, guest support, pagination, offline retryToken expiry, network retry, conflict handling.Stable/experimental.
Admin panelPermissions, destructive mutations, audit statesValidation and permission errors.Stable/experimental.
QATest cases, edge cases, fixturesHow to reproduce errors.Stable/experimental.
Internal serviceIdempotency, retries, event semanticsRetryable vs non-retryable errors.Stable/experimental.

13.5 API Tradeoffs and Rationale

Every non-trivial API design choice needs a short rationale.

DecisionChosen BehaviorAlternatives ConsideredWhy This TradeoffRiskMitigation
Pagination stylePage or cursorOther styleReason.Risk.Mitigation.
Auth modePublic/guest/JWT/adminAlternativeReason.Risk.Mitigation.
Error shapeExisting envelopeAlternativeReason.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.

ChangeAffected ConsumersBackend ImpactData ImpactMigration Needed?Compatibility Plan
Field renameWeb/mobile/adminMapper/DTO updateNone/table updateYes/NoVersioning/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