{"data":{"slug":"discovered-9b77e88eab22ec1779fffd275f715ed4d6bb6e7d5b0f4cbc","title":"OpenAPI Design \u2014 Universal API Contract (3.1 + 3.2)","summary":"Design and document HTTP\/REST APIs using OpenAPI 3.1 or 3.2 specifications, ensuring correct resource naming, status codes, error handling, security schemes, and compatibility with modern features like Server-Sent Events (SSE) and JSON Lines streaming.","url":"https:\/\/skillshunter.net\/skills\/discovered-9b77e88eab22ec1779fffd275f715ed4d6bb6e7d5b0f4cbc","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-9b77e88eab22ec1779fffd275f715ed4d6bb6e7d5b0f4cbc","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-9b77e88eab22ec1779fffd275f715ed4d6bb6e7d5b0f4cbc.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-9b77e88eab22ec1779fffd275f715ed4d6bb6e7d5b0f4cbc\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Mandatory for code-first approaches: lock the generated spec into version control and CI-diff it. A breaking change to a route should produce a spec diff in the PR \u2014 that's your review checkpoint. Always generate the spec from code (e.g., Zod, Pydantic, DTO classes) \u2014 never write it by hand for a real service.","instructions":"---\nname: openapi-design\nversion: 2.0.0\ndescription: \"OpenAPI 3.1 \/ 3.2 spec design \u2014 resource naming, status codes, problem+json (RFC 9457) errors, pagination, versioning, security schemes, idempotency, deprecation. Covers OpenAPI 3.2 (Sept 2025) deltas: native Server-Sent Events (SSE), JSON Lines streaming, hierarchical tags (parent\/kind), QUERY HTTP method, additionalOperations, querystring location, $self document URI, OAuth2 device flow. Fully backward-compatible with 3.1 (no breaking changes). Stack-agnostic. Invoke when designing or documenting any HTTP\/REST API that publishes an OpenAPI spec, regardless of framework (Fastify, Hono, FastAPI, Laravel, Express, etc.).\"\n---\n\n# OpenAPI Design \u2014 Universal API Contract (3.1 + 3.2)\n\n**Invoke before adding a new endpoint, before publishing a public API, and during code review of any route handler.**\n\n> The OpenAPI document is the contract. Code that drifts from it lies to clients. Generate the spec from code (Zod \/ Pydantic \/ DTO classes) \u2014 never write it by hand for a real service.\n\nThis skill covers **what the spec should look like**. For **how to generate it** in your stack, see the per-framework skill (`fastify-api`, `hono-api`, `fastapi-patterns`, `laravel-patterns`, etc.).\n\n## Version policy (2026)\n\n- **OpenAPI 3.2** (Sept 2025): adopt for new specs \u2014 fully backward-compatible with 3.1, just bump the `openapi` field. **Zero breaking changes.**\n- **OpenAPI 3.1** (Feb 2021): full JSON Schema 2020-12 \u2014 still fine for stable APIs.\n- **OpenAPI 3.0**: legacy. Migrate when convenient.\n\n### What 3.2 adds (cheat sheet)\n\n| Feature | Use when |\n|---|---|\n| **Server-Sent Events (SSE)** as a first-class media type | Long-running progress, AI streaming responses, live dashboards |\n| **JSON Lines** (`application\/jsonl`) | Streaming row-oriented data (logs, exports) |\n| **Multipart streaming** | Upload progress with metadata |\n| **Hierarchical tags** (`parent`, `kind`, `summary`) | Replaces vendor-extensions `x-tagGroups`, `x-displayName`. Native nav for large APIs. |\n| **`QUERY` HTTP method** | Safe & idempotent reads with a request body (search APIs that exceed URL limits) |\n| **`additionalOperations`** field | Document custom HTTP verbs without spec extensions |\n| **`querystring` parameter location** | Describe an entire query string as a single typed parameter |\n| **`$self`** document URI | Solves multi-document `$ref` resolution |\n| **OAuth2 Device Authorization flow** | CLI \/ IoT auth |\n| **Discriminator `defaultMapping`** | Cleaner polymorphic schemas |\n\n---\n\n## 1. Resource Naming\n\n| Rule | Good | Bad |\n|---|---|---|\n| Plural nouns | `\/users`, `\/orders` | `\/user`, `\/getUser` |\n| No verbs in path | `POST \/users` | `\/createUser` |\n| Kebab-case multi-word | `\/payment-methods` | `\/paymentMethods`, `\/payment_methods` |\n| Hierarchy via path | `\/users\/{id}\/orders` | `\/orders?userId=...` (only for filters) |\n| Verbs only for actions | `POST \/orders\/{id}\/cancel` | `PATCH \/orders\/{id}` with `action=cancel` |\n\nThe action sub-resource pattern (`\/orders\/{id}\/cancel`) is the escape hatch when an operation is not a clean CRUD on a resource. Use sparingly.\n\n---\n\n## 2. HTTP Status Codes\n\n| Code | Use For | Body |\n|---|---|---|\n| `200 OK` | Successful GET \/ PUT \/ PATCH | Resource representation |\n| `201 Created` | Successful POST that creates | New resource + `Location` header |\n| `202 Accepted` | Async work queued | Job ID + status URL |\n| `204 No Content` | DELETE, or PUT\/PATCH with no body | Empty |\n| `400 Bad Request` | Malformed request | problem+json |\n| `401 Unauthorized` | Missing \/ invalid credentials | problem+json + `WWW-Authenticate` header |\n| `403 Forbidden` | Authenticated but not allowed | problem+json |\n| `404 Not Found` | Resource not found OR not visible to caller | problem+json |\n| `409 Conflict` | Version conflict, duplicate key, state mismatch | problem+json |\n| `410 Gone` | Resource permanently removed | problem+json |\n| `422 Unprocessable Entity` | Body parses but fails business validation | problem+json with field errors |\n| `429 Too Many Requests` | Rate limited | problem+json + `Retry-After` |\n| `5xx` | Server fault | problem+json (no internals) |\n\n**Never** return `200` with `{ \"success\": false, \"error\": ... }`. That breaks every reverse proxy, CDN cache, and HTTP client retry policy. Use the right code.\n\n`401` vs `403`: 401 = \"I don't know who you are\". 403 = \"I know who you are and you can't do this\". Resources you don't want to leak the existence of: return `404` even if authenticated (with a security review note in the spec).\n\n---\n\n## 2.5. Streaming Responses *(OpenAPI 3.2)*\n\nStop documenting streams as `200 application\/json` with hand-rolled extensions. 3.2 lets you describe SSE, JSON Lines, and multipart streams natively.\n\n### Server-Sent Events (SSE)\n\n```yaml\npaths:\n  \/chat\/{id}\/stream:\n    get:\n      summary: Stream assistant tokens as they generate\n      responses:\n        '200':\n          description: SSE stream\n          content:\n            text\/event-stream:\n              schema:\n                type: object\n                properties:\n                  event: { type: string, enum: [token, tool_call, done] }\n                  data:  { type: object }\n```\n\n### JSON Lines (newline-delimited JSON)\n\n```yaml\npaths:\n  \/exports\/{id}:\n    get:\n      responses:\n        '200':\n          description: One JSON object per line\n          content:\n            application\/jsonl:\n              schema:\n                $ref: '#\/components\/schemas\/Order'\n```\n\nUse SSE for **client subscribes to live updates** (chat tokens, progress); JSON Lines for **bulk row export** (logs, analytics dumps). Document the terminator (`event: done` for SSE; EOF for JSON Lines) so codegen clients know when to stop reading.\n\n---\n\n## 2.6. Hierarchical Tags *(OpenAPI 3.2)*\n\nReplaces the legacy `x-tagGroups` \/ `x-displayName` extensions. Native nested navigation in tools that support 3.2.\n\n```yaml\ntags:\n  - name: billing\n    summary: Billing\n    kind: nav            # 'nav' = navigation group only, no operations directly under it\n  - name: invoices\n    parent: billing\n    summary: Invoices\n  - name: payments\n    parent: billing\n    summary: Payments\n```\n\nFor tools still on 3.1, the same effect is achieved with `x-tagGroups` \/ `x-displayName`. Specs published as 3.2 should drop the extensions.\n\n---\n\n## 2.7. The `QUERY` HTTP method *(OpenAPI 3.2)*\n\nFor **safe & idempotent** reads whose parameters exceed URL length limits (complex search, large filter sets). Bodies on `GET` are technically legal but proxies eat them; `QUERY` is the standardized escape hatch.\n\n```yaml\npaths:\n  \/search:\n    additionalOperations:\n      QUERY:\n        summary: Complex search\n        requestBody:\n          required: true\n          content:\n            application\/json:\n              schema:\n                $ref: '#\/components\/schemas\/SearchRequest'\n        responses:\n          '200': { $ref: '#\/components\/responses\/SearchResults' }\n```\n\n`QUERY` is **safe** (no side effects) and **idempotent** (same body \u2192 same response) \u2014 clients and caches treat it like `GET`.\n\n---\n\n## 3. Error Envelope \u2014 `application\/problem+json` (RFC 9457)\n\nOne shape for every error response in the entire API. Codegen clients can match a single discriminator.\n\n```json\n{\n  \"type\": \"https:\/\/api.example.com\/problems\/validation-error\",\n  \"title\": \"Validation failed\",\n  \"status\": 422,\n  \"detail\": \"The request body did not pass schema validation.\",\n  \"instance\": \"\/orders\/01HZ...\/validate\",\n  \"errors\": [\n    { \"field\": \"email\", \"code\": \"invalid_format\", \"message\": \"Must be a valid email.\" },\n    { \"field\": \"items[0].quantity\", \"code\": \"out_of_range\", \"message\": \"Must be \u2265 1.\" }\n  ],\n  \"trace_id\": \"0af7651916cd43dd8448eb211c80319c\"\n}\n```\n\n| Field | Source | Notes |\n|---|---|---|\n| `type` | RFC | URI identifying the error class. Stable across versions; humans can read at the URL |\n| `title` | RFC | Short, human, generic per `type` |\n| `status` | RFC | Mirrors HTTP status \u2014 useful when only the body is logged |\n| `detail` | RFC | Specific to **this occurrence**; safe to show to the user |\n| `instance` | RFC | URI\/path of the failing operation |\n| `errors[]` | extension | Field-level validation errors (422 only) |\n| `trace_id` | extension | Correlate with logs \/ observability |\n\n**Never** put stack traces, raw SQL, file paths, or PII (email, name) in `detail`. Log those server-side, hand the user the `trace_id`.\n\nOpenAPI declaration of the schema (reuse via `$ref` everywhere):\n\n```yaml\ncomponents:\n  schemas:\n    Problem:\n      type: object\n      required: [type, title, status]\n      properties:\n        type: { type: string, format: uri }\n        title: { type: string }\n        status: { type: integer, minimum: 100, maximum: 599 }\n        detail: { type: string }\n        instance: { type: string, format: uri-reference }\n        trace_id: { type: string }\n    ValidationProblem:\n      allOf:\n        - $ref: '#\/components\/schemas\/Problem'\n        - type: object\n          properties:\n            errors:\n              type: array\n              items:\n                type: object\n                required: [field, code, message]\n                properties:\n                  field: { type: string }\n                  code: { type: string }\n                  message: { type: string }\n```\n\n---\n\n## 4. Pagination\n\nPick **one** strategy per endpoint and document it. Mixing breaks clients.\n\n### Cursor-based (preferred for large\/realtime sets)\n\n```http\nGET \/events?limit=50&cursor=eyJpZCI6IjAxSFoifQ\n```\n```json\n{\n  \"data\": [ ... ],\n  \"next_cursor\": \"eyJpZCI6IjAxSFAifQ\",\n  \"has_more\": true\n}\n```\n\nPros: stable under writes (no skipped\/duplicated rows when items are inserted), unbounded depth. Cons: no random access, no total count.\n\n### Offset-based (only for small, finite sets \u2014 admin, archives)\n\n```http\nGET \/users?page=2&page_size=50\n```\n```json\n{ \"data\": [ ... ], \"page\": 2, \"page_size\": 50, \"total\": 1247 }\n```\n\nCap `page_size` at 100. Cap `page * page_size` (deep pagination is expensive on every database).\n\n### Link header alternative (RFC 8288)\n\n```http\nLink: <\/users?cursor=eyJ...>; rel=\"next\", <\/users?cursor=eyI...>; rel=\"prev\"\n```\n\nUseful when the body is a bare array. Most teams prefer the JSON envelope above.\n\n---\n\n## 5. Versioning\n\nPick one strategy at the API level. Don't mix.\n\n| Strategy | Example | When |\n|---|---|---|\n| URI segment | `\/v1\/users` | Public APIs, mobile clients (most common, simplest) |\n| Header | `Accept: application\/vnd.example.v1+json` | Hypermedia APIs, content negotiation purists |\n| Query param | `\/users?api_version=2024-10-01` | Date-based versioning (Stripe-style) |\n\nDate-based (`api_version=2024-10-01`) lets you ship breaking changes more gracefully than `\/v2`: clients pin a date, you accumulate changes, deprecate per change. Higher cognitive load to operate.\n\n**Never** version internal microservice contracts the same way as public ones. Internal: SemVer the package, deploy in lockstep. Public: dated or `\/vN`, kept stable for years.\n\n---\n\n## 6. Deprecation Lifecycle (RFC 8594, RFC 9745)\n\n```http\nHTTP\/1.1 200 OK\nDeprecation: @1735689600\nSunset: Wed, 01 Jan 2026 00:00:00 GMT\nLink: <https:\/\/docs.example.com\/migration\/v2>; rel=\"deprecation\"\n```\n\n| Stage | Action | Communicate via |\n|---|---|---|\n| Announce | Mark `deprecated: true` in OpenAPI; document replacement | spec, docs, CHANGELOG |\n| Headers | Add `Deprecation` + `Sunset` headers on every response | runtime |\n| Monitor | Track usage by client (User-Agent, API key) | observability |\n| Sunset | Return `410 Gone` after the published date | runtime |\n\nRule of thumb: announce at least 6 months for paid B2B, 12 months for free public APIs.\n\n---\n\n## 7. Idempotency\n\nRequired for any unsafe retry-able operation: payments, signups, write webhooks.\n\n```http\nPOST \/orders\nIdempotency-Key: 7f9c2bd6-1f3a-4b9e-8a4d-1e2d3a4b5c6d\nContent-Type: application\/json\n```\n\nServer contract:\n1. Hash the request (method + path + body) and store it under the key for \u2265 24h\n2. Same key + same hash \u2192 return the original response\n3. Same key + **different** hash \u2192 `409 Conflict` (client bug)\n4. Reject keys longer than 255 chars; require client-generated UUIDs\n\nDocument in the spec which endpoints require it (the IETF `Idempotency-Key` draft is widely adopted: Stripe, Square, PayPal).\n\n---\n\n## 8. Security Schemes\n\nDeclare every auth method. Multiple are fine \u2014 clients pick.\n\n```yaml\ncomponents:\n  securitySchemes:\n    bearerAuth:\n      type: http\n      scheme: bearer\n      bearerFormat: JWT\n    apiKey:\n      type: apiKey\n      in: header\n      name: X-API-Key\n    oauth2:\n      type: oauth2\n      flows:\n        authorizationCode:\n          authorizationUrl: https:\/\/auth.example.com\/authorize\n          tokenUrl: https:\/\/auth.example.com\/token\n          scopes:\n            read:orders: Read user's orders\n            write:orders: Create and update orders\n    cookieSession:\n      type: apiKey\n      in: cookie\n      name: session\n\nsecurity:\n  - bearerAuth: []\n  # OR per-operation:\n  #   security:\n  #     - oauth2: [read:orders]\n```\n\n| Scheme | Use For | Caveats |\n|---|---|---|\n| `bearer` JWT | Service-to-service, mobile\/SPA | Short expiry (\u226415min), refresh flow |\n| `apiKey` (header) | Server-to-server with rotation | Never in query string (logs leak) |\n| `oauth2` | Third-party access on user's behalf | PKCE for public clients |\n| `cookieSession` | First-party browser session | `HttpOnly`, `Secure`, `SameSite` |\n\n**Never** declare `security: []` globally and forget to re-add per operation. Easier to declare globally and override `security: []` only on truly public endpoints (health, login, public docs).\n\n---\n\n## 9. Document Hygiene\n\n### `operationId` matters\n\nCodegen uses it as the function name. Make it stable, snake_case or camelCase, descriptive:\n\n```yaml\npaths:\n  \/users\/{id}\/orders:\n    get:\n      operationId: listUserOrders   # \u2192 client.listUserOrders(...)\n```\n\nRenaming an `operationId` is a breaking change for SDK users. Treat it like a public symbol.\n\n### Reuse via `$ref`\n\nDefine schemas once, reference everywhere. Avoid repeating field shapes inline \u2014 codegen produces ugly anonymous types.\n\n```yaml\ncomponents:\n  schemas:\n    User: { ... }\n    UserList:\n      type: object\n      properties:\n        data: { type: array, items: { $ref: '#\/components\/schemas\/User' } }\n```\n\n### Examples \u2014 always\n\nEvery schema and parameter should have at least one realistic `example`. Tools like Swagger UI, Redoc, Stoplight render them; mock servers serve them. Empty examples \u2192 empty SDK fixtures \u2192 no testing.\n\nUse **placeholder data only**. Never copy production payloads with real emails, names, IDs.\n\n### Tags\n\nGroup by resource, not by handler file. \u2264 10 tags total \u2014 more becomes navigational soup.\n\n```yaml\ntags:\n  - { name: Users, description: User accounts and profiles }\n  - { name: Orders, description: Order lifecycle }\n```\n\n### Servers\n\nList every environment so the spec is usable as-is in tooling:\n\n```yaml\nservers:\n  - url: https:\/\/api.example.com\/v1\n    description: Production\n  - url: https:\/\/api.staging.example.com\/v1\n    description: Staging\n  - url: http:\/\/localhost:3000\/v1\n    description: Local dev\n```\n\n---\n\n## 10. Content Types & Negotiation\n\n| Content | Type |\n|---|---|\n| Standard JSON request\/response | `application\/json` |\n| Errors | `application\/problem+json` |\n| File upload | `multipart\/form-data` |\n| Streaming events | `text\/event-stream` (SSE) or `application\/x-ndjson` |\n| Large file download | `application\/octet-stream` with `Content-Disposition` |\n| Patch | `application\/merge-patch+json` (RFC 7396) or `application\/json-patch+json` (RFC 6902) |\n\nDon't invent new content types unless you genuinely need to. `application\/json` covers 95% of APIs.\n\n---\n\n## 11. CORS\n\nDocument expected `Access-Control-Allow-Origin`\/`Methods`\/`Headers` in the OpenAPI description **and** enforce them in middleware. Mismatch between spec and reality is a top integration bug.\n\nFor browser clients: every endpoint must have CORS configured. Don't rely on a wildcard reverse-proxy default \u2014 origin allowlists must be explicit.\n\n---\n\n## 12. What NOT to Put in OpenAPI\n\n| Don't | Why | Where instead |\n|---|---|---|\n| Internal\/admin endpoints | Spec is shipped to SDK consumers | Separate `internal-openapi.yaml`, not deployed |\n| Experimental endpoints | Tagged `x-internal` is brittle; consumers see them anyway | Feature flag + private spec |\n| Secret schemas | Auth payloads \/ signed tokens internals | Document only the contract, not the implementation |\n| Real production data in examples | PII leak | Synthetic fixtures |\n| Implementation details in `description` | Rot when you refactor | API behavior only \u2014 not the database schema |\n\n---\n\n## 13. Spec-First or Code-First?\n\nBoth are valid; pick one and be consistent.\n\n| Approach | Pro | Con | Tooling |\n|---|---|---|---|\n| **Code-first** (generate spec from Zod \/ Pydantic \/ DTO) | Spec never drifts; types are the source of truth | Coupled to framework; spec PRs noisy in diff | `fastify-type-provider-zod`, `@hono\/zod-openapi`, FastAPI built-in, drf-spectacular |\n| **Spec-first** (write YAML, generate stubs) | Design conversation in PR; multiple impls | Discipline required; easy for code to drift | OpenAPI Generator, Stoplight, Redocly |\n\nFor most product APIs in 2025, code-first with Zod\/Pydantic wins on velocity. Spec-first is better for: cross-team contracts, public APIs with multiple SDK targets, regulated environments.\n\n**Mandatory for code-first:** lock the generated spec into version control and CI-diff it. A breaking change to a route should produce a spec diff in the PR \u2014 that's your review checkpoint.\n\n---\n\n## 14. Pre-Merge Checklist\n\n- [ ] Every operation has `operationId`, `summary`, response schema, error responses (at least 400, 401\/403 if auth, 404 if path param)\n- [ ] All 4xx responses use `application\/problem+json` schema\n- [ ] Schemas defined in `components\/schemas` and `$ref`'d\n- [ ] Examples present and synthetic (no real PII)\n- [ ] Pagination strategy documented\n- [ ] Security scheme set (global or per-op)\n- [ ] Spec checked into git; CI fails on uncommitted regeneration\n- [ ] Linted with Spectral or Redocly (`oas-3.1-*` rules)\n\n---\n\n## FORBIDDEN\n\n| Pattern | Reason |\n|---|---|\n| `200 OK` with `{ \"error\": ... }` | Breaks every HTTP-aware tool in the chain |\n| Plain-text error bodies on 4xx\/5xx | Codegen can't model it; client retries break |\n| Hand-written OpenAPI for a real service | Drifts within one sprint |\n| Renaming `operationId` without major version bump | Breaks every generated SDK |\n| Mixing pagination styles in one API | Client code has to special-case |\n| Real PII in examples | GDPR violation, PR review surface area |\n| Stack traces \/ SQL \/ file paths in `detail` | Information disclosure |\n| `security: []` global + forgotten per-op | Endpoints ship publicly unauthenticated |\n| Versioning by both URI and header | Cache fragmentation, doc confusion |\n| Deprecating without `Sunset` header | Clients can't plan migration |\n\n---\n\n## See Also\n\n- `security-baseline` \u2014 auth patterns, problem+json complements `A03 Injection` defense\n- `fastify-api` (Node) \u2014 generate this spec via `@fastify\/swagger` + `fastify-type-provider-zod`\n- `fastapi-patterns` (Python) \u2014 FastAPI generates 3.1 spec automatically; this skill says **what shape** it should have\n- `laravel-patterns` \/ `api-design` (PHP) \u2014 Laravel + L5-Swagger \/ Scribe\n- `database-migrations` \u2014 coordinate spec deprecation with backwards-compat schema migrations\n","use_cases":["Designing a new HTTP\/REST API with OpenAPI 3.1 or 3.2","Reviewing route handlers during code review for compliance with OpenAPI spec","Implementing secure authentication schemes like bearer JWT, API keys, OAuth2, and cookie sessions","Handling idempotency for unsafe retry-able operations such as payments and signups","Using Server-Sent Events (SSE) and JSON Lines streaming for real-time data delivery"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/0x57-1\/start-vibing-stacks\/blob\/6e398b34c4dfe73ac8f809216b218856b8e02ff4\/stacks\/_shared\/skills\/openapi-design\/SKILL.md","source_commit":"6e398b34c4dfe73ac8f809216b218856b8e02ff4","license":null,"version":null,"listing_approved_at":"2026-12-03","created_at":"2026-12-02T09:11:29.000000Z","updated_at":"2026-12-03T16:20:08.000000Z","seo_title":"OpenAPI Design \u2014 Universal API Contract (3.1 + 3.2)","seo_description":"Design and document HTTP\/REST APIs using OpenAPI 3.1 or 3.2 specifications, ensuring correct resource naming, status codes, error handling, security schemes, and modern\u517c\u5bb9","seo_keywords":["OpenAPI design","OpenAPI 3.1","OpenAPI 3.2","REST API design","HTTP status codes","problem+json errors","API security schemes","Server-Sent Events (SSE) in OpenAPI"]}}