How to handle errors in REST APIs

· Category: API & REST

Short answer

Good error handling in REST APIs provides enough information for clients to diagnose and recover from problems without exposing sensitive internals.

Steps

  1. Use the correct HTTP status code class for the error type.
  2. Return a structured error object with a machine-readable code and a human-readable message.
  3. Include a correlation ID to link the error to server logs.
  4. Provide a request ID and timestamp for troubleshooting.
  5. Document all possible error codes and their meanings in the API specification.

Tips

  • Differentiate between client errors that are retryable and those that are not.
  • Localize error messages if the API serves a global audience.
  • Avoid stack traces or database details in production error responses.
  • Use RFC 7807 Problem Details for consistent error formats.

Common issues

  • Returning 500 for all errors, masking actionable client mistakes.
  • Vague error messages that force developers to guess the cause.
  • Inconsistent error schemas across different endpoints.
  • Leaking sensitive information through verbose error details.

Example

curl -X GET https://api.example.com/users   -H "Accept: application/json"   -H "Authorization: Bearer $TOKEN"

This curl command demonstrates a standard GET request with headers for content negotiation and bearer token authentication.