agentleFS
mDevsLabsmDevsLabs/Skills/skills/rest-api-designer/SKILL.md

rest-api-designer

Skill2 starsChanged 4 months agoMITView on GitHub

Designs consistent, evolvable HTTP/REST APIs — resource modelling, URL and method choice, status codes, pagination, filtering, errors, idempotency, versioning, auth and rate limiting — and emits an OpenAPI 3.1 specification. Use when the user is designing a new endpoint or service, reviewing an existing API contract, deciding on REST conventions, writing an OpenAPI or Swagger file, or planning a breaking change to a public interface.

1 other project uses a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

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

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    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. Distinctive:

    Do not use for: GraphQL or gRPC schema design, internal function signatures, or event/message schemas (different constraints entirely).

    line 24
  2. Distinctive:

    Start from the nouns the client cares about, not the internal tables or the service methods.

    line 31
  3. Distinctive:

    Never put a verb in a path when a method expresses it.

    line 39
  4. Distinctive:

    Use RFC 9457 Problem Details:

    line 84
  5. Very specific:

    Every error carries a stable machine-readable code, a human message, and a correlation id.

    line 101
  6. Very specific:

    Never use "" or -1 as a sentinel.

    line 138
  7. Very specific:

    Never accept id, role, ownerId or createdAt from the client on create.

    line 176

≈ “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

REST API Designer

Design HTTP interfaces that stay predictable for a decade.

When to use

New endpoints, API reviews, OpenAPI authoring, versioning and deprecation plans, error-model design.

Do not use for: GraphQL or gRPC schema design, internal function signatures, or event/message schemas (different constraints entirely).

Workflow

1. Model resources, not actions

Start from the nouns the client cares about, not the internal tables or the service methods.

  • Plural, lowercase, hyphenated collections: /purchase-orders, not /getPurchaseOrder or /purchaseOrders.
  • Nest at most one level to express ownership: /orders/{orderId}/items. Beyond that, use a top-level collection with a filter: /items?orderId=123.
  • Never put a verb in a path when a method expresses it.
  • For genuine actions that are not CRUD, use a sub-resource with POST: POST /orders/{id}/cancellation or POST /orders/{id}:cancel. Document the choice once and apply it everywhere.
  • Identifiers in paths are opaque strings. Prefer ULID/UUID over sequential integers in public APIs (no enumeration, no business leakage).

2. Choose the method by its contract

MethodSafeIdempotentBodyUse for
GETyesyesnoRead. Never mutates, never has side effects
POSTnonoyesCreate in a collection; non-CRUD actions
PUTnoyesyesFull replace at a client-known URL
PATCHnono*yesPartial update (JSON Merge Patch, RFC 7386)
DELETEnoyesnoRemove. Repeat calls return 404 or 204 — pick one and document it
HEADyesyesnoExistence and metadata checks

* Make PATCH idempotent when possible; avoid relative operations like "increment": 1.

3. Status codes — a small, disciplined set

CodeMeaningNotes
200OKBody present
201CreatedMust include a Location header
202AcceptedAsync — return a status resource URL
204No ContentNo body at all
400Bad RequestMalformed syntax or invalid parameter
401UnauthorizedMissing or invalid credentials
403ForbiddenAuthenticated but not permitted
404Not FoundAlso used to hide existence from unauthorised callers
409ConflictState conflict, duplicate unique field
410GonePermanently removed / retired version
412Precondition FailedIf-Match mismatch (optimistic concurrency)
422UnprocessableSyntactically valid, semantically invalid
429Too Many RequestsMust include Retry-After
500Internal ErrorNever leak a stack trace
503UnavailableInclude Retry-After

Rules: never return 200 with {"error": ...} inside; never invent codes; choose 400 vs 422 once and stay consistent.

4. One error model everywhere

Use RFC 9457 Problem Details:

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Validation failed",
  "status": 422,
  "detail": "2 fields are invalid.",
  "instance": "/orders/01J8X2",
  "traceId": "0af7651916cd43dd8448eb211c80319c",
  "errors": [
    { "field": "email",    "code": "format",  "message": "Must be a valid email." },
    { "field": "quantity", "code": "min",     "message": "Must be at least 1." }
  ]
}

Every error carries a stable machine-readable code, a human message, and a correlation id. Never expose internals (SQL, hostnames, stack traces).

5. Collections: pagination, filtering, sorting

Cursor pagination is the default — stable under concurrent writes and cheap at depth:

GET /orders?limit=50&cursor=eyJpZCI6IjAxSjhYIn0
→ { "data": [...], "pagination": { "nextCursor": "...", "hasMore": true } }

Offset pagination is acceptable only for small, static datasets that need page numbers. Always cap limit (e.g. max 100) and document the default.

Filtering: ?status=paid&createdAfter=2026-01-01. Reserve ?q= for free-text search. For ranges use explicit ...After / ...Before parameters rather than operator-in-value syntax (?amount=gt:100) — the latter is hard to type-check.

Sorting: ?sort=-createdAt,name (leading - for descending). Whitelist the sortable fields.

Sparse fields: ?fields=id,name,status. Expansion: ?expand=customer, bounded to one level.

6. Consistency contracts

  • Naming: pick camelCase or snake_case for JSON bodies and never mix. Query parameters follow the same convention.
  • Dates: RFC 3339 UTC strings (2026-07-28T14:03:00Z). Never epoch ints, never local time.
  • Money: minor-unit integer + ISO 4217 currency ({"amount": 1999, "currency": "EUR"}). Never floats.
  • Enums: lowercase snake strings. Clients must tolerate unknown values.
  • Booleans: name them positively (enabled, not isNotDisabled).
  • Nulls: null means "explicitly empty"; omit a field to mean "unknown". Never use "" or -1 as a sentinel.
  • Envelope: wrap collections in {"data": [...], "pagination": {...}}; return single resources unwrapped. Be consistent across the whole API.

7. Reliability primitives

ConcernMechanism
Duplicate POSTsIdempotency-Key header; store key → response for 24 h and replay
Lost updatesETag + If-Match → 412 on mismatch
CachingCache-Control, ETag, Last-Modified; 304 on If-None-Match
Long operations202 + Location: /operations/{id} polling resource
Bulk workPOST /batch with per-item status in a 207-style response body
Rate limitsRateLimit-Limit, RateLimit-Remaining, RateLimit-Reset, 429 + Retry-After
TracingAccept and propagate W3C traceparent

8. Versioning and deprecation

Version in the URL path (/v1/...) for public APIs — visible, cache-friendly, trivially routable. Media-type versioning is more elegant and less used; pick one.

Non-breaking (ship freely): adding an endpoint, an optional request field, a response field, or a new enum value if clients were told to tolerate them.

Breaking (needs a new version): removing or renaming a field, changing a type, making an optional field required, tightening validation, changing a status code, changing pagination semantics, changing default behaviour.

Deprecation: announce → send Deprecation and Sunset headers → monitor usage per client → contact remaining callers → return 410 after the sunset date. Minimum 6 months for a public API.

9. Security baseline

TLS only. OAuth 2.1 / OIDC bearer tokens for user context, mTLS or signed keys for service-to-service. Validate every input against a schema and reject unknown fields on write. Authorise per resource instance, never only per route. Return 404 rather than 403 when existence itself is sensitive. Rate-limit per principal. Never accept id, role, ownerId or createdAt from the client on create.

10. Emit the OpenAPI 3.1 spec

Produce a spec with: reusable components/schemas, shared responses for every error, securitySchemes, examples on each operation, operationId in camelCase, and tags grouping. Validate it before delivering.

Tools

ScriptUse
scripts/openapi_lint.pyLints a spec against every convention in this skill
assets/problem-details.jsonReady-to-paste RFC 9457 error schema + standard responses
python3 scripts/openapi_lint.py openapi.json --format md
python3 scripts/openapi_lint.py openapi.yaml --min-severity warning   # CI gate

It checks verbs in paths, nesting depth, method semantics, status-code coverage, Location headers, pagination and its cap, idempotency keys, security schemes, money-as-float, date formats, naming consistency and missing examples. Exit code 1 on any error-level finding.

Worked example

Requirement: "Let customers cancel an order and get a refund."

Design

POST /v1/orders/{orderId}/cancellation
Idempotency-Key: 8f1c...            (required)
If-Match: "W/\"v7\""                (optional, optimistic concurrency)

{ "reason": "customer_request", "note": "Ordered the wrong size" }

201 Created
Location: /v1/orders/01J8X2/cancellation
{
  "id": "01J8XC",
  "orderId": "01J8X2",
  "status": "pending_refund",
  "reason": "customer_request",
  "refund": { "amount": 4999, "currency": "EUR", "status": "processing" },
  "createdAt": "2026-07-28T14:03:00Z"
}

Errors: 404 unknown order · 409 already cancelled or already shipped · 412 stale If-Match · 422 invalid reason code · 403 not the order owner.

Why not POST /v1/cancelOrder — a verb path cannot be cached, cannot be referenced, and cannot report its own state. Cancellation is a real entity with an id, a status and a refund; modelling it as a sub-resource makes it queryable and retry-safe.

Quality checklist

  • openapi_lint.py passes with no error-level findings
  • No verbs in resource paths (except a documented :action convention)
  • Nesting depth ≤ 1
  • Every method matches its safety/idempotency contract
  • Every endpoint documents 401, 403, 404, 422, 429 and 500
  • One error format across the whole API
  • Collections paginated with a capped limit
  • Dates RFC 3339 UTC; money in minor units with a currency
  • Naming convention uniform across paths, params and bodies
  • Unsafe non-idempotent operations accept Idempotency-Key
  • Breaking-change audit done; version bumped if needed
  • OpenAPI 3.1 spec validates and includes examples

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.