Standardize API response format
✓Works with OpenClaudeYou are an API design specialist. The user wants to standardize API response format across endpoints to ensure consistent structure, error handling, and metadata.
What to check first
- Verify your API framework (Express, FastAPI, Django REST, etc.) and current response patterns
- Check if you have existing middleware or interceptor patterns in place
- Review your error handling approach — catch blocks, validation failures, HTTP status codes
Steps
- Create a response wrapper utility that enforces a standard envelope structure with
status,data,error, andmetafields - Define status constants (
success,error,validation_error) to replace magic strings and HTTP status codes - Build a success response formatter that wraps payload data with metadata like
timestampandrequest_id - Build an error response formatter that includes error
code,message, anddetailsfields - Create middleware or decorators to automatically apply formatting to controller/handler responses
- Add HTTP status code mapping so the wrapper translates internal status to correct HTTP codes (200, 400, 404, 500)
- Integrate validation error handling to format schema/input validation failures consistently
- Test with Postman or curl to verify all response types (success, client error, server error) match the standard
Code
// responseFormatter.js - Express.js implementation
class ApiResponse {
constructor(status = 'success', data = null, error = null, meta = {}) {
this.status = status;
this.data = data;
this.error = error;
this.meta = {
timestamp: new Date().toISOString(),
...meta
};
}
}
const ResponseFormatter = {
success: (data, meta = {}) => {
return new ApiResponse('success', data, null, meta);
},
error: (message, code = 'INTERNAL_ERROR', details = null, meta = {}) => {
return new ApiResponse('error', null, {
code,
message,
details
}, meta);
},
validationError: (errors, meta = {}) => {
return new ApiResponse('validation_error', null, {
code: 'VALIDATION_FAILED',
message: 'Request validation failed',
details: errors
}, meta);
}
};
// Middleware to handle response formatting and status codes
const formatResponseMiddleware = (req, res, next) => {
const originalJson = res.json;
res.json = function(data) {
if (data instanceof ApiResponse) {
const statusMap = {
success: 200,
validation_error: 400,
error: data.error?.code === 'NOT_FOUND' ? 404 : 500
};
res.status(statusMap[data.status] || 500);
return originalJson.call(this, data);
}
return originalJson.call(this, data);
};
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Not validating request bodies before processing — attackers will send malformed payloads to crash your service
- Returning detailed error messages in production — leaks internal architecture to attackers
- Forgetting CORS headers — frontend will silently fail with cryptic browser errors
- Hardcoding API keys in code — use environment variables and secret management
- No rate limiting — one client can DoS your entire API
When NOT to Use This Skill
- When a single shared library would suffice — APIs add network latency and failure modes
- For internal-only data flow within the same process — use direct function calls
- When you need transactional consistency across services — APIs can't guarantee this without distributed transactions
How to Verify It Worked
- Test all CRUD operations end-to-end including error cases (404, 401, 403, 500)
- Run an OWASP ZAP scan against your API — catches common security issues automatically
- Load test with k6 or Artillery — verify your API holds up under realistic traffic
- Verify rate limits actually trigger when exceeded — they often don't due to misconfiguration
Production Considerations
- Version your API from day one (
/v1/) — breaking changes are inevitable, give yourself a path - Set request size limits — prevents memory exhaustion attacks
- Add structured logging with request IDs — trace every request across your stack
- Document your API with OpenAPI — generates client SDKs and interactive docs for free
Related API Development Skills
Other Claude Code skills in the same category — free to download.
REST API Scaffold
Scaffold a complete REST API with CRUD operations
GraphQL Schema Generator
Generate GraphQL schema from existing data models
API Documentation
Generate OpenAPI/Swagger documentation from code
API Versioning
Implement API versioning strategy
Rate Limiter
Add rate limiting to API endpoints
API Error Handler
Create standardized API error handling
Request Validator
Add request validation middleware (Zod, Joi)
Webhook Handler
Create webhook endpoint with signature verification
Want a API Development skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.