Api design
Use when adding or changing an HTTP endpoint, choosing a status code, shaping a request or response body, adding pagination, filtering, or sorting to a list endpoint, designing an error format, or deciding whether a change needs a new API version. Also use when reviewing an endpoint someone else wrote, and when a client is about to depend on a response shape.From its SKILL.md
npx -y skills add m-de-graaff/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
11.6 KB, as published. Nobody here has run it
API Design
The wire contract: URLs, methods, status codes, response shapes, pagination, versioning. What
happens behind the handler is backend-patterns.
Core principle: the status code is part of the response. An API that returns 200 with
{"success": false} has thrown away the one field every client, proxy, and monitoring tool
already understands.
Resources
Nouns, plural, lowercase, kebab-case. The method is the verb.
GET /api/v1/team-members
GET /api/v1/team-members/:id
POST /api/v1/team-members
PATCH /api/v1/team-members/:id
DELETE /api/v1/team-members/:id
GET /api/v1/users/:id/orders # nesting expresses ownership
POST /api/v1/orders/:id/cancel # a verb, when the action isn't CRUD
Not: /getUsers (verb), /user (singular), /team_members (snake_case),
/users/:id/getOrders (both).
Nest one level, at most. /users/:id/orders/:orderId/items/:itemId should be
/order-items/:itemId — the client already has the ID, and deep nesting makes every URL depend
on a hierarchy that will change.
Methods and status codes
| Method | Idempotent | Body in response | For |
|---|---|---|---|
| GET | yes | yes | Reads. Never mutates — not even a counter |
| POST | no | yes | Create, or an action that isn't CRUD |
| PUT | yes | optional | Full replacement |
| PATCH | no | yes | Partial update |
| DELETE | yes | no | Remove |
| QUERY | yes | yes | A read whose parameters don't fit a URL — see below |
200 OK GET, PATCH, PUT with a body
201 Created POST that created something — include Location
204 No Content DELETE, or a PUT with nothing to say
400 Bad Request Malformed — bad JSON, missing required param
401 Unauthorized Not authenticated (the name is a misnomer)
403 Forbidden Authenticated, not allowed
404 Not Found Doesn't exist — or exists and isn't yours, when existence is a secret
409 Conflict State conflict: duplicate, version mismatch, already cancelled
422 Unprocessable Well-formed but semantically invalid — failed validation
429 Too Many Requests Include Retry-After
500 Internal Server Error Never expose the cause
503 Service Unavailable Include Retry-After
400 vs 422: 400 means you couldn't parse it, 422 means you parsed it and the values are wrong. If you only ever want one, use 400 — but be consistent, because clients branch on it.
403 vs 404: returning 403 for a resource that exists tells an attacker it exists. When existence is sensitive, return 404 for both.
QUERY — a safe method with a body
RFC 10008, June 2026. The first new HTTP method since PATCH in 2010, and it closes a real gap: a read whose parameters are too large or too structured for a URL.
The workaround has always been POST /search with a JSON body — which lies. POST is neither safe
nor idempotent, so intermediaries cannot cache it, clients cannot safely retry it, and every
proxy and log treats a search as a mutation. QUERY is safe, idempotent, and cacheable, with
the body carrying the query.
Reach for it when the query genuinely doesn't fit a URL: nested boolean filters, a geometry, a
long ID list, a structured search DSL. Not for ?status=active — a URL that works is better than
one that needs a body, because it is linkable, loggable, and cacheable everywhere today.
QUERY /api/v1/products HTTP/1.1
Content-Type: application/json
{"filter": {"and": [{"price": {"lte": 100}}, {"tags": {"in": ["a","b"]}}]}}
Requirements that differ from the methods above:
Content-Typeis mandatory. The server MUST fail a request whose Content-Type is missing or inconsistent with the body —415if the type is unsupported,400if the body is malformed,422if it parses but can't be processed.- The cache key MUST incorporate the request content. Caches may normalise insignificant differences for key generation only; they must not alter the request.
Accept-Queryis a response header (Structured Fields, a list of media ranges) advertising which query media types the resource accepts. It applies to every URI sharing the path.- Redirects behave unlike POST.
301,302,307,308all mean repeat the QUERY at the new URI.303means the result is a resource to fetch with GET.Locationmay point at an equivalent GET-able resource;Content-Locationat one holding the results. - Conditional requests work as they do for GET —
If-None-Match,If-Modified-Since,304.
Support it, don't require it
Adoption is partial and uneven. Node.js parses the method, OpenAPI 3.2 documents it, and
Cloudflare and Akamai co-authored the RFC so CDN support is likely to lead. But browser
fetch() cannot send it yet, HTML forms know only GET and POST, several major server frameworks
had not shipped support as of mid-2026, and WAFs, corporate proxies, and API gateways routinely
reject methods they don't recognise — often as a suspected attack rather than a clean 405.
So: accept QUERY, advertise it with Accept-Query, and keep POST working on the same
endpoint. Treat it as an optimisation for clients that can use it, never as the only path for a
client you don't control. Verify it survives your own edge before depending on it — the failure
mode is a request that never reaches your application.
Response shape
Pick one and never deviate — a client that handles two shapes has two bugs waiting.
{ "data": { "id": "abc-123", "email": "[email protected]", "created_at": "2025-01-15T10:30:00Z" } }
{
"data": [ { "id": "abc-123" }, { "id": "def-456" } ],
"meta": { "has_next": true, "next_cursor": "eyJpZCI6MTQzfQ" }
}
{
"error": {
"code": "validation_error",
"message": "Request validation failed",
"details": [
{ "field": "email", "code": "invalid_format", "message": "Must be a valid email address" }
]
}
}
code is for machines, message is for humans. Clients branch on code, so it must be
stable — changing it is a breaking change. message can be reworded freely.
The data envelope earns its place on public APIs: it leaves room for meta and links
without a breaking change. Internal APIs can return the resource bare and distinguish success by
status. Either is fine; mixing them is not.
Timestamps are ISO 8601 UTC. Field naming is snake_case or camelCase — whichever the
codebase already uses. Consistency beats preference.
Pagination
| Situation | Use |
|---|---|
| Feeds, infinite scroll, large or actively-written tables | Cursor |
| Admin tables under ~10k rows, search results where users expect page numbers | Offset |
| Public APIs | Cursor as the default |
GET /api/v1/users?cursor=eyJpZCI6MTIzfQ&limit=20
GET /api/v1/users?page=2&per_page=20
Offset is easy and supports "jump to page 8". It also gets slower the deeper you go — OFFSET 100000 makes the database walk 100,000 rows to discard them — and it skips and duplicates
rows when items are inserted while a client pages through. That last one is a correctness bug,
not a performance one, and it's why feeds use cursors.
Cursor pagination: order by a stable unique key, fetch limit + 1 to learn whether there's a
next page, and treat the cursor as opaque so you can change its contents later.
Always cap limit server-side. An uncapped per_page is a denial-of-service parameter.
Filtering, sorting, sparse fields
GET /api/v1/orders?status=active&customer_id=abc-123 # equality
GET /api/v1/products?price[gte]=10&price[lte]=100 # comparison
GET /api/v1/products?category=electronics,clothing # any-of
GET /api/v1/products?sort=-featured,price # - prefixes descending
GET /api/v1/users?fields=id,name,email # sparse fieldset
GET /api/v1/products?q=wireless+headphones # full-text
Filterable fields are an allowlist. Passing query params through to the query builder is how you get both an injection surface and full table scans on unindexed columns.
Versioning
/api/v1/ in the path. Explicit, routable, cacheable, and visible in every log line.
Don't version until you must. These are not breaking, and need no new version: adding a response field, adding an optional parameter, adding an endpoint, adding an enum value if you documented that clients must tolerate unknown ones.
These are breaking: removing or renaming a field, narrowing a type, changing a status code
for an existing condition, changing an error code, making an optional parameter required,
changing the URL.
Run at most two versions. Retire the old one with a Sunset header and real notice — six months
for a public API — then return 410 Gone.
Rate limiting
The contract, not the implementation (that's backend-patterns):
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640000000
HTTP/1.1 429 Too Many Requests
Retry-After: 60
{ "error": { "code": "rate_limit_exceeded", "message": "Try again in 60 seconds." } }
Send the headers on every response, not only on 429 — a client that can see it's at 95/100 can slow down instead of getting rejected.
Example — validation and creation
One example, TypeScript. The shape is what matters; it ports directly to Pydantic, Zod, or struct tags.
const createUser = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
});
export async function POST(req: NextRequest) {
const parsed = createUser.safeParse(await req.json());
if (!parsed.success) {
return NextResponse.json({
error: {
code: "validation_error",
message: "Request validation failed",
details: parsed.error.issues.map(i => ({
field: i.path.join("."),
code: i.code,
message: i.message,
})),
},
}, { status: 422 });
}
const user = await createUser(parsed.data);
return NextResponse.json(
{ data: user },
{ status: 201, headers: { Location: `/api/v1/users/${user.id}` } },
);
}
Note the field-level details. A 422 that says only "validation failed" forces the client to
guess which input to highlight.
Checklist
- Plural, kebab-case, no verbs, nested at most one level
- Method matches semantics; GET has no side effects
- Status codes used meaningfully — never 200 for failure
- 201 carries
Location - Input validated against a schema before anything touches the database
- Errors use the standard shape with a stable
codeand field-level details - List endpoints paginate, and
limitis capped server-side - Filterable and sortable fields are an allowlist, and indexed
- Auth required, or the endpoint is deliberately and documentedly public
- Authorization checked per resource, not just authentication
- No internal details in error responses — no stack traces, no SQL, no driver messages
- Naming consistent with the endpoints already shipped
- OpenAPI spec updated
Non-goals
Doesn't cover handler internals, persistence, caching, or background work (backend-patterns).
Doesn't cover GraphQL or gRPC. Doesn't review for vulnerabilities — that's /security-review.
Source
Adapted from ECC by Affaan Mohamed (MIT).