Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
API Developmentbeginner

API Response Formatter

Share

Standardize API response format

Works with OpenClaude

You 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

  1. Create a response wrapper utility that enforces a standard envelope structure with status, data, error, and meta fields
  2. Define status constants (success, error, validation_error) to replace magic strings and HTTP status codes
  3. Build a success response formatter that wraps payload data with metadata like timestamp and request_id
  4. Build an error response formatter that includes error code, message, and details fields
  5. Create middleware or decorators to automatically apply formatting to controller/handler responses
  6. Add HTTP status code mapping so the wrapper translates internal status to correct HTTP codes (200, 400, 404, 500)
  7. Integrate validation error handling to format schema/input validation failures consistently
  8. 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

Quick Info

Difficultybeginner
Version1.0.0
AuthorClaude Skills Hub
apiresponseformat

Install command:

curl -o ~/.claude/skills/api-response-formatter.md https://claude-skills-hub.vercel.app/skills/api/api-response-formatter.md

Related API Development Skills

Other Claude Code skills in the same category — free to download.

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.