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).
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.
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.ts if 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
details array. 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-After header.
- 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-key header 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
ab or hey).
- Success: All happy paths return correct status + shape. Error paths return consistent error objects. No secrets leaked. Validation prevents bad data.
References
1---2name: api-route-builder3description: 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.4license: Apache-2.05---67## Overview89Designs 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.1011## When to Use This Skill1213- Creating or refactoring backend API endpoints (Next.js App Router, Express, Fastify, tRPC).14- The user describes a resource or action ("user profile", "create order", "list products with filters").15- You need consistent error handling, validation, and documentation across an API.16- Preparing an API for production or for consumption by frontend/mobile clients.1718## Prerequisites1920- Backend framework decided (Next.js API routes / App Router, Express, Fastify, tRPC + Next.js, etc.).21- Validation library installed or ready to install (`zod`, `joi`, `yup`).22- Authentication/authorization strategy known (JWT, sessions, API keys, OAuth).23- Database or service layer that the route will call.24- For OpenAPI: `swagger-ui-express`, `redoc`, or built-in Next.js OpenAPI tooling.2526## Steps27281. **Determine API style and resource**:29 - REST (resource-oriented, HTTP verbs) vs tRPC (type-safe procedures).30 - Resource name (plural for collections, e.g., `/users`, `/orders`).31 - Action for non-CRUD (e.g., `POST /orders/{id}/cancel`).32332. **Select HTTP method and status codes** (use this table):34 | Method | Success | Created | No Content | Common Errors |35 |--------|---------|---------|------------|---------------|36 | GET | 200 | — | — | 404, 400 |37 | POST | 200/201 | 201 | — | 400, 409, 422 |38 | PUT | 200 | — | 204 | 400, 404, 409 |39 | PATCH | 200 | — | 204 | 400, 404 |40 | DELETE | 200/204 | — | 204 | 404, 409 |41423. **Define input validation schema** (Zod recommended):43 - Path params, query params, body, headers.44 - Use `.strict()` to reject unknown fields.45 - Coerce types where safe (e.g., `z.coerce.number()` for IDs from URLs).46 - Provide human-friendly error messages.47484. **Implement consistent error response format**:49 ```json50 {51 "error": {52 "code": "VALIDATION_ERROR",53 "message": "Invalid input",54 "details": [...]55 }56 }57 ```58 - Define a small set of standard error codes.59605. **Structure the handler**:61 - Parse & validate input first.62 - Authorize the request (call auth middleware or check session).63 - Perform business logic (call service/repository).64 - Return success response or throw/return typed error.65 - Use try/catch with centralized error handler.66676. **Add middleware chain** (in order):68 - CORS (if needed)69 - Rate limiting70 - Body parser (framework default)71 - Authentication72 - Authorization / RBAC73 - Validation (or do inside handler)74 - Logging / request ID75767. **Add rate limiting stub**:77 - Use `express-rate-limit`, `upstash/ratelimit`, or Next.js middleware.78 - Document the limits (e.g., 100 requests per 15 minutes per IP for public endpoints).79808. **Document with OpenAPI**:81 - Add JSDoc or comment annotations that tools can convert (or use `zod-to-openapi`).82 - Include request/response schemas, auth requirements, error responses.83849. **Security checklist** (always apply):85 - Validate all input (never trust client).86 - Use parameterized queries / ORM to prevent SQL injection.87 - Sanitize output (especially user-generated content).88 - Set security headers (Helmet or manual: CSP, HSTS, X-Frame-Options, etc.).89 - Return generic error messages to clients; log full details server-side.90 - Implement proper CORS (never `*` in production).919210. **Output the complete route + supporting code**:93 - The route/handler file.94 - Zod schemas in a separate `schemas.ts` if complex.95 - Example curl or HTTP request.96 - Test suggestions.9798## Examples99100**Example 1: Create User (POST /api/users) - Next.js App Router + Zod**101102```ts103// app/api/users/route.ts104import { NextRequest, NextResponse } from 'next/server';105import { z } from 'zod';106107const CreateUserSchema = z.object({108 email: z.string().email(),109 name: z.string().min(1).max(100),110 password: z.string().min(8).max(128),111}).strict();112113export async function POST(request: NextRequest) {114 try {115 const body = await request.json();116 const data = CreateUserSchema.parse(body);117118 // TODO: hash password, check for existing user, create in DB119 const user = await createUser(data);120121 return NextResponse.json(122 { id: user.id, email: user.email, name: user.name },123 { status: 201 }124 );125 } catch (error) {126 if (error instanceof z.ZodError) {127 return NextResponse.json(128 { error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: error.errors } },129 { status: 422 }130 );131 }132 console.error('Create user error:', error);133 return NextResponse.json(134 { error: { code: 'INTERNAL_ERROR', message: 'Something went wrong' } },135 { status: 500 }136 );137 }138}139```140141**OpenAPI annotation example** also included.142143**Example 2: tRPC Procedure** (similar complete router definition).144145## Edge Cases & Error Handling146147- **Validation fails**: Return 422 with structured `details` array. Never leak internal validation library names.148- **Resource not found**: Return 404 with a standard error body. Do not distinguish "not found" vs "no permission" for security.149- **Rate limit exceeded**: Return 429 with `Retry-After` header.150- **Concurrent modification (409)**: For optimistic locking or unique constraint violations.151- **Large payloads**: Enforce body size limits at the framework level + document in the route.152- **Idempotency**: For POST that should be idempotent, require an `idempotency-key` header and implement deduplication.153- **Authentication failures**: Always return 401 (not 403) for missing/invalid credentials. 403 only for insufficient permissions on a known identity.154155## Verification1561571. Add the route to the project and run the dev server.1582. Test with curl or Postman using the exact examples provided.1593. Send invalid payloads — verify 422 responses with clear messages.1604. Check that sensitive fields (passwords, tokens) are never returned in responses.1615. Run `npm run build` — TypeScript clean.1626. If OpenAPI generated, open Swagger UI and confirm the endpoint appears with correct schemas.1637. Load test the rate limiting (use `ab` or `hey`).1648. Success: All happy paths return correct status + shape. Error paths return consistent error objects. No secrets leaked. Validation prevents bad data.165166## References167168- [REST API Design Best Practices](https://restfulapi.net/)169- [Zod Documentation](https://zod.dev/)170- [OWASP API Security Top 10](https://owasp.org/API-Security/editions/2023/en/0x00-header/)171- [RFC 7807 Problem Details for HTTP APIs](https://datatracker.ietf.org/doc/html/rfc7807)172- Framework-specific docs (Next.js Route Handlers, Express, tRPC)