API Design Skill
This skill ensures that all backend API routes are robust, type-safe, and secure.
Standards
- •Framework: Use Next.js App Router (
app/api/route.ts). - •Validation: Use
zodfor all request body/query validation. - •Typing:
- •Define a
Requestschema. - •Define a
Responseinterface.
- •Define a
- •Error Handling:
- •Use
try/catchblocks. - •Return standard HTTP status codes (200, 400, 401, 500).
- •Return JSON:
{ success: false, error: "message" }.
- •Use
Template
When creating a new API route, use this structure:
typescript
import { NextResponse } from 'next/server';
import { z } from 'zod';
// 1. Schema Definition
const RequestSchema = z.object({
email: z.string().email(),
// ... other fields
});
// 2. Handler
export async function POST(request: Request) {
try {
const body = await request.json();
// 3. Validation
const validatedData = RequestSchema.parse(body);
// 4. Business Logic
// ...
return NextResponse.json({ success: true, data: ... });
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({ success: false, error: error.errors }, { status: 400 });
}
return NextResponse.json({ success: false, error: "Internal Server Error" }, { status: 500 });
}
}
Checklist
- • Is input validated with Zod?
- • Are sensitive errors masked in production?
- • Is the response type explicitly clear?