agentleFS
peterbamuhigirepeterbamuhigire/chwezi-dev-engine/skills/architecture/api-design-first/SKILL.md

api-design-first

Skill31 starsChanged 18 days agoMITView on GitHub

Use when designing HTTP APIs with OpenAPI, versioning, authentication, rate limits, idempotency, error contracts, observability requirements, and choosing REST, webhooks, SSE, or WebSocket delivery.

2 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

10 rules. About 0 are common, 7 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈7

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Read this SKILL.md, then load only the references needed for the task (for example openapi-workflow.md for a greenfield design.

    line 40
  2. Distinctive:

    Run the implementation checklist before merging.

    line 44
  3. Distinctive:

    Every endpoint has documented auth, error codes, rate limits, pagination where relevant, and observability notes.

    line 49
  4. Very specific:

    Every response carries the mandatory security headers from auth-and-security.md.

    line 168
  5. Very specific:

    Every POST that causes an external side effect (payment, email, webhook, inventory movement) requires an Idempotency-Key.

    line 169
  6. Distinctive:

    Every new endpoint is added to the observability notes table before merge.

    line 170
  7. Distinctive:

    Write the API action plan, then model resources and actions around business concepts, not controller names.

    line 229
  8. Distinctive:

    Write the OpenAPI contract, including auth, validation, errors, and pagination.

    line 230
  9. Distinctive:

    Default to contract design and validation.

    line 274
  10. Distinctive:

    If consumers, traffic evidence, or the current contract are unavailable, produce a read-only draft with assumptions and unresolved …

    line 277

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

API Design First

Acknowledgement: Shared by Peter Bamuhigire, techguypeter.com, +256 784 464178.

Design APIs as contracts before code. This skill produces the OpenAPI 3.1 contract and its companion auth / error / idempotency / observability artifacts that downstream frontend, mobile, SDK, security, and reliability skills depend on.

<!-- dual-compat-start -->

Use When

  • Designing a new HTTP API (REST or GraphQL decision open), or adding endpoints to an existing API.
  • Normalising an existing API against the house contract (envelope, error model, versioning, rate limits).
  • Producing the OpenAPI contract that SDK, frontend, mobile, contract-testing, and security skills will consume.
  • Choosing an auth method and writing the auth/role matrix for a new service.
  • Defining idempotency keys and observability notes handed to reliability-engineering and observability-monitoring.

Do Not Use When

  • The task is purely client-side consumption of a third-party API (load the relevant SDK or integration skill).
  • The task is full threat modelling — load vibe-security-skill; this skill only records the auth model.
  • GraphQL-specific hardening is needed — load graphql-patterns.

Required Inputs

  • Context map and critical-flow table from system-architecture-design.
  • Access-pattern list from database-design-engineering.
  • Consumers, trust boundaries, and latency budget for each endpoint.
  • Tenancy model (single-tenant, shared schema, schema-per-tenant) so tenant_id propagation can be proven.

Workflow

  • Read this SKILL.md, then load only the references needed for the task (for example openapi-workflow.md for a greenfield design; auth-and-security.md for an auth choice; rest-conventions.md for URL / status-code review).
  • Apply the six-step design workflow before writing any code.
  • Produce the OpenAPI contract in the template format from skill-composition-standards/references/openapi-contract.md.
  • Record the auth model, error model, idempotency map, and observability notes alongside the spec.
  • Run the implementation checklist before merging.

Quality Standards

  • Spec is the source of truth; code follows the spec, never the reverse.
  • Every endpoint has documented auth, error codes, rate limits, pagination where relevant, and observability notes.
  • Tenant scope is derived from the auth token, never from a request body or query string.
  • Breaking changes require a new major version; existing versions are frozen except for bug fixes.
  • British English, no emojis, language-tagged code fences.

Anti-Patterns

  • Writing code first and "generating" the spec afterwards — the spec loses its role as contract.
  • Accepting tenant_id from the request body — enables cross-tenant data leaks.
  • Returning 403 for wrong-tenant lookups — leaks existence; return 404.
  • Wildcard Access-Control-Allow-Origin: * with credentials — browsers ignore, auth breaks, security hole opens.
  • Storing API keys in plaintext — a database leak becomes an immediate credential leak.
  • Mutating an existing version's response schema — every client with hard-coded parsers breaks.

Skill-specific anti-patterns:

  • Spec-after-code. The team writes endpoints and exports the OpenAPI spec from code annotations. Fix: draft the spec in a PR first, get sign-off from at least one consumer, then implement.
  • Tenant from body. POST /api/v1/invoices { "franchise_id": 42, "amount": 100 }. Fix: derive franchise_id from the authenticated token server-side; ignore any tenant field on the wire.
  • 403 on wrong-tenant. GET /api/v1/invoices/999 returns 403 Forbidden when invoice 999 belongs to another tenant. Fix: return 404 Not Found — 403 leaks that the resource exists.
  • Wildcard CORS with credentials. Access-Control-Allow-Origin: * plus Access-Control-Allow-Credentials: true. Fix: echo only origins from an allow-list; set credentials true only for those origins.
  • Raw API key storage. INSERT INTO api_keys (key) VALUES ('sk_live_abc123'). Fix: store key_hash = SHA-256(key), return the raw key once on creation, never again.
  • Unversioned breaking change. The team removes a field from GET /api/v1/invoices/{id} because nobody "should" be using it. Fix: ship as v2, keep v1 unchanged, emit Deprecation + Sunset headers on v1.
  • No idempotency on payments. POST /api/v1/payments charges the card. Network retry charges it again. Fix: require Idempotency-Key header, store (tenant, user, key) -> response for 24 h, replay the stored response on duplicate.
  • Unbounded page size. GET /api/v1/invoices?per_page=100000. Fix: clamp per_page to a hard maximum (e.g. 100) server-side.
  • Numbers as JSON integers or client-assigned. "invoice_number": 1042, or the client sends its own number on create. Fix: return document numbers as strings, ignore client numbers, require Idempotency-Key on numbered creates and store it on the document row so a replay returns the same number (tenant-document-numbering).

Outputs

  • OpenAPI 3.1 contract covering every endpoint, schema, error, rate-limit header, and example.
  • Auth model: selected method, role/scope matrix, token lifetime, revocation strategy.
  • Error model conforming to the standard envelope with documented error codes.
  • Idempotency map: which endpoints require Idempotency-Key, scope, TTL.
  • Observability notes: per-endpoint span names, SLO class, log fields, audit events.
  • Implementation checklist result.

Skill-specific outputs:

ArtifactConsumed byTemplate
OpenAPI 3.1 contractfrontend, mobile, SDK, advanced-testing-strategy (contract tests)skill-composition-standards/references/openapi-contract.md
Error modelfrontend, mobile, advanced-testing-strategyskill-composition-standards/references/error-model.md
Auth modelvibe-security-skill, mobile-rbac, ios-rbacinline in spec (components.securitySchemes) + role/scope matrix in auth-and-security.md
Idempotency mapreliability-engineering, stripe-paymentsinline table — see references/auth-and-security.md
Observability notesobservability-monitoringinline table — see references/implementation-checklist.md

Evidence Produced

CategoryArtifactFormatExample
CorrectnessOpenAPI contractMarkdown doc plus OpenAPI YAML covering paths, schemas, and error responsesdocs/api/openapi-checkout.yml
CorrectnessContract test resultsCI log or recorded report from API contract tests against the OpenAPI specdocs/api/contract-tests-2026-04-16.md

References

  • references/rest-conventions.md — URLs, methods, status codes, envelope, pagination, middleware order, health checks.
  • references/openapi-workflow.md — spec-first workflow, OpenAPI 3.1 skeleton, versioning, HATEOAS, HTTP caching, GraphQL decision.
  • references/auth-and-security.md — headers, CORS, auth-method selection table, API key, JWT, OAuth2, rate limiting, idempotency keys.
  • references/implementation-checklist.md — pre-merge checklist and observability contract handed to observability-monitoring.
  • references/practical-api-architecture.md — book-distilled API product-contract checks, lifecycle/versioning policy, idempotency map, and error semantics.
  • references/api-you-wont-hate-rules.md — consumer-first API action planning, resource shape, pagination, versioning, and endpoint test rules.
  • references/source-register-api-you-wont-hate.md — local EPUB source register for the API-design upgrade.
  • references/api-error-handling.md - absorbed API error envelope and failure-response guidance.
  • references/api-pagination.md - absorbed pagination, cursor, and collection-response guidance.
  • references/api-testing-verification.md - absorbed API contract testing and verification guidance.
  • references/api-style-selection.md - load when choosing REST, GraphQL, gRPC, webhooks, SSE, WebSocket, messaging, or feeds per interaction (decision matrix, AsyncAPI/OpenAPI 3.2 currentness).
  • references/json-payload-and-schema-design.md - load when designing payloads, JSON Schema 2020-12 contracts, RFC 9457 problem details, or classifying a change as breaking.
  • references/api-security-owasp-top10.md - load for API authorisation design or pre-release review against OWASP API Security Top 10 (2023) with negative-test proofs.
  • references/apis-for-ai-agents-and-data.md - load when LLM agents, MCP servers, notebooks/BI tools, or model-inference clients consume the API (MCP 2026-07-28).
  • Companion skill: graphql-patterns — schema-first Apollo Server + TypeScript patterns when choosing GraphQL over REST for client-shaped reads.
<!-- dual-compat-end -->

Skill-specific references:

  • references/rest-conventions.md — URLs, methods, status codes, envelope, pagination, middleware order, health checks, PHP controller skeleton.
  • references/openapi-workflow.md — six-step workflow, OpenAPI 3.1 skeleton, versioning, HATEOAS, HTTP caching (ETags), GraphQL decision.
  • references/auth-and-security.md — security headers, CORS, auth-method selection, API key, JWT, OAuth2, rate limiting, idempotency keys.
  • references/implementation-checklist.md — pre-merge checklist, observability notes handed to observability-monitoring, hand-off table to other skills.
  • references/practical-api-architecture.md — API product-contract checks, versioning lifecycle, idempotency, and error semantics.
  • references/api-you-wont-hate-rules.md — API action plan, resource design, JSON ergonomics, pagination, embedding, versioning, and endpoint tests.
  • references/source-register-api-you-wont-hate.md — local EPUB source register for the API-design upgrade.
  • references/skill-deep-dive.md — index redirect for the legacy deep-dive; kept for backward compatibility.
  • references/api-error-handling.md, references/api-pagination.md, and references/api-testing-verification.md - absorbed API specialist entrypoints.

Prerequisites

Load these skills first:

  • system-architecture-design — produces the context map and critical-flow table consumed below.
  • database-design-engineering — produces the access-pattern list that shapes resource design.
  • world-class-engineering — the shared release gate this skill ships into.

Load alongside:

  • vibe-security-skill for threat modelling of the auth model produced here.
  • graphql-patterns whenever building or auditing a GraphQL API (it owns the GraphQL hardening guidance).

When this skill applies

  • A new service is being designed and needs its HTTP surface defined.
  • A feature adds endpoints to an existing API and must follow the house contract.
  • An existing API is being normalised for versioning, error envelope, or rate limits.
  • A partner integration requires a published OpenAPI contract.
  • Mobile or SDK work is blocked on a stable contract for code generation.

Inputs

ArtifactProduced byRequired?Why
Context mapsystem-architecture-designrequiredDefines service/module boundaries the API sits inside
Critical-flow tablesystem-architecture-designrequiredSupplies latency/availability targets for endpoints
Access-pattern listdatabase-design-engineeringrequiredRead/write shapes drive resource model and pagination choices
Failure-mode listsystem-architecture-designoptionalInforms degradation behaviour on dependency outages
Threat modelvibe-security-skilloptionalInforms auth, rate-limit, and abuse-case rules
Tenancy modeldatabase-design-engineeringrequiredProves tenant isolation at the API boundary

Non-negotiables

  • OpenAPI spec is written before a single endpoint is implemented.
  • Tenant scope comes from the auth token, never from the request body or query string.
  • Every response carries the mandatory security headers from auth-and-security.md.
  • Every POST that causes an external side effect (payment, email, webhook, inventory movement) requires an Idempotency-Key.
  • Every new endpoint is added to the observability notes table before merge.
  • Breaking changes never mutate an existing version; they ship as a new major version.

Decision rules

Auth-method selection

Caller shapeChooseFailure mode if wrong
Server-to-server, trusted partner, long-livedAPI Key (SHA-256 hashed)JWT: can't be revoked fast; raw-key storage: leak = instant compromise
Web app with user consent, third-party accessedOAuth2 Authorization CodeImplicit flow: token leaks via URL history; ROPC: phishing vector
Service-to-service with scopes, standards-compliantOAuth2 Client CredentialsAPI key: no standardised scopes or introspection
First-party mobile app / SPAJWT access + refresh (short)Long-lived JWT: revocation impossible; session cookie: breaks on iOS
Legacy / tightly-controlled client with no user flowOAuth2 ROPC (last resort)Credentials pass through the API surface — avoid when any alternative

Versioning action

ChangeActionFailure mode if wrong
Adding optional field, endpoint, or enum valueShip in current version, mark non-breakingSpawning a new version for a safe change: client churn
Removing or renaming a fieldShip as new major version, sunset oldMutating existing version: silent parsing failures in clients
Changing response shape or required paramsShip as new major version, sunset oldAs above
Bug fix that narrows behaviour clients may depend onShip behind a header flag, deprecate quietlySilent fix: clients relying on the bug break in production

Idempotency requirement

Endpoint classRequire Idempotency-Key?TTLFailure mode if skipped
Payment, refund, chargeyes24 hDouble charges on retry
Order/invoice creationyes24 hDuplicate orders on network retry
Outbound email / webhook dispatchyes7 dDuplicate user-visible side effects
Inventory movementyes24 hPhantom stock changes
Read-only (GET, HEAD)non/an/a
Partial update without external effectoptional1 hBenign — but worth enabling on sensitive ops

Cache-Control choice

Resource shapeHeaderFailure mode if wrong
Public, rarely changes (prices)public, max-age=3600no-store: wastes bandwidth, slow clients
Per-user privateprivate, max-age=300public: leaks via shared CDN cache
Sensitive or mutable (auth, cart)no-storepublic: security incident

GraphQL vs REST

SituationChoose
Multiple clients with diverging field needsGraphQL
Public API, webhooks, file uploadsREST
Simple CRUDREST
Real-time subscriptionsGraphQL subscriptions

Failure mode if wrong: GraphQL-first for simple CRUD buys query-complexity DoS risk with no field-flexibility payoff; REST-first for multi-client heavy-reads pushes clients into over-fetch and N+1 round trips.

This table is the REST/GraphQL shortcut only. For real-time, service-to-service, event, or callback interactions (SSE, WebSocket, gRPC, webhooks, broker messaging), decide per interaction with references/api-style-selection.md; one-way live updates rarely need GraphQL subscriptions or WebSocket.

Design workflow (six steps)

  1. Define consumers, latency expectations, and trust boundaries.
  2. Write the API action plan, then model resources and actions around business concepts, not controller names.
  3. Write the OpenAPI contract, including auth, validation, errors, and pagination.
  4. Prove tenancy, authorisation, and idempotency rules before implementation.
  5. Design observability: request IDs, audit events, deprecation path, rate-limit telemetry.
  6. Validate that the API can evolve without breaking current consumers.

Full spec skeleton and per-step detail in references/openapi-workflow.md. For partner, public, long-lived, or workflow-heavy APIs, also load references/practical-api-architecture.md. For consumer ergonomics, endpoint naming, pagination, embedding, versioning, and test expectations, load references/api-you-wont-hate-rules.md.

Response envelope

The canonical envelope produced by this skill — every downstream client depends on it:

{
  "success": true,
  "data": { "id": 123 },
  "meta": { "page": 1, "per_page": 25, "total": 142 }
}
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The amount field is required.",
    "documentation_url": "https://api.example.com/errors#VALIDATION_ERROR",
    "fields": { "amount": ["Required"] }
  }
}

Detail, status-code mapping, and pagination mechanics live in references/rest-conventions.md.

Read next

  • skill-composition-standards — normalisation standard this skill was rewritten against; templates for the OpenAPI contract and error model live there.
  • observability-monitoring — consumes the observability notes table to build SLOs, alerts, and runbooks.
  • reliability-engineering — consumes the idempotency map for retry and circuit-breaker design.
  • deployment-release-engineering — consumes the versioning plan for migration choreography and rollback windows.
  • vibe-security-skill — consumes the auth model to build the threat model and abuse-case list.

Capability contract

Default to contract design and validation. Write specifications or generate clients only when authorised; do not deploy gateways, rotate credentials, or change production routes without approval.

Degraded mode

If consumers, traffic evidence, or the current contract are unavailable, produce a read-only draft with assumptions and unresolved compatibility risks; do not claim implementation readiness.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.