agentsclimarketplace

Api design

Skill u-abramchuk/skills/skills/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

Install
npx -y skills add u-abramchuk/skills --skill api-design

Assembled 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

CodeMeaningAgent action
400Invalid request syntaxFix the request — do not retry
401Bad/expired credentialsCheck code field: TOKEN_EXPIRED → refresh; TOKEN_INVALID → re-authenticate; do not retry the original request
404Not foundCheck IDs — do not retry
409ConflictRead conflicting_id from response to resolve without extra call — do not retry
422Business logic validationFix configuration per detail — do not retry
429Rate limitedRead Retry-After header (seconds); fall back to 60s if absent; retry
500Server errorRetry only if method is safe or endpoint is idempotent (see retry matrix)
502Upstream unavailableSame as 500
410Gone (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

MethodSafe to retry?Condition
GET, HEAD, OPTIONSAlwaysReads only — no side effects
DELETEAlwaysIdempotent by definition
PUTAlwaysIdempotent by definition
POSTOnly if x-agent-retryable: true in spec, or Idempotency-Key was sentCheck the spec before retrying
POST (non-idempotent)NeverRetrying 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-idempotency is set only if the endpoint supports an idempotency header
  • x-agent-timeout is 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:

PatternExampleNotes
Exact match?status=activeField name as param
Multiple values?status=active,archivedComma-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=termFree-text search across relevant fields
Sort?sort=created_at / ?sort=-created_atPrefix - 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 parameters section — 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 null to clear it (only if project uses Option A null convention)
  • operationId: updateProject, patchUser — verb is update or patch
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, /register and 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 exp claim)
  • 401 distinction: TOKEN_EXPIRED (refresh available) vs TOKEN_INVALID (re-authenticate from scratch) vs TOKEN_REVOKED vs INSUFFICIENT_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.

CodeWhen to useHTTP status
VALIDATION_FAILEDRequest body fails schema validation400
INVALID_PARAMETERQuery or path parameter invalid400
TOKEN_EXPIREDJWT or session expired; refresh available401
TOKEN_INVALIDToken malformed or signature invalid; re-auth401
TOKEN_REVOKEDToken was valid but explicitly revoked401
INSUFFICIENT_SCOPEToken valid but lacks required scope403
NOT_FOUNDResource does not exist404
SLUG_CONFLICT / RESOURCE_CONFLICTDuplicate resource409
STATE_CONFLICTCurrent state prevents the operation409
BUSINESS_RULE_VIOLATIONValid request, violates a domain rule422
RATE_LIMITEDToo many requests429
INTERNAL_ERRORUnexpected server error500
UPSTREAM_UNAVAILABLEA dependency is down502
GONEResource deliberately removed410

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)

  1. Take nothing away
  2. Don't redefine things
  3. 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). Set x-agent-retryable: true.
  • Idempotency-Key header: client provides a UUID; server deduplicates on it. Set x-agent-idempotency: "Idempotency-Key" and x-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 in required for 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 null identically 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)

  1. operationId is set, camelCase verb+noun, unique
  2. info.version bumped
  3. /openapi.json is exposed without auth (capability discovery)
  4. All 4xx/5xx responses reference the Error component
  5. Error codes come from the recommended taxonomy (or are added deliberately, not ad-hoc)
  6. Error component has: machine-readable error code, actionable detail message, correlation ID — consistent naming across all services
  7. All list endpoints use {"items": [...], "total", "offset", "limit"} envelope — empty state returns full envelope, never null
  8. Auth in securitySchemes; all routes require auth except observability + authentication endpoints
  9. Every POST documents its idempotency strategy and has x-agent-retryable set
  10. Every operation has x-agent-timeout set
  11. x-agent-idempotency header name set on operations supporting Idempotency-Key
  12. 401 responses use TOKEN_EXPIRED vs TOKEN_INVALID (vs TOKEN_REVOKED, INSUFFICIENT_SCOPE) codes as appropriate
  13. 409 responses include conflicting_id (or equivalent) for agent self-resolution
  14. All timestamp fields use format: date-time in schema
  15. Null/absent convention documented and applied consistently
  16. detail messages are actionable (not just status descriptions)
  17. oasdiff ran locally — no breaking changes on minor bump (or new major version created)
  18. docs/agent-integration.md updated if endpoint behaviour changed (includes pagination pattern, token lifecycle if new); intent→endpoint table updated
  19. PATCH endpoints use application/merge-patch+json content type and return the full resource
  20. Filter/sort parameters are documented in the operation's parameters section 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_id is non-standard — let's just use detail"

Anti-patterns

  • Bare array responses
  • Opaque error messages ({"error": "Bad Request"})
  • operationId like handler_post or api_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, securitySchemes templates, /openapi.json exposure, FastAPI example

Keep looking

Skills are one crate of 607,533. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.