Spaces:
Running
Running
File size: 11,201 Bytes
b17baae | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | # API Reference
This is a navigational overview of the API surface exposed by `@micprotocol/api` (NestJS). It is intentionally not exhaustive β for request/response shapes, use the live Swagger UI at `http://localhost:4000/api/docs` after starting the API, or read the controllers in [`apps/api/src/`](../apps/api/src/).
The API exposes three transports:
1. **REST** β public REST endpoints under `/api/v1/β¦` plus the guest portal under `/portal/β¦` and integrations under `/integrations/webhooks/β¦`. Swagger auto-documents most of it.
2. **tRPC** β typed procedures consumed by `@micprotocol/web`, `@micprotocol/admin`, and `@micprotocol/mobile`. Composed in [`apps/api/src/trpc/`](../apps/api/src/trpc/).
3. **Socket.io WebSockets** β real-time push to clients, namespaced by workspace. Gateway: [`apps/api/src/websocket/events.gateway.ts`](../apps/api/src/websocket/events.gateway.ts).
## Transports
### tRPC
The root app router merges per-domain routers; each domain lives in its own folder under `apps/api/src/`. Inputs are validated with Zod schemas shared from `@micprotocol/shared-types` β same package on web, mobile, and admin.
Key middleware:
| Middleware | File | Purpose |
|---|---|---|
| Idempotency | `apps/api/src/trpc/trpc-idempotency.middleware.ts` | Dedupes mutations via idempotency keys |
| Rate limit | `apps/api/src/trpc/trpc-rate-limit.middleware.ts` | Redis-backed per-IP + per-workspace limits |
### Socket.io events
| Event | Direction | Payload | Consumer |
|---|---|---|---|
| `guest:status_changed` | Server β Client | `{ guestId, oldStatus, newStatus, timestamp }` | Kanban board auto-refresh |
| `outreach:email_opened` | Server β Client | `{ messageId, guestId, openedAt }` | Outreach activity feed |
| `booking:confirmed` | Server β Client | `{ episodeId, startTime, guestName }` | Dashboard notification banner |
| `asset:submitted` | Server β Client | `{ requestId, assetType, guestName }` | Episode production checklist |
| `recording:session_ready` | Server β Client | `{ episodeId, meetLink }` | Host pre-recording alert |
Namespace scoping is per-workspace (`/ws?workspaceId=β¦` plus the JWT bearer in `Authorization`).
### mic-realtime (separate Erlang/OTP service)
Real-time chat fanout, presence, and live domain events are handled by `mic-realtime` (`:4001`), not the NestJS Socket.io gateway. The API publishes events into mic-realtime via its `/internal/dispatch` HTTP API; clients open a second WebSocket to `MIC_REALTIME_PUBLIC_URL`. See [Self-Hosted Stack β mic-realtime](./self-hosted-stack.md#mic-realtime).
## Health & Monitoring
```
GET /health Basic liveness check (200 OK)
GET /health/detailed Full system health (DB, Redis, search, storage)
GET /health/ready Kubernetes readiness probe
GET /health/live Kubernetes liveness probe
GET /tracing/spans Recent execution spans + p95 latency
GET /tracing/metrics Aggregate metrics (request count, error rate)
GET /integrations/health Reachability of every self-hosted integration
```
Every response carries `X-Trace-Id` (`tr-xxxxxxxx`) and `X-Response-Time` (`<n>ms`) for distributed tracing.
## Module Map
Each folder under `apps/api/src/` is a bounded context (domain module).
| Module | Folder | What it owns |
|---|---|---|
| Auth | `auth/` | Clerk JWT verification, webhook handling |
| Users | `users/` | User profile + settings |
| Workspace | `workspace/` | Workspaces, members, roles (`Owner|Admin|Editor|Viewer`) |
| Podcast | `podcast/` | Podcast CRUD, recording + outreach defaults, calendar integration |
| Guest | `guest/` | Guest CRM, priority scoring, tags, AI enrichment triggers |
| Outreach | `outreach/` | Sequences, templates, message tracking, scheduling |
| Scheduling | `scheduling/` | Bookings, availability, calendar sync (Nylas + Cal.com) |
| Assets | `assets/` | Asset requests, submissions, AI validation |
| Recording | `recording/` | Double-ender sessions, Green Room diagnostics, chunked upload, edge processing |
| Content Studio | `content-studio/` | Viral clip detection, scoring, export jobs |
| Analytics | `analytics/` | Funnel metrics, time-to-book, snapshot jobs |
| Network | `network/` | Verified Guest Network β public profiles, reputation, search, bookings |
| Tasks | `tasks/` | Workspace tasks |
| Diary | `diary/` | Time-series diary entries |
| Chat | `chat/` | Conversations, messages, reactions, media comments (backed by mic-realtime) |
| Notifications | `notifications/` | Push channels, preferences |
| Billing | `billing/` | Stripe + Paystack + M-Pesa subscriptions and webhooks |
| Portal | `portal/` | Signed-token guest portal (booking, upload, episode briefing) |
| Integrations | `integrations/` | Self-hosted clients + webhook controllers + health |
| LiveKit | `livekit/` | LiveKit token minting, room lifecycle |
| Email | `email/` | Resend + React Email templates |
| AI | `ai/` | NVIDIA NIM / DeepSeek / Moonshot wrappers |
| Queue | `queue/` | BullMQ processors (outreach, content, clip-scoring, etc.) |
| Websocket | `websocket/` | Socket.io gateway |
| Trpc | `trpc/` | tRPC router composition + middleware |
| Prisma | `prisma/` | PrismaClient service wrapper |
| Redis | `redis/` | Redis client factory |
| Settings | `settings/` | User + workspace settings |
| Common | `common/` | Shared utilities (storage, safe-fetch, redis constants) |
| Health | `health/` | Health controller |
| Types | `types/` | Shared TypeScript types |
Sub-READMEs in the source tree: [`apps/api/src/network/README.md`](../apps/api/src/network/README.md), [`apps/api/README.md`](../apps/api/README.md).
## Common REST Endpoints
### Authentication
All endpoints require a Bearer token in the `Authorization` header:
```
Authorization: Bearer <clerk_jwt_token>
```
Dev mode (no Clerk configured) accepts an `x-user-id` header containing a user UUID instead β useful for synthetic agent runs and local dev. **Never enable this in production.**
### Workspaces
```
GET /api/v1/workspaces
POST /api/v1/workspaces
GET /api/v1/workspaces/:id
PUT /api/v1/workspaces/:id
DELETE /api/v1/workspaces/:id
POST /api/v1/workspaces/:id/members
```
### Podcasts
```
GET /api/v1/workspaces/:id/podcasts
POST /api/v1/workspaces/:id/podcasts
GET /api/v1/workspaces/:id/podcasts/:id
PUT /api/v1/workspaces/:id/podcasts/:id
DELETE /api/v1/workspaces/:id/podcasts/:id
GET /api/v1/workspaces/:id/podcasts/:id/stats
```
### Guests
```
GET /api/v1/podcasts/:id/guests
POST /api/v1/podcasts/:id/guests
POST /api/v1/podcasts/:id/guests/bulk
GET /api/v1/podcasts/:id/guests/top-priority
GET /api/v1/podcasts/:id/guests/needs-follow-up
GET /api/v1/podcasts/:id/guests/status-counts
GET /api/v1/podcasts/:id/guests/:id
PUT /api/v1/podcasts/:id/guests/:id
PATCH /api/v1/podcasts/:id/guests/:id/status
DELETE /api/v1/podcasts/:id/guests/:id
POST /api/v1/podcasts/:id/guests/:id/tags
```
### Outreach
```
GET /api/v1/podcasts/:id/outreach
POST /api/v1/podcasts/:id/outreach
GET /api/v1/podcasts/:id/outreach/:id
POST /api/v1/podcasts/:id/outreach/:id/pause
POST /api/v1/podcasts/:id/outreach/:id/resume
POST /api/v1/podcasts/:id/outreach/:id/complete
GET /api/v1/podcasts/:id/outreach/stats
```
### Verified Guest Network
Full reference in [`apps/api/src/network/README.md`](../apps/api/src/network/README.md). Highlights:
```
GET /network/guests/search
GET /network/guests/trending
GET /network/guests/:vanityUrl
POST /network/views
POST /network/profiles
GET /network/profiles/me
PUT /network/profiles/me
GET /network/profiles/:id/views
POST /network/bookmarks
PUT /network/bookmarks/:id
DELETE /network/bookmarks/:id
GET /network/bookmarks
POST /network/booking-requests
PUT /network/booking-requests/:id/respond
GET /network/booking-requests/received
GET /network/booking-requests/sent
GET /network/profiles/:id/reputation
POST /network/profiles/:id/reputation/recalculate
GET /network/profiles/:id/recommendations
GET /network/profiles/:id/network-stats
POST /network/reviews
```
The Network module is also exposed via the `network.` tRPC namespace (`trpc.network.search`, `trpc.network.requestBooking`, etc.). See the linked sub-README for tRPC examples.
### Guest portal (signed-token REST)
The guest portal uses minimal public REST, authenticated via short-lived signed tokens in the URL β no account creation required.
```
GET /portal/booking/:token Available scheduling slots
POST /portal/booking/:token/confirm Confirm a selected slot
GET /portal/upload/:token Asset requirements
POST /portal/upload/:token/file Initiate chunked file upload
PATCH /portal/upload/:token/submit Mark submission complete
GET /portal/episode/:token Episode briefing + recording instructions
```
### Integrations + webhooks
Webhooks are mounted under `/integrations/webhooks/<provider>` β full reference in [Webhooks](./webhooks.md).
Integration health: `GET /integrations/health`.
### Billing
Stripe, Paystack, and M-Pesa webhook receivers. Exact paths are configured in the billing module routes β see `apps/api/src/billing/` for source. M-Pesa callback is `POST /billing/webhooks/mpesa` (see `.env.example`).
## Background Job Queues
BullMQ workers live in `apps/api/src/queue/` and run under the separate `worker` container in `docker-compose.yml` (`command: npx bullmq-pro`).
| Queue | Sample jobs | Notes |
|---|---|---|
| outreach | `send-email`, `schedule-message` | Tracking pixel + reply parsing |
| content | `transcribe`, `generate-clips`, `export` | Whisper transcription + clip export |
| clip-scoring | `score-clip` | Spawns Python subprocess (in-worker); uses Redis distributed locks |
| notifications | `send-notification` | In-app + push |
| analytics | `aggregate-stats` | Snapshot jobs |
See [Architecture β Background Job Architecture](./design.md#10-background-job-architecture) for the full queue table with concurrency and retry policies.
## Type Sharing & Codegen
- All tRPC procedures are inferred directly by the NestJS router via `createTRPCRouter({ β¦ })`. There is **no codegen step** β the frontend imports the `AppRouter` type and gets end-to-end type safety.
- Zod schemas in `packages/shared-types/src/schemas.ts` are imported by both API and clients for input validation.
- Enums in `packages/shared-types/src/enums.ts` mirror the Prisma enums in [`apps/api/prisma/schema.prisma`](../apps/api/prisma/schema.prisma) and must be kept in sync manually.
## Discovering Endpoints
The fastest way to discover the full surface:
```bash
# 1. Start the API
pnpm dev # or: docker compose up -d api
# 2. Open Swagger
open http://localhost:4000/api/docs
# 3. Search the source tree for a route
grep -rn '@Controller' apps/api/src | less
grep -rn '@Post\|@Get\|@Put\|@Delete\|@Patch' apps/api/src | less
# 4. List the tRPC routers
grep -rn 'createTRPCRouter' apps/api/src | less
```
Swagger covers REST; tRPC procedures are documented by reading the router composition. Webhooks are catalogued in [Webhooks](./webhooks.md).
|