Api design
Use when designing new HTTP endpoints, reviewing endpoint designs for agent-friendliness, or verifying naming, error schema, pagination, and auth conventionsFrom its SKILL.md
npx -y skills add u-abramchuk/skills --skill api-designAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
2 things to look at
- no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
14.2 KB, as published. Nobody here has run it
HTTP Endpoint Design Rules
operationId
camelCase, verb+noun: createProject, listFiles, deleteUser, uploadProjectFile. Unique across the entire spec. Required on every endpoint — agents use these as function names. Never handler_post, api_v1_projects_post, or any auto-generated name.
HTTP status codes
| Code | Meaning | Agent action |
|---|---|---|
| 400 | Invalid request syntax | Fix the request — do not retry |
| 401 | Bad/expired credentials | Check code field: TOKEN_EXPIRED → refresh; TOKEN_INVALID → re-authenticate; do not retry the original request |
| 404 | Not found | Check IDs — do not retry |
| 409 | Conflict | Read conflicting_id from response to resolve without extra call — do not retry |
| 422 | Business logic validation | Fix configuration per detail — do not retry |
| 429 | Rate limited | Read Retry-After header (seconds); fall back to 60s if absent; retry |
| 500 | Server error | Retry only if method is safe or endpoint is idempotent (see retry matrix) |
| 502 | Upstream unavailable | Same as 500 |
| 410 | Gone (deliberately removed) | Do not retry; endpoint is permanently removed |
Use 422 (not 400) for business logic failures. 400 is for malformed requests; 422 is for well-formed requests that violate business rules.
Retry matrix — method safety
| Method | Safe to retry? | Condition |
|---|---|---|
| GET, HEAD, OPTIONS | Always | Reads only — no side effects |
| DELETE | Always | Idempotent by definition |
| PUT | Always | Idempotent by definition |
| POST | Only if x-agent-retryable: true in spec, or Idempotency-Key was sent | Check the spec before retrying |
| POST (non-idempotent) | Never | Retrying creates duplicates |
After max retries (3): surface the error to the user with the request_id. Do not silently swallow.
Retry backoff: parse Retry-After header if present; otherwise use exponential backoff starting at 1s (1s, 2s, 4s).
x-agent-* OpenAPI extensions
Add to every operation so agents can introspect behaviour from the spec itself:
post:
operationId: createInvoice
x-agent-retryable: false # false = non-idempotent POST; true = safe to retry
x-agent-idempotency: "Idempotency-Key" # header name if supported; omit if not
x-agent-timeout: 30 # seconds; agent aborts and surfaces error if exceeded
Rules:
- Every POST must set
x-agent-retryable x-agent-idempotencyis set only if the endpoint supports an idempotency headerx-agent-timeoutis required on every operation
Capability discovery — /openapi.json is mandatory
Every service must expose its current OpenAPI spec at /openapi.json without auth. This is how agents discover what the service can do. Not a "nice to have" — without it, agents must be pre-configured or guess at endpoints. Make it part of the server bootstrap, not an opt-in feature.
Pagination
offset + limit only. No opaque cursors. Every list response uses this envelope:
{"items": [...], "total": integer, "offset": integer, "limit": integer}
Empty results always return the full envelope — never null, never a missing items key:
{"items": [], "total": 0, "offset": 0, "limit": 20}
Bare array responses cannot be evolved without a breaking change. Offset pagination returns inconsistent results on large, frequently-changing datasets — document this constraint in the spec so agents know.
Pagination iteration pattern for agents — document this in docs/agent-integration.md for each paginated endpoint:
offset = 0
items = []
while True:
resp = get("/resources", params={"offset": offset, "limit": 100})
items += resp["items"]
if offset + resp["limit"] >= resp["total"]:
break
offset += resp["limit"]
Filtering and sorting
List endpoints that support filtering use query parameters with predictable naming:
| Pattern | Example | Notes |
|---|---|---|
| Exact match | ?status=active | Field name as param |
| Multiple values | ?status=active,archived | Comma-separated; OR semantics |
| Range | ?created_after=2026-01-01T00:00:00Z&created_before=2026-02-01T00:00:00Z | {field}_after / {field}_before for dates |
| Search | ?q=term | Free-text search across relevant fields |
| Sort | ?sort=created_at / ?sort=-created_at | Prefix - for descending; default sort documented in spec |
Rules:
- Every filter parameter is optional — omitting returns unfiltered results
- Invalid filter values return 400 with
INVALID_PARAMETER— never silently ignore - Document available filters in the operation's
parameterssection — agents discover filters from the spec, not from trial and error - Sorting defaults are documented in the operation description, not implicit
- Combine with pagination: filters apply before offset/limit
PATCH — partial updates
Use JSON Merge Patch (application/merge-patch+json, RFC 7396) as the default strategy:
- Send only the fields to update; omitted fields are unchanged
- Set a field to
nullto clear it (only if project uses Option A null convention) operationId:updateProject,patchUser— verb isupdateorpatch
patch:
operationId: updateProject
x-agent-retryable: true
x-agent-timeout: 10
requestBody:
content:
application/merge-patch+json:
schema:
$ref: '#/components/schemas/ProjectPatch'
Rules:
- PATCH is idempotent — same patch applied twice produces the same result. Set
x-agent-retryable: true. - Document which fields are patchable — not every field is. Non-patchable fields in the request body return 422 with
BUSINESS_RULE_VIOLATION. - Return the full resource after patch (not just the changed fields) — agents need the current state without an extra GET.
When to use PUT instead: full resource replacement where the client sends the complete object. PUT replaces; PATCH merges. Don't use PUT for partial updates.
Auth
All routes require auth except:
- Observability:
/health,/metrics,/version,/openapi.json - Authentication: routes that establish identity —
/login,/token,/oauth/callback,/registerand similar (these cannot require the identity they are establishing)
Declare auth in securitySchemes (Bearer JWT, API key, or OAuth2 — specify which).
Token lifecycle — document in docs/agent-integration.md
- TTL — or how to check expiry from the token itself (e.g., JWT
expclaim) - 401 distinction:
TOKEN_EXPIRED(refresh available) vsTOKEN_INVALID(re-authenticate from scratch) vsTOKEN_REVOKEDvsINSUFFICIENT_SCOPE - Refresh strategy: if refresh token available →
POST /token/refresh; else → re-authenticate fully - Proactive refresh: if the token has a known TTL, refresh when less than 20% of TTL remains rather than waiting for 401
Recommended error code taxonomy
Use these as the starting set. Extend per domain but stay consistent across services in the same platform.
| Code | When to use | HTTP status |
|---|---|---|
VALIDATION_FAILED | Request body fails schema validation | 400 |
INVALID_PARAMETER | Query or path parameter invalid | 400 |
TOKEN_EXPIRED | JWT or session expired; refresh available | 401 |
TOKEN_INVALID | Token malformed or signature invalid; re-auth | 401 |
TOKEN_REVOKED | Token was valid but explicitly revoked | 401 |
INSUFFICIENT_SCOPE | Token valid but lacks required scope | 403 |
NOT_FOUND | Resource does not exist | 404 |
SLUG_CONFLICT / RESOURCE_CONFLICT | Duplicate resource | 409 |
STATE_CONFLICT | Current state prevents the operation | 409 |
BUSINESS_RULE_VIOLATION | Valid request, violates a domain rule | 422 |
RATE_LIMITED | Too many requests | 429 |
INTERNAL_ERROR | Unexpected server error | 500 |
UPSTREAM_UNAVAILABLE | A dependency is down | 502 |
GONE | Resource deliberately removed | 410 |
Codes are machine-readable — never localized, never user-facing. The detail field is the human/agent-readable explanation.
Generated clients
Consumers use auto-generated clients, not hand-written HTTP calls. Regeneration runs via pre-commit hook; CI verifies clients match the current spec. See api-first-workflow/references/http-tooling.md for setup.
Three modification rules (Amundsen)
- Take nothing away
- Don't redefine things
- Make additions optional
Tolerant reader (Newman)
Design consumers to extract only what they need and ignore unknown response fields. Document this expectation in docs/agent-integration.md — minor versions may add new fields; consumers must not break.
Idempotency
Every POST endpoint must document its strategy:
- Idempotent by design: slug-based deduplication → 409 Conflict on duplicate (response includes
conflicting_id). Setx-agent-retryable: true. - Idempotency-Key header: client provides a UUID; server deduplicates on it. Set
x-agent-idempotency: "Idempotency-Key"andx-agent-retryable: true. - Explicitly non-idempotent: set
x-agent-retryable: false. Document clearly. Agents must not retry on 5xx.
409 Conflict — resolution data
Every 409 response must include enough data to resolve the conflict without an additional GET. Minimum:
{
"code": "SLUG_CONFLICT",
"detail": "Project with slug 'my-app' already exists",
"conflicting_id": "proj_abc123",
"request_id": "550e8400-e29b-41d4-a716-446655440000"
}
The field name for the conflicting resource is conflicting_id (or the equivalent per project convention — apply consistently across all services). Document what the agent should do with it.
Timestamps
All timestamp fields use RFC 3339 format (2026-01-01T00:00:00Z). In the OpenAPI schema, mark as type: string, format: date-time. Never return epoch integers or non-standard formats.
Null vs absent fields
Choose one convention per project and apply uniformly:
- Option A (recommended): Optional response fields that are inapplicable are always present as
null— never omitted. Mark optional fields in the schema and include them inrequiredfor responses. Agents never need to distinguish "missing" from "null". - Option B: Optional fields are omitted when inapplicable; presence is meaningful. Document this explicitly — agents must treat missing and
nullidentically only if the spec says so.
Consistency model
State-changing endpoints document their consistency model if non-obvious:
- Strong: read-your-own-writes guaranteed
- Eventual: reads may return stale data briefly
Correlation ID
Every error response must include a correlation ID field. Every success response should include it too. Propagate as X-Request-ID header in both directions. Include in logs.
Field name: choose one (request_id, requestId, correlationId) consistent with your stack's conventions and apply uniformly across all services. The X-Request-ID HTTP header name is independent of the JSON field name.
Deep module signal
An endpoint that simply wraps a single DB row operation (CRUD on one table, exposing the row's columns directly) is a sign the module boundary is in the wrong place. See api-first:module-boundaries.
Pre-commit checklist (20 items)
operationIdis set, camelCase verb+noun, uniqueinfo.versionbumped/openapi.jsonis exposed without auth (capability discovery)- All 4xx/5xx responses reference the
Errorcomponent - Error codes come from the recommended taxonomy (or are added deliberately, not ad-hoc)
Errorcomponent has: machine-readable error code, actionable detail message, correlation ID — consistent naming across all services- All list endpoints use
{"items": [...], "total", "offset", "limit"}envelope — empty state returns full envelope, nevernull - Auth in
securitySchemes; all routes require auth except observability + authentication endpoints - Every POST documents its idempotency strategy and has
x-agent-retryableset - Every operation has
x-agent-timeoutset x-agent-idempotencyheader name set on operations supporting Idempotency-Key- 401 responses use
TOKEN_EXPIREDvsTOKEN_INVALID(vsTOKEN_REVOKED,INSUFFICIENT_SCOPE) codes as appropriate - 409 responses include
conflicting_id(or equivalent) for agent self-resolution - All timestamp fields use
format: date-timein schema - Null/absent convention documented and applied consistently
detailmessages are actionable (not just status descriptions)- oasdiff ran locally — no breaking changes on minor bump (or new major version created)
docs/agent-integration.mdupdated if endpoint behaviour changed (includes pagination pattern, token lifecycle if new); intent→endpoint table updated- PATCH endpoints use
application/merge-patch+jsoncontent type and return the full resource - Filter/sort parameters are documented in the operation's
parameterssection with defaults stated
Red flags — STOP
- "We don't need
x-agent-*extensions — no agents use this" - "The error message is descriptive enough"
- "Pagination is obvious from the spec — no need for the iteration pattern in docs"
- "409 just means conflict — the consumer can GET the resource to find the conflicting ID"
- "We'll add the intent table when we write agent-integration.md"
- "
conflicting_idis non-standard — let's just usedetail"
Anti-patterns
- Bare array responses
- Opaque error messages (
{"error": "Bad Request"}) operationIdlikehandler_postorapi_v1_projects_post- Required request fields with no defaults
- Endpoints that expose internal DB row structure
- 409 responses with no resolution data
- Missing
x-agent-*extensions on POST operations - Designing error responses that only make sense when a human reads logs
SOFT REFERENCE: modularity:balanced-coupling — is this endpoint at the right abstraction level?
References
references/error-schema.md— full Error component schema, error code taxonomy,securitySchemestemplates,/openapi.jsonexposure, FastAPI example