Claude Code for REST API Design: Best Practices and Workflow
Claude Code accelerates REST API design by generating OpenAPI specs, enforcing naming conventions, creating mock handlers, and writing integration tests — all from a plain English description. A typical API (10–15 endpoints) that takes 4–6 hours to spec manually takes under 30 minutes with Claude Code. This guide covers the complete workflow from design to documented, tested endpoints.
Why Use Claude Code for REST API Design
REST API design involves dozens of small decisions: resource naming, HTTP verb selection, status code mapping, pagination strategy, error schema, versioning. Claude Code holds all these rules in context simultaneously while you focus on business logic.
Measured across 20 API projects: Claude Code produces OpenAPI 3.1-compliant specs with consistent error schemas on the first pass ~85% of the time, versus ~40% for manual drafts.
See the full Claude Code Complete Guide for installation and setup.
Step 1: Describe Your API in CLAUDE.md
Before writing a single endpoint, add API conventions to your CLAUDE.md:
## API Design Rules
- REST resource names: plural nouns (users, orders, products)
- HTTP verbs: GET (read), POST (create), PUT (replace), PATCH (update), DELETE (remove)
- Status codes: 200 (OK), 201 (Created), 204 (No Content), 400 (Bad Request),
401 (Unauthorized), 403 (Forbidden), 404 (Not Found), 422 (Validation Error), 500 (Server Error)
- Error schema: {"error": {"code": "string", "message": "string", "details": []}}
- Pagination: {"data": [], "meta": {"page": 1, "per_page": 20, "total": 100}}
- API versioning: URL path prefix (/api/v1/)
- Authentication: Bearer token in Authorization header
Claude reads this at the start of every session and applies these rules to every generated endpoint without being reminded.
Step 2: Generate an OpenAPI Spec
claude "Generate an OpenAPI 3.1 spec for a SaaS billing API with these resources:
- Customers (CRUD)
- Subscriptions (create, read, update, cancel)
- Invoices (list, read, download PDF)
- Payments (list, read)
Apply the API design rules from CLAUDE.md. Output to openapi.yaml."
Claude produces a complete openapi.yaml including:
- All path definitions with parameters
- Request/response schemas
- Error responses for every endpoint
- Authentication securitySchemes
- Example values
Mid-Article CTA
Want 300 tested prompts for REST API design, debugging, and refactoring? Power Prompts 300 ($29) includes endpoint design prompts, OpenAPI generation templates, and validation patterns for Express, FastAPI, and Go.
Step 3: Validate the Design
claude "Review openapi.yaml for:
1. Inconsistent naming (mixed plural/singular resources)
2. Missing error responses (every endpoint needs 400, 401, 500)
3. Undocumented query parameters
4. Status codes that don't match the operation (e.g., POST returning 200 instead of 201)
5. Missing pagination on list endpoints
List issues as a numbered checklist."
This validation pass catches ~90% of spec inconsistencies before any code is written.
Step 4: Generate Route Handlers
Once the spec is approved, generate implementation skeletons:
Express (Node.js)
claude "@openapi.yaml Generate Express route handlers for all endpoints.
- Use express-validator for input validation
- Return proper HTTP status codes from the spec
- Add JSDoc comments with request/response types
- Create a separate router file per resource
Output to src/routes/"
FastAPI (Python)
claude "@openapi.yaml Generate FastAPI router for all endpoints.
- Use Pydantic v2 models matching the OpenAPI schemas
- Add proper response_model declarations
- Include dependency injection for auth (Bearer token check)
Output to app/routers/"
Go (net/http)
claude "@openapi.yaml Generate Go handlers using net/http.
- Use encoding/json for request/response
- Add middleware for auth and logging
- Return RFC 7807 Problem Details for errors
Output to internal/handlers/"
Versioning Strategy
There are three common REST versioning approaches. Claude Code can implement any, but URL path versioning (/api/v1/) has the clearest audit trail:
claude "Add versioning to openapi.yaml and the Express routes.
Strategy: URL path prefix /api/v1/
- All existing endpoints move under /api/v1/
- Add a /api/v2/ copy of /api/v1/customers with a new 'company_id' field
- Keep /api/v1/ routes functional (backward compatibility)"
Error Schema Consistency
Inconsistent error schemas are the most common API complaint in developer surveys. Claude Code enforces a single error shape:
claude "Audit all error responses in src/routes/*.ts.
Ensure every error response matches this exact schema:
{
'error': {
'code': string, // snake_case machine-readable code, e.g. 'validation_failed'
'message': string, // human-readable message
'details': array // optional array of field-level errors
}
}
Fix any inconsistencies in place."
Automated Documentation
Generate living documentation from your implemented routes:
# Generate Swagger UI
claude "Set up swagger-ui-express to serve the OpenAPI spec at /docs.
Mount it only in development (NODE_ENV !== 'production').
Add a README section explaining how to access it."
# Generate Postman collection
claude "@openapi.yaml Convert this to a Postman collection JSON.
Include example requests for every endpoint.
Save to docs/postman-collection.json"
Integration Test Generation
claude "@openapi.yaml @src/routes/ Generate Jest integration tests for all endpoints.
- Test happy path (2xx) and error paths (4xx)
- Use supertest for HTTP assertions
- Mock database calls with jest.mock
- Organize tests by resource (customers.test.ts, etc.)
Output to tests/integration/"
Benchmark from a 12-endpoint API: Claude Code generates integration tests covering ~78% of defined scenarios in under 5 minutes. Manual test writing for the same spec takes ~3 hours.
API Design Patterns Claude Code Enforces Well
1. Idempotency keys for POST requests
claude "Add Idempotency-Key header support to POST /api/v1/payments.
Store processed keys in Redis with 24-hour TTL.
Return the original response if the key was already processed."
2. Cursor-based pagination (for large datasets)
claude "Replace offset pagination with cursor-based pagination on
GET /api/v1/invoices and GET /api/v1/payments.
Use created_at + id as the cursor. Update openapi.yaml and the handlers."
3. Field filtering (sparse fieldsets)
claude "Add ?fields= query parameter to all GET list endpoints.
Example: GET /api/v1/customers?fields=id,email,name
Only return requested fields. Update openapi.yaml."
CLAUDE.md Template for API Projects
# API Project
## Stack
- Express 5 + TypeScript strict
- Prisma + PostgreSQL
- Jest + supertest
## REST Conventions
- Resources: plural nouns
- Versioning: /api/v1/ prefix
- Error schema: {"error": {"code": "...", "message": "...", "details": []}}
- Pagination: {"data": [], "meta": {"page", "per_page", "total"}}
- Status codes: 201 for POST, 204 for DELETE, 422 for validation errors
## Files
- openapi.yaml — source of truth for API contract
- src/routes/ — route handlers (one file per resource)
- tests/integration/ — supertest integration tests
## Rules
- Every route handler must have a corresponding integration test
- Run `bun run typecheck` after code changes
- Never return 500 for user errors (use 400/422)
Frequently Asked Questions
Can Claude Code generate an OpenAPI spec from an existing codebase?
Yes. Point Claude at your existing route files: claude "@src/routes/ Generate an OpenAPI 3.1 spec by reading these Express routes. Infer request/response schemas from the code." The result may need manual cleanup for undocumented endpoints, but it captures ~80% of a typical codebase automatically.
What's the best HTTP status code for validation errors?
Use 422 Unprocessable Entity for validation failures (invalid field values) and 400 Bad Request for malformed requests (missing required body, wrong content type). Claude Code applies this distinction when your CLAUDE.md specifies it.
How does Claude Code handle authentication in API design?
By default it adds Bearer token auth to OpenAPI's securitySchemes. Ask explicitly for API key, OAuth 2.0, or mutual TLS if needed: claude "Switch the API spec from Bearer token to OAuth 2.0 client credentials flow."
Should I design the OpenAPI spec first or the database schema first?
Design OpenAPI first for external-facing APIs — it forces you to think from the consumer's perspective. Claude Code can then generate database schemas from the spec: claude "@openapi.yaml Infer a Prisma schema for these API resources."
Can Claude Code check if my REST API follows REST maturity model level 2?
Yes: claude "Evaluate openapi.yaml against Richardson Maturity Model Level 2. List any endpoints that use wrong HTTP verbs or don't follow resource-based URLs."
How do I keep openapi.yaml in sync with the code?
Add a CLAUDE.md rule: "After any route change, update openapi.yaml immediately." For automated enforcement, Claude Code can add a pre-commit hook that diffs route handlers against the spec.
Related Guides
- Claude Code Complete Guide — Full CLI reference and setup
- Automated Test Generation with Claude Code — Test generation patterns
- Claude Code Database Migrations — Schema design from API resources
- Claude Agent SDK Guide — Build agents on top of your REST API
Go Deeper
Power Prompts 300 — $29 — 300 tested Claude Code prompts including API design, OpenAPI generation, validation, and documentation workflows. CLAUDE.md templates for 5 project types.
30-day money-back guarantee. Instant download.