# API Design Standards

## Overview

Rules for consistent, consumer-friendly API design across all AI-DLC phases.
Each rule is a blocking constraint: a phase or stage cannot complete until all
applicable checks pass or are marked N/A.

### Relationship to EGS

EGS defines API policy (§3.1: approved patterns, versioning strategy; §3.5: event
schema management). The security extension covers API security (DES-04: access
control; BLD-02: input validation; BLD-03: HTTP headers). This extension covers
API design conventions: naming, error format, pagination, idempotency, and
contract generation. It does not redefine security or policy thresholds.

### Blocking Behavior

When a check fails:
1. List the finding in the phase/stage completion message under "API Design
   Findings" with the rule ID and failed check.
2. Do NOT present "Continue to Next Stage" until resolved.
3. Present only "Request Changes" with what needs to change.
4. Log the finding in `aidlc-docs/audit/audit-log.md` as `EXTENSION_FINDING`.

If a rule does not apply (e.g., no external API), mark it **N/A**.

---

## Applicability Question

Asked during pre-flight when this extension is loaded:

```
Should API design rules be enforced for this project?

A) Yes — enforce as blocking constraints (recommended for APIs consumed by external teams)
B) No — skip all API design rules (suitable for internal-only or event-driven projects)
```

Record the answer in `aidlc-docs/aidlc-state.md` under Extension Configuration.

---

## Design-Time Rules

Enforced during Mob Elaboration and the design stages of Mob Construction.

### API-01: Resource Naming Conventions

API resources follow consistent, predictable naming.

- [ ] Resource names are plural nouns (`/tasks`, `/events`, not `/getTask`)
- [ ] URL paths use kebab-case for multi-word segments (`/line-items`)
- [ ] No verbs in URL paths; HTTP methods convey the action
- [ ] Nested resources limited to one level (`/orders/{id}/items`, not deeper)
- [ ] Query parameters use camelCase

### API-02: Standard Error Response Format

All error responses follow a single, documented structure.

- [ ] Error body includes: `code` (machine-readable), `message` (human-readable), `requestId`
- [ ] Validation errors include a `details` array with per-field errors (`field`, `reason`)
- [ ] HTTP status codes used correctly: 400 (bad input), 401 (unauthenticated), 403 (unauthorized), 404 (not found), 409 (conflict), 422 (unprocessable), 429 (rate limited), 500 (server error)
- [ ] No stack traces, internal paths, or implementation details in error responses
- [ ] Error format documented in OpenAPI spec `components/schemas`

### API-03: Pagination and Filtering

Collection endpoints support bounded responses.

- [ ] All list endpoints return paginated results by default
- [ ] Pagination uses cursor-based (preferred) or offset-based approach, documented consistently
- [ ] Response includes: `items`, `nextToken` (or `nextPage`), `count` (items in page)
- [ ] Maximum page size enforced server-side (client cannot request unbounded results)
- [ ] Filtering and sorting parameters documented per endpoint

### API-04: Idempotency

Mutating operations are safe to retry.

- [ ] POST endpoints that create resources accept an `Idempotency-Key` header
- [ ] Duplicate requests with the same idempotency key return the original response, not an error
- [ ] PUT and DELETE are naturally idempotent by design
- [ ] Idempotency key TTL documented (e.g., 24 hours)
- [ ] *Defers to EGS §8.2 for fault tolerance requirements around retries*

---

## Build-Time Rules

Enforced during Mob Construction implementation stages and Code Elevation.

### API-05: OpenAPI Contract

Every API has a machine-readable contract.

- [ ] OpenAPI 3.x specification generated or maintained alongside code
- [ ] All endpoints, request/response schemas, and error responses documented
- [ ] Examples included for each endpoint (request and response)
- [ ] Contract validated in CI (schema linting, breaking change detection)
- [ ] *Defers to EGS §3.1 for versioning strategy and deprecation policy*

### API-06: Consistent Response Envelope

Successful responses follow a predictable structure.

- [ ] Single-resource responses return the resource directly (no unnecessary wrapper)
- [ ] Collection responses use the pagination structure from API-03
- [ ] 201 Created responses include `Location` header with the new resource URL
- [ ] 204 No Content for successful DELETE (no body)
- [ ] Date/time fields use ISO 8601 format with timezone

### API-07: Rate Limit Communication

Clients can discover and react to rate limits.

- [ ] Responses include `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` headers
- [ ] 429 responses include `Retry-After` header
- [ ] Rate limit tiers documented in API reference
- [ ] *Defers to EGS §8.4 for rate limit thresholds and Security DES-04 for auth-tier differentiation*

### API-08: Deprecation and Sunset

API changes are communicated to consumers.

- [ ] Deprecated endpoints return `Deprecation` header with date
- [ ] Sunset date communicated via `Sunset` header
- [ ] Changelog or migration guide published for breaking changes
- [ ] *Defers to EGS §3.1 for versioning strategy and deprecation timeline*

---

## Enforcement by Ritual

| Ritual | Primary Rules | Secondary Rules |
|--------|--------------|-----------------|
| Mob Elaboration | API-01 through API-04 | API-05 through API-08 (flag as requirements) |
| Mob Construction: Design stages | API-01 through API-04 | API-05 through API-08 (verify design supports them) |
| Mob Construction: Implementation | API-05 through API-08 | API-01 through API-04 (verify code matches design) |
| Code Elevation | All rules | Assess existing API against full checklist |

At each phase/stage completion, include an "API Design Compliance" section:
- List each applicable rule as ✅ compliant, ❌ non-compliant, or N/A
- Any ❌ is a blocking finding
