API Endpoint Builder
Build REST API endpoints following security and performance best practices.
Workflow
Execute this process for building API endpoints:
1. Plan the Endpoint
- Determine HTTP method (GET, POST, PUT, DELETE)
- Design path pattern following REST conventions
- Identify required input validation
- Define output format (JSON, status codes)
2. Validate Security
- Input validation and sanitization
- Authentication/authorization checks
- Rate limiting considerations
- SQL injection prevention
- XSS protection
3. Implement Structure
- Create route handler file
- Add middleware for validation
- Implement error handling
- Add request/response types
- Include logging
4. Add Tests
- Unit tests for handler
- Integration tests for route
- Validation test cases
- Error scenario tests
5. Verify Compliance
- Check error codes follow conventions
- Verify response format consistency
- Validate security headers
- Test input validation
Example Implementation
// POST /api/users
export async function POST(request: NextRequest) {
try {
// 1. Validate input
const body = await request.json();
const validated = CreateUserSchema.parse(body);
// 2. Check authentication
const user = await authenticate(request);
if (!user || !hasPermission(user, "create_user")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// 3. Create user
const newUser = await createUser(validated);
// 4. Return response
return NextResponse.json({ user: sanitizeUser(newUser) }, { status: 201 });
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: "Invalid input", details: error.errors },
{ status: 400 },
);
}
logger.error("Create user failed", { error, userId: user?.id });
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 },
);
}
}
Best Practices
- Always validate input - Use Zod or similar for schema validation
- Use parameterized queries - Prevent SQL injection
- Implement rate limiting - Protect against abuse
- Log security events - Track authentication failures
- Use proper status codes - 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 500 Internal Server Error
- Sanitize output - Prevent XSS attacks
- Version your APIs - Use /api/v1/ paths
- Document responses - Use OpenAPI/Swagger
Integration
This skill integrates with:
security - Security patterns and validation
backend-patterns - Backend best practices
engineering-lifecycle - Testing requirements
Genetic Code
This component carries essential Seed System principles for context: fork isolation:
Delta Standard: Good Component = Expert Knowledge − What Claude Already Knows
Recognition Questions:
- "Would Claude know this without being told?" → Delete (zero delta)
- "Can this work standalone?" → Fix if no (non-self-sufficient)
- "Did I read the actual file, or just see it in grep?" → Verify before claiming
MANDATORY: Use parameterized queries to prevent SQL injection
MANDATORY: Implement proper authentication/authorization checks
MANDATORY: Return appropriate HTTP status codes (400, 401, 403, 500)
MANDATORY: Log security events (authentication failures, errors)
No exceptions. API security is non-negotiable.
1---2name: api-endpoint-builder3description: Build REST API endpoints when designing or implementing API routes with security best practices. Not for client-side fetching or non-API logic.4---56# API Endpoint Builder78Build REST API endpoints following security and performance best practices.910## Workflow1112Execute this process for building API endpoints:1314### 1. Plan the Endpoint1516- Determine HTTP method (GET, POST, PUT, DELETE)17- Design path pattern following REST conventions18- Identify required input validation19- Define output format (JSON, status codes)2021### 2. Validate Security2223- Input validation and sanitization24- Authentication/authorization checks25- Rate limiting considerations26- SQL injection prevention27- XSS protection2829### 3. Implement Structure3031- Create route handler file32- Add middleware for validation33- Implement error handling34- Add request/response types35- Include logging3637### 4. Add Tests3839- Unit tests for handler40- Integration tests for route41- Validation test cases42- Error scenario tests4344### 5. Verify Compliance4546- Check error codes follow conventions47- Verify response format consistency48- Validate security headers49- Test input validation5051## Example Implementation5253```typescript54// POST /api/users55export async function POST(request: NextRequest) {56 try {57 // 1. Validate input58 const body = await request.json();59 const validated = CreateUserSchema.parse(body);6061 // 2. Check authentication62 const user = await authenticate(request);63 if (!user || !hasPermission(user, "create_user")) {64 return NextResponse.json({ error: "Unauthorized" }, { status: 401 });65 }6667 // 3. Create user68 const newUser = await createUser(validated);6970 // 4. Return response71 return NextResponse.json({ user: sanitizeUser(newUser) }, { status: 201 });72 } catch (error) {73 if (error instanceof z.ZodError) {74 return NextResponse.json(75 { error: "Invalid input", details: error.errors },76 { status: 400 },77 );78 }7980 logger.error("Create user failed", { error, userId: user?.id });81 return NextResponse.json(82 { error: "Internal server error" },83 { status: 500 },84 );85 }86}87```8889## Best Practices9091- **Always validate input** - Use Zod or similar for schema validation92- **Use parameterized queries** - Prevent SQL injection93- **Implement rate limiting** - Protect against abuse94- **Log security events** - Track authentication failures95- **Use proper status codes** - 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 500 Internal Server Error96- **Sanitize output** - Prevent XSS attacks97- **Version your APIs** - Use /api/v1/ paths98- **Document responses** - Use OpenAPI/Swagger99100## Integration101102This skill integrates with:103104- `security` - Security patterns and validation105- `backend-patterns` - Backend best practices106- `engineering-lifecycle` - Testing requirements107108---109110## Genetic Code111112This component carries essential Seed System principles for context: fork isolation:113114<critical_constraint>115MANDATORY: All components MUST be self-contained (zero .claude/rules dependency)116MANDATORY: Achieve 80-95% autonomy (0-5 AskUserQuestion rounds per session)117MANDATORY: Description MUST use What-When-Not format in third person118MANDATORY: No component references another component by name in description119MANDATORY: Progressive disclosure - references/ for detailed content120MANDATORY: Use XML for control (mission_control, critical_constraint), Markdown for data121No exceptions. Portability invariant must be maintained.122</critical_constraint>123124**Delta Standard**: Good Component = Expert Knowledge − What Claude Already Knows125126**Recognition Questions**:127128- "Would Claude know this without being told?" → Delete (zero delta)129- "Can this work standalone?" → Fix if no (non-self-sufficient)130- "Did I read the actual file, or just see it in grep?" → Verify before claiming131 MANDATORY: Use parameterized queries to prevent SQL injection132 MANDATORY: Implement proper authentication/authorization checks133 MANDATORY: Return appropriate HTTP status codes (400, 401, 403, 500)134 MANDATORY: Log security events (authentication failures, errors)135 No exceptions. API security is non-negotiable.136 </critical_constraint>