# API Documentation Design

**Date:** 2026-03-15
**Status:** Approved

## Goal

Create comprehensive, accurate API documentation for the Jackbox Game Picker by reading the source code directly — not relying on existing docs which may be stale or incorrect. The documentation serves both internal maintainers and external integrators (bot developers, extension authors, etc.).

## Scope

- All 41 REST/HTTP endpoints across 7 route groups (Auth, Games, Sessions, Picker, Stats, Votes, Webhooks) plus the health check
- WebSocket protocol at `/api/sessions/live` (auth, subscriptions, event broadcasting)
- Does NOT cover: Chrome extension internals, deployment/Docker setup, frontend

## Approach

**OpenAPI-first with generated Markdown** (Approach A from brainstorming).

- `openapi.yaml` (OpenAPI 3.1) is the single source of truth for REST endpoints
- Human-readable Markdown endpoint docs are derived from the spec and enriched with guide-style prose, curl examples, and workflow explanations
- WebSocket protocol documented separately in Markdown (outside OpenAPI's scope)
- Existing `docs/` files archived to `docs/archive/`

## File Structure

```
docs/
├── archive/                          # Old docs preserved here
│   ├── API_QUICK_REFERENCE.md
│   ├── BOT_INTEGRATION.md
│   ├── SESSION_END_QUICK_START.md
│   ├── SESSION_END_WEBSOCKET.md
│   ├── SESSION_START_WEBSOCKET.md
│   ├── WEBSOCKET_FLOW_DIAGRAM.md
│   ├── WEBSOCKET_SUBSCRIPTION_GUIDE.md
│   ├── WEBSOCKET_TESTING.md
│   └── todos.md
├── api/
│   ├── openapi.yaml                  # OpenAPI 3.1 spec (source of truth)
│   ├── README.md                     # API overview, auth, base URL, error conventions
│   ├── endpoints/
│   │   ├── auth.md
│   │   ├── games.md
│   │   ├── sessions.md
│   │   ├── picker.md
│   │   ├── stats.md
│   │   ├── votes.md
│   │   └── webhooks.md
│   ├── websocket.md                  # WebSocket protocol documentation
│   └── guides/
│       ├── getting-started.md        # Quick start: auth, pick a game, run a session
│       ├── session-lifecycle.md      # Sessions end-to-end
│       ├── voting-and-popularity.md  # Chat import, live votes, popularity scoring
│       └── webhooks-and-events.md    # Webhooks + WS event system
└── plans/
```

## OpenAPI Spec Design

### Info & Servers
- Title: "Jackbox Game Picker API"
- Servers: local dev (`http://localhost:5000`), Docker proxy (`http://localhost:3000/api`)

### Security
- `bearerAuth` scheme (JWT via `Authorization: Bearer <token>`)
- Applied per-operation; public endpoints explicitly marked

### Tags
Auth, Games, Sessions, Picker, Stats, Votes, Webhooks

### Schemas (components)
- `Game`, `Session`, `SessionGame`, `Pack`, `PackMeta`
- `Webhook`, `WebhookLog`
- `ChatMessage`, `LiveVote`
- `Error` (reusable error response)
- Enums: `status` (playing/played/skipped), `vote_type` (up/down), `favor_bias` (-1/0/1), `drawing` (only/exclude), `length` (short/medium/long)

### Per-operation
Each path operation includes: `operationId`, `summary`, `description`, `parameters`, `requestBody`, `responses` (success + all documented error codes)

## Markdown Endpoint Template

Each file in `docs/api/endpoints/` follows:

1. **Header:** Resource overview, what it represents, common use cases
2. **Summary table:** Method | Path | Auth | Description
3. **Per-endpoint sections:**
   - Description and when to use it
   - Authentication requirement
   - Parameters table (Name | In | Type | Required | Description)
   - Request body (JSON schema with field descriptions)
   - Success response (JSON example with annotations)
   - Error responses table (Status | Body | When)
   - curl example + sample response

## WebSocket Documentation Structure

`docs/api/websocket.md` covers:
- Connection URL and setup
- Authentication flow (send `auth` message with JWT)
- Client-to-server message types: `auth`, `subscribe`, `unsubscribe`, `ping`
- Server-to-client message types: `auth_success`, `subscribed`, `unsubscribed`, `pong`, `session.started`, `game.added`, `session.ended`, `player-count.updated`, `error`, `auth_error`
- Subscription model (per-session)
- Event payloads with full JSON examples
- Heartbeat/timeout (60s) and reconnection guidance
- Complete session lifecycle example

## Guide Documents

Each guide uses narrative prose connecting endpoints into workflows:

- **getting-started.md:** Authenticate, browse games, pick a game, start a session — minimum viable integration path
- **session-lifecycle.md:** Create session → add games → track status → room codes → player counts → close session
- **voting-and-popularity.md:** How `popularity_score`, `upvotes`, `downvotes` work; chat import flow; live vote endpoint; how voting affects the picker
- **webhooks-and-events.md:** Create/manage webhooks, event types, delivery logs, relationship between webhook events and WebSocket events

## Maintenance Strategy

- `openapi.yaml` is the source of truth for REST endpoints
- When endpoints change: update spec first, then update Markdown
- WebSocket and guide docs are maintained manually
- No build-time generation tooling — Markdown committed directly

## Validation Plan

After writing, cross-reference:
1. Every route file in `backend/routes/` against the spec — no endpoints missed
2. Request/response shapes against database schema (`backend/database.js`) and route handlers
3. Auth requirements against middleware usage in each route
