API Design

Designing Consistent API Error Responses

How to build a consistent error response format for your API — status codes, error objects, validation errors, and RFC 7807 Problem Details.

Why Consistency Matters

Nothing frustrates API consumers more than inconsistent error responses. One endpoint returns {"error": "not found"}, another returns {"message": "Not Found", "code": 404}, and a third returns plain text. Pick a format and stick to it.

The Basic Error Object

A good error response includes:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The request body contains invalid fields.",
    "details": [
      {"field": "email", "message": "Must be a valid email address."},
      {"field": "age", "message": "Must be a positive integer."}
    ]
  }
}

RFC 7807 Problem Details

RFC 7807 defines a standard format for error responses:

{
  "type": "https://api.example.com/errors/validation",
  "title": "Validation Error",
  "status": 422,
  "detail": "The email field is not a valid email address.",
  "instance": "/api/users/42"
}

The type field is a URI that links to documentation about the error type. This is the format recommended by the IETF and used by many modern APIs.

Matching Status Codes to Errors

ScenarioStatus CodeError Code
Missing required field400MISSING_FIELD
Invalid field value422VALIDATION_ERROR
Resource not found404NOT_FOUND
Authentication required401UNAUTHORIZED
Insufficient permissions403FORBIDDEN
Rate limit exceeded429RATE_LIMIT_EXCEEDED
Internal failure500INTERNAL_ERROR

Validation Errors

For validation errors, return all errors at once, not just the first one:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Multiple fields failed validation.",
    "fields": {
      "email": ["Invalid format.", "Already taken."],
      "password": ["Must be at least 8 characters."]
    }
  }
}

Anti-Patterns

  • 200 OK with an error body — Use proper HTTP status codes
  • Leaking stack traces — Never expose server internals in production
  • Generic messages — 'Something went wrong' helps nobody
  • Inconsistent field names — Pick message or msg and stick with it
  • Missing error codes — Numeric/string codes are machine-readable, messages are not

Best Practice

Adopt RFC 7807 or define your own consistent schema. Document it. Return the same structure for every error. Include an error code clients can switch on, a human-readable message, and field-level details for validation errors.

関連プロトコル

関連用語

同シリーズ API Design