$ npx rulesync-cli pull✓ Wrote CLAUDE.md (2 rulesets)# Coding Standards- Always use async/await- Prefer named exports
Best Practices

AI Rules for API Development: Patterns That Prevent Bad Endpoints

The specific rules that stop AI from generating APIs with inconsistent responses, missing validation, and poor error handling.

8 min read·July 9, 2025

Every AI-generated endpoint should follow the same contract

Rules for response formats, error handling, validation, and authentication

The API Consistency Problem

AI assistants generate endpoints that work — but every endpoint works differently. One returns { data: user }, another returns { user }, a third returns the user object directly. Error responses are equally inconsistent: { error: 'not found' } vs { message: 'User not found', code: 404 } vs a plain string.

This inconsistency makes API consumers' lives miserable. Frontend developers can't write a generic API client because every endpoint has a different response shape. Error handling becomes a per-endpoint switch statement instead of a unified pattern.

A handful of rules creates complete API consistency. Once the AI knows your response envelope, error format, and validation approach, every generated endpoint follows the same contract.

Rule 1: Consistent Response Envelope

Define your response format once and the AI applies it everywhere. The most common pattern: success responses wrap data in { data: T, meta?: object }, error responses use { error: { message: string, code: string } }.

The rule: 'All API responses use the envelope pattern. Success: { data: T }. Errors: { error: { message: string, code: string } }. Never return raw objects or arrays at the top level. Never return 200 with an error message in the body — use appropriate HTTP status codes.'

Add a specific example in your rule file for the AI to pattern-match against. One three-line JSON example is worth a paragraph of description.

⚠️ Consistency Matters

When every endpoint returns a different response shape, frontend developers can't write a generic API client. One rule — 'All responses use { data: T } envelope' — fixes the entire API surface.

Rule 2: Structured Error Handling

API error handling is where AI assistants diverge most from production standards. Without rules, the AI generates try/catch blocks that return generic 500 errors, swallowing the actual error information.

The rule: 'Use custom error classes (AppError, ValidationError, NotFoundError) with HTTP status codes. Never catch errors silently — always return structured error responses. Use error middleware for unhandled errors. Log errors with request context (requestId, userId, path).'

For validation errors specifically: 'Return 400 with an array of field-level errors: { error: { message: "Validation failed", code: "VALIDATION_ERROR", details: [{ field: "email", message: "Invalid format" }] } }.'

💡 Structured Errors

Return validation errors as field-level arrays: { error: { details: [{ field: 'email', message: 'Invalid' }] } }. This format lets frontends map errors to form fields automatically.

Rule 3: Input Validation at the Boundary

Every API endpoint should validate its input before processing. Without this rule, AI assistants trust incoming data — accessing req.body.email without checking if it exists, is a string, and is a valid email format.

The rule: 'Validate all request input at the handler level using Zod (TypeScript), Pydantic (Python), or your framework's validation library. Define a schema for every endpoint's params, query, and body. Return 400 for invalid input with field-level error details. Never access unvalidated request data.'

Rule 4: Auth and Authorization Patterns

AI assistants frequently generate endpoints without any authentication — or with authentication implemented inline rather than through middleware. Both are dangerous: public endpoints expose data, and inline auth is inconsistent.

The rule: 'All non-public endpoints must use the auth middleware. Extract the authenticated user from the middleware — never from the request directly. Check authorization (does this user have access to this resource?) in the handler, not the middleware. Use role-based or resource-based access control, never arbitrary checks.'

⚠️ Auth Is Not Optional

AI assistants frequently generate endpoints without any authentication. The rule 'All non-public endpoints must use auth middleware' prevents data exposure from the first generated endpoint.

Complete API Rules Template

Here's a consolidated set of API development rules. Add this as a dedicated section in your CLAUDE.md for any project with REST API endpoints.

  • Response envelope: { data: T } for success, { error: { message, code } } for errors
  • HTTP status codes: 200 success, 201 created, 400 validation, 401 unauth, 403 forbidden, 404 not found, 500 server error
  • Input validation: Zod/Pydantic schema for every endpoint — reject invalid input with 400
  • Auth middleware: required on all non-public endpoints — never inline auth checks
  • Error handling: custom error classes, structured responses, error middleware for unhandled
  • Rate limiting: apply to all public endpoints — return 429 with Retry-After header
  • Logging: structured logs with requestId, userId, method, path, status, duration