api-route-builder
Skill1 starsChanged 5 months agoApache-2.0View on GitHub
Designs and implements RESTful or tRPC API routes with input validation, error handling, and OpenAPI documentation. Use when building backend routes in Next.js, Express, Fastify, or similar.
In this repository58 other files it gives its agents.
- agent-chain-designerSkill
- api-wrapper-builderSkill
- embeddings-builderSkill
- evaluation-harnessSkill
- fine-tuning-preparerSkill
- llm-router-builderSkill
- ml-model-trainerSkill
- model-benchmarkerSkill
- prompt-engineerSkill
- rag-pipeline-builderSkill
- synthetic-data-generatorSkill
- vector-db-integratorSkill
- csv-processorSkill
- database-schema-designerSkill
- data-pipeline-builderSkill
- etl-workflow-designerSkill
- json-transformerSkill
- pandas-data-cleanerSkill
- report-generatorSkill
- sql-query-optimizerSkill
- time-series-analyzerSkill
- visualization-generatorSkill
- backup-strategySkill
- ci-cd-optimizerSkill
- docker-compose-generatorSkill
- github-actions-pipelineSkill
- kubernetes-deploymentSkill
- load-balancer-configSkill
- log-aggregator-setupSkill
- monitoring-dashboardSkill
- nginx-config-generatorSkill
- security-hardeningSkill
- ssl-certificate-managerSkill
- terraform-module-builderSkill
- api-security-auditorSkill
- compliance-checkerSkill
- dependency-checkerSkill
- incident-responderSkill
- jwt-security-auditorSkill
- owasp-checkerSkill
- penetration-test-plannerSkill
- secret-detectorSkill
- threat-model-designerSkill
- vulnerability-scannerSkill
- accessibility-auditorSkill
- auth-flow-builderSkill
- css-animation-crafterSkill
- form-validatorSkill
- graphql-schema-designerSkill
- html-component-builderSkill
- nextjs-app-scaffoldSkill
- performance-auditorSkill
- pwa-setupSkill
- react-component-generatorSkill
- responsive-layout-systemSkill
- seo-optimizerSkill
- tailwind-design-systemSkill
- websocket-integrationSkill
The file
We split this skill into the rules it gives an agent
12 rules. About 0 are common, 8 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈8
Distinctive · estimate
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
- Very specific: line 50
Use .strict() to reject unknown fields.
- Distinctive: line 71
Use try/catch with centralized error handler.
- Very specific: line 83
Use express-rate-limit, upstash/ratelimit, or Next.js middleware.
- Distinctive: line 84
Document the limits (e.g., 100 requests per 15 minutes per IP for public endpoints).
- Very specific: line 87
Add JSDoc or comment annotations that tools can convert (or use zod-to-openapi).
- Distinctive: line 92
Use parameterized queries / ORM to prevent SQL injection.
- Distinctive: line 159
Authentication failures: Always return 401 (not 403) for missing/invalid credentials.
- Distinctive: line 163
Add the route to the project and run the dev server.
- Distinctive: line 164
Test with curl or Postman using the exact examples provided.
- Distinctive: line 166
Check that sensitive fields (passwords, tokens) are never returned in responses.
- Very specific: line 167
Run npm run build — TypeScript clean.
- Distinctive: line 168
If OpenAPI generated, open Swagger UI and confirm the endpoint appears with correct schemas.
≈ “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.
Files
Overview
Designs and implements secure, well-documented API routes following REST conventions or tRPC patterns. The skill produces route handlers with strong input validation (Zod or Joi), consistent error responses, proper HTTP status codes, rate limiting stubs, security headers, middleware ordering, and OpenAPI/Swagger annotations or tRPC router definitions.
When to Use This Skill
- Creating or refactoring backend API endpoints (Next.js App Router, Express, Fastify, tRPC).
- The user describes a resource or action ("user profile", "create order", "list products with filters").
- You need consistent error handling, validation, and documentation across an API.
- Preparing an API for production or for consumption by frontend/mobile clients.
Prerequisites
- Backend framework decided (Next.js API routes / App Router, Express, Fastify, tRPC + Next.js, etc.).
- Validation library installed or ready to install (
zod,joi,yup). - Authentication/authorization strategy known (JWT, sessions, API keys, OAuth).
- Database or service layer that the route will call.
- For OpenAPI:
swagger-ui-express,redoc, or built-in Next.js OpenAPI tooling.
Steps
- Determine API style and resource:
- REST (resource-oriented, HTTP verbs) vs tRPC (type-safe procedures).
- Resource name (plural for collections, e.g.,
/users,/orders). - Action for non-CRUD (e.g.,
POST /orders/{id}/cancel).
- Select HTTP method and status codes (use this table):
Method Success Created No Content Common Errors GET 200 — — 404, 400 POST 200/201 201 — 400, 409, 422 PUT 200 — 204 400, 404, 409 PATCH 200 — 204 400, 404 DELETE 200/204 — 204 404, 409 - Define input validation schema (Zod recommended):
- Path params, query params, body, headers.
- Use
.strict()to reject unknown fields. - Coerce types where safe (e.g.,
z.coerce.number()for IDs from URLs). - Provide human-friendly error messages.
- Implement consistent error response format:
{ "error": { "code": "VALIDATION_ERROR", "message": "Invalid input", "details": [...] } }- Define a small set of standard error codes.
- Structure the handler:
- Parse & validate input first.
- Authorize the request (call auth middleware or check session).
- Perform business logic (call service/repository).
- Return success response or throw/return typed error.
- Use try/catch with centralized error handler.
- Add middleware chain (in order):
- CORS (if needed)
- Rate limiting
- Body parser (framework default)
- Authentication
- Authorization / RBAC
- Validation (or do inside handler)
- Logging / request ID
- Add rate limiting stub:
- Use
express-rate-limit,upstash/ratelimit, or Next.js middleware. - Document the limits (e.g., 100 requests per 15 minutes per IP for public endpoints).
- Use
- Document with OpenAPI:
- Add JSDoc or comment annotations that tools can convert (or use
zod-to-openapi). - Include request/response schemas, auth requirements, error responses.
- Add JSDoc or comment annotations that tools can convert (or use
- Security checklist (always apply):
- Validate all input (never trust client).
- Use parameterized queries / ORM to prevent SQL injection.
- Sanitize output (especially user-generated content).
- Set security headers (Helmet or manual: CSP, HSTS, X-Frame-Options, etc.).
- Return generic error messages to clients; log full details server-side.
- Implement proper CORS (never
*in production).
- Output the complete route + supporting code:
- The route/handler file.
- Zod schemas in a separate
schemas.tsif complex. - Example curl or HTTP request.
- Test suggestions.
Examples
Example 1: Create User (POST /api/users) - Next.js App Router + Zod
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
const CreateUserSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
password: z.string().min(8).max(128),
}).strict();
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const data = CreateUserSchema.parse(body);
// TODO: hash password, check for existing user, create in DB
const user = await createUser(data);
return NextResponse.json(
{ id: user.id, email: user.email, name: user.name },
{ status: 201 }
);
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: error.errors } },
{ status: 422 }
);
}
console.error('Create user error:', error);
return NextResponse.json(
{ error: { code: 'INTERNAL_ERROR', message: 'Something went wrong' } },
{ status: 500 }
);
}
}OpenAPI annotation example also included.
Example 2: tRPC Procedure (similar complete router definition).
Edge Cases & Error Handling
- Validation fails: Return 422 with structured
detailsarray. Never leak internal validation library names. - Resource not found: Return 404 with a standard error body. Do not distinguish "not found" vs "no permission" for security.
- Rate limit exceeded: Return 429 with
Retry-Afterheader. - Concurrent modification (409): For optimistic locking or unique constraint violations.
- Large payloads: Enforce body size limits at the framework level + document in the route.
- Idempotency: For POST that should be idempotent, require an
idempotency-keyheader and implement deduplication. - Authentication failures: Always return 401 (not 403) for missing/invalid credentials. 403 only for insufficient permissions on a known identity.
Verification
- Add the route to the project and run the dev server.
- Test with curl or Postman using the exact examples provided.
- Send invalid payloads — verify 422 responses with clear messages.
- Check that sensitive fields (passwords, tokens) are never returned in responses.
- Run
npm run build— TypeScript clean. - If OpenAPI generated, open Swagger UI and confirm the endpoint appears with correct schemas.
- Load test the rate limiting (use
aborhey). - Success: All happy paths return correct status + shape. Error paths return consistent error objects. No secrets leaked. Validation prevents bad data.
References
- REST API Design Best Practices
- Zod Documentation
- OWASP API Security Top 10
- RFC 7807 Problem Details for HTTP APIs
- Framework-specific docs (Next.js Route Handlers, Express, tRPC)
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
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.

