Add API Endpoint

The OpenAPI spec at openapi/v1.yaml is the single source of truth. Define the endpoint there first, then implement.

New Endpoint Checklist

  1. Define in OpenAPI spec: Add path, request/response schemas, and x-required-scopes in openapi/v1.yaml
  2. Create route handler: app/api/v1/<resource>/route.ts
  3. Auth: Use validateApiKey() from lib/api-keys.ts
  4. Scopes: Use hasScopes() from lib/scopes.ts to enforce x-required-scopes
  5. Business logic: Add query helpers in lib/<resource>.ts, mutations in lib/actions/<resource>.ts
  6. Database: If new tables needed, edit lib/schema.ts and run bunx drizzle-kit generate (see db-health skill)
  7. Tests: Add unit tests in tests/unit/
  8. CLI command: Add corresponding command in cli/cmd/<resource>.go (see docs/cli.md)
  9. Gates: Run ./scripts/gates.sh

New Scope Checklist

If the endpoint needs a new scope:

  1. Add scope string to lib/scopes.ts in ALL_SCOPES and SCOPE_DESCRIPTIONS
  2. Add to openapi/v1.yaml under x-all-scopes and components.schemas.Scope.enum
  3. Add x-required-scopes to the endpoint in openapi/v1.yaml
  4. Enforce in route handler via hasScopes()
  5. Add tests
  6. Run ./scripts/gates.sh

Route Handler Pattern

import { NextRequest, NextResponse } from "next/server"
import { withApiKeyAuth } from "@/lib/api-v1-auth"

export const GET = withApiKeyAuth(
  async (_request: NextRequest, { apiKey, user }) => {
    // apiKey and user are already validated
    // Business logic here
    return NextResponse.json({ data: result })
  },
  { requiredScopes: ["resource:read"] }
)

Architecture Layers

openapi/v1.yaml          ← spec (source of truth)
app/api/v1/*/route.ts    ← thin route handler
lib/api-v1-auth.ts       ← auth wrapper
lib/scopes.ts            ← scope definitions
lib/<resource>.ts         ← queries and helpers
lib/actions/<resource>.ts ← mutations
tests/unit/              ← tests
cli/cmd/<resource>.go    ← CLI command

Current Scopes

ScopeDescription
keys:readList and inspect API keys
keys:writeCreate and revoke API keys
usage:readRead usage metrics
usage:writeRecord usage events

If You're Lost