agentleFS
blyatiful1blyatiful1/ultraweb/skills/api-design/SKILL.md

api-design

Skill1 starsChanged 3 months agoMITView on GitHub

Design and build the site's HTTP API surface — Next.js route handlers with typed Response.json, zod v4 validation at every boundary, one consistent error envelope (stable code + human message), strict status-code discipline, and the decision rule for when server actions beat API routes (internal mutations) and when routes win (external consumers, webhooks, non-browser clients). Invoke during the backend phase whenever the brief needs HTTP endpoints or the user says "API", "endpoint", "REST", "route handler", "webhook", or "expose the data". For the site's own forms mutating its own data, use ultraweb:server-actions instead.

125 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use data-modeling, ci-pipeline and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • mmondoraSkill

    data-modeling

    Schema design, multi-tenant data isolation, and migration management. Firestore and PostgreSQL patterns, RLS, UUID v7 conventions. Use when designing database schemas, writing migrations, or implementing multi-tenant data access.

    Also in 7 projects that use this

  • vndeeSkill

    ci-pipeline

    Use when creating or updating CI/CD pipelines with GitHub Actions or GitLab CI for Go, Python, or React projects

    Also in 4 projects that use this

  • pluginagentmarketplaceSkill

    microservices

    Microservices architecture patterns and best practices. Service decomposition, inter-service communication, and distributed data management.

    Also in 4 projects that use this

  • kevinaimonsterSkill

    typescript-strict

    TypeScript strict mode and advanced type system assistant. Helps write strictly-typed TypeScript code with generics, type guards, utility types, conditional types, mapped types, and template literal types. Trigger when user says 'TypeScript types' 'type gymnastics' 'TypeScript generics' 'strict TypeScript' 'type guard' 'TS类型' 'TypeScript严格模式' '类型体操' '泛型怎么写' 'TS type help'. Keywords: TypeScript, strict mode, generics, type guard, utility types, conditional types, mapped types, template literal types, infer, extends, keyof, typeof, type narrowing, discriminated unions, type assertion, type predicate, type gymnastics, TS, 类型体操, 泛型, 类型守卫, 严格类型

    Also in 4 projects that use this

  • InfopibeSkill

    deployment-patterns

    Deployment workflows, CI/CD pipeline patterns, Docker containerization, health checks, rollback strategies, and production readiness checklists for web applications.

    Also in 10 projects that use this

  • DatabricksSkill

    load-testing

    Load test a Databricks App to find its maximum QPS. Use when: (1) User says 'load test', 'benchmark', 'QPS', 'throughput', or 'performance test', (2) User wants to find how many queries per second their app can handle, (3) User wants to set up load testing scripts for their agent, (4) User wants to view load test results/dashboard, (5) User wants to validate results or observe latency/error rate with MLflow tracing.

    Also in 4 projects that use this

The file

We split this skill into the rules it gives an agent

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

  • 0

    Common

    Most of the 104 edited versions we read keep these.

  • 3

    Distinctive

    This author's own choices. Worth a look.

  • 4

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Default: server actions for mutations, direct queries for reads.

    line 24
  2. Very specific:

    Create lib/api.ts with the envelope helpers below.

    line 29
  3. Very specific:

    Write handlers. await params — dynamic segments are Promises in Next 16.

    line 31
  4. Distinctive:

    200: read/update ok · 201 created (return the created resource) · 204 deleted (empty body)

    line 84
  5. Very specific:

    500: only for genuine bugs. Wrap handler bodies so an unexpected throw returns apiError(500, "internal", ...) — never Next's default error …

    line 86
  6. Distinctive:

    Never 200-with-error-body.

    line 87
  7. Very specific:

    Every public unauthenticated POST (contact, newsletter, sign-up) gets a rate-limit check before parsing.

    line 91

“Common” is measured: kept by at least 6 in 10 of the 104 edited versions of this file we could read. “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 — boring contracts, typed boundaries

Stage: Phase 7 (Backend) - Reads: design/BRIEF.md, db/schema.ts (when database ran) - Writes: app/api/**/route.ts, lib/api.ts

Standard

A first-grade API is boring to consume: every response typed, every error the same shape, every status code meaning what RFC 9110 says. A consumer could write their client from three example responses. Every route traces to a line in BRIEF.md — zero endpoints "just in case".

First decision: route handler or not

ConsumerTool
Your own forms/buttons mutating your dataServer action (ultraweb:server-actions) — typed end-to-end, progressive enhancement, no public surface
External services calling in (Stripe/Resend webhooks)Route handler — they need a URL
Non-browser clients (mobile app, partner, CLI)Route handler — they need HTTP
Client components fetching on interaction (typeahead, infinite scroll)Route handler GET
An RSC that needs dataNeither — query the database directly (ultraweb:data-fetching)

Default: server actions for mutations, direct queries for reads. Route handlers only where HTTP itself is the requirement.

Process

  1. List every endpoint BRIEF.md demands: method, path, auth requirement, request/response shape. Empty list → this skill doesn't run.
  2. Create lib/api.ts with the envelope helpers below. Every handler imports it — no handler invents its own error shape.
  3. Define zod v4 schemas per endpoint (in the route file; lib/validators.ts when shared with a server action). Validate everything that crosses the boundary: body, searchParams, dynamic params.
  4. Write handlers. await params — dynamic segments are Promises in Next 16.
  5. Auth-gate protected routes first thing in the handler (session via ultraweb:auth); return 401 before doing any work.
  6. Exercise every endpoint with curl: happy path, invalid body, missing auth. Three real responses per endpoint, recorded, before calling it done.

The envelope

Success returns the resource directly. Failure returns ONE shape, always:

// lib/api.ts
export type ApiError = { error: { code: string; message: string } };

export function apiError(status: number, code: string, message: string) {
  return Response.json({ error: { code, message } } satisfies ApiError, { status });
}

code is a stable machine string (validation_failed, unauthorized, not_found, conflict, rate_limited, internal); message is written for humans in the site's voice. Never leak stack traces, zod issue arrays, or SQL into message.

A worked handler

// app/api/posts/[id]/route.ts
import { z } from "zod";
import { apiError } from "@/lib/api";
import { auth } from "@/lib/auth";

const patchSchema = z.object({
  title: z.string().min(3, { error: "Title needs at least 3 characters" }).optional(),
  published: z.boolean().optional(),
});

export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await auth.api.getSession({ headers: req.headers });
  if (!session) return apiError(401, "unauthorized", "Sign in required.");

  const { id } = await params;
  const json = await req.json().catch(() => null);
  const parsed = patchSchema.safeParse(json);
  if (!parsed.success)
    return apiError(400, "validation_failed", parsed.error.issues[0].message);

  const post = await updatePost(id, parsed.data, session.user.id);
  if (!post) return apiError(404, "not_found", "Post not found.");

  return Response.json(post satisfies Post);
}

Load-bearing details: zod v4 customizes errors with { error: "..." } — the message param is deprecated. .catch(() => null) on req.json() turns malformed JSON into a clean 400 instead of a 500. satisfies types the response at compile time with zero runtime cost.

Status codes

  • 200 read/update ok · 201 created (return the created resource) · 204 deleted (empty body)
  • 400 validation failed or malformed JSON · 401 no valid session · 403 valid session, forbidden resource · 404 absent (also for resources the caller must not learn exist) · 409 uniqueness/state conflict · 429 rate limited, with Retry-After header
  • 500 only for genuine bugs. Wrap handler bodies so an unexpected throw returns apiError(500, "internal", ...) — never Next's default error page as an API response.
  • Never 200-with-error-body. Never 500 for bad input.

Rate-limit hook points

Every public unauthenticated POST (contact, newsletter, sign-up) gets a rate-limit check before parsing. Ship the seam even as a stub — an early checkRateLimit(ip) in lib/api.ts returning 429. Which limiter backs it: verify against current docs first; STACK.md pins none.

Anti-patterns

  • middleware.ts — Next 16 renamed it proxy.ts; and proxy checks are optimistic, never API authorization
  • success: false, { err:, { errorMessage: — a second error shape anywhere
  • NextApiRequest, res.status( — Pages Router relics; handlers speak Web Request/Response
  • params.id without await — params are Promises
  • parsed.error.message sent raw to clients — zod's aggregate string is an internal artifact
  • fetch("/api/ from an RSC in the same app — self-HTTP round trip; call the query function directly
  • app/api/[...slug] catch-all re-implementing Express inside Next

Worked example — Tidepool, versioned read API for Fleet customers

Moved to references/example.md — read only when this build's case is genuinely ambiguous; the sections above are the decision material.

Composes with

Moved to references/composes.md — the handoff map; load it when orchestrating this skill against its neighbors.

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.