Skip to content
IRC-CodingIRC-Coding
REST APIError HandlingError ObjectsProblem DetailsRFC 7807HTTP Status Codes

REST API Error Handling: Status Codes & Problem Details

Master REST API error handling with HTTP status codes, structured error objects, RFC 7807 Problem Details, and best practices.

S

schutzgeist

6 min read
REST API Error Handling: Status Codes & Problem Details

REST API Error Handling: Status Codes and Error Objects

Good REST API error handling helps developers understand, locate, and fix problems quickly, without guessing.

Quick Overview

REST API error handling defines how an interface responds to invalid requests, technical failures, and business rule violations. This includes selecting the right HTTP status code, structuring the error response, and identifying errors uniquely. RFC 7807 defines Problem Details as a standard error format, with fields like type, title, status, detail, and instance. Effective error handling is consistent across all endpoints, provides enough information for developers, and avoids leaking internal security details. It reduces support overhead, improves Developer Experience, and lets clients automatically classify and respond to errors appropriately.

When you work with APIs, server-side errors become your biggest challenge. One provider might enforce token and request limits, and they might also use Cloudflare, which has its own rate limits and rules. If your requests only get partially processed or seem to fail sporadically, solid debugging matters. You need to understand what response you’re getting and what it means.

Key Components

Correct HTTP Status Codes

HTTP status codes are the first signal a client receives about request success or failure. 4xx codes indicate client errors; 5xx codes signal server errors. Important 4xx codes include 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Content, and 429 Too Many Requests. 5xx codes such as 500 Internal Server Error, 502 Bad Gateway, and 503 Service Unavailable point to server-side issues.

Problem Details per RFC 7807

RFC 7807 defines a standard format for error responses. A Problem Detail must include type, title, status, and detail. You can optionally add instance for the problematic URI and other extensions. The Content-Type is application/problem+json. This format lets clients parse and display errors consistently.

Unique Error Identifiers

Each error response should contain a unique error ID—a UUID or correlation ID, for example. This lets you trace errors in logs and monitoring systems without exposing internal details. Clients can provide the error ID to support.

Error Categories and Codes

Beyond HTTP status codes, error responses should include application-specific error codes. A code like ORDER_NOT_FOUND or PAYMENT_DECLINED is more precise than a generic 404. These codes help clients respond to specific situations.

Validation Errors

For validation errors, the response should name the failing fields and explain why. For example: field: email, message: Invalid email format. This lets clients correct forms directly on the client side.

Avoiding Internal Details

Error messages should be informative but must not expose internal paths, stack traces, or database details. Such information can aid attackers. Keep internal details in logs, not in API responses.

Localization and Language

Error messages can be language-dependent. Clients declare their language preference via the Accept-Language header. The server responds with appropriately localized messages if available.

Retry Information

For transient errors like 429 or 503, the server should use the Retry-After header to tell the client when to retry. This prevents thoughtless retries and reduces server load.

Logging and Monitoring

Every error should be logged server-side with context: Request-ID, timestamp, endpoint, status code, and error details. Monitoring systems can then trigger alerts and spot error trends.

Consistency Across All Endpoints

All endpoints in an API should use the same error format. A uniform structure makes client implementation and error handling simpler. Inconsistencies breed special-case code and increase the risk of bugs.

Practical Example

A client sends a request to create an order with invalid data:

POST /api/v1/orders
Content-Type: application/json

{
  "customerId": 123,
  "items": [
    { "productId": 42, "quantity": 0 }
  ]
}

The API responds with 422 Unprocessable Content and a Problem Detail:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
X-Request-ID: a1b2c3d4-e5f6-7890-abcd-ef1234567890

{
  "type": "https://api.shop.de/problems/validation-error",
  "title": "Validation Error",
  "status": 422,
  "detail": "The order contains invalid data.",
  "instance": "/api/v1/orders",
  "errors": [
    {
      "field": "items[0].quantity",
      "code": "QUANTITY_TOO_LOW",
      "message": "Quantity must be at least 1."
    }
  ]
}

The client immediately sees which field is wrong and why. The X-Request-ID helps support find the error in logs. The error format is consistent and machine-readable.

FAQ: REST API Error Handling

1. What is a Problem Detail per RFC 7807?

A Problem Detail is a standardized error format containing fields like type, title, status, detail, and instance. It lets clients process and display errors uniformly.

2. Why should APIs use uniform error formats?

Uniform error formats simplify client implementation and reduce error-handling overhead. Developers know which fields to expect, regardless of the endpoint.

3. What should an error response contain?

A good error response includes the HTTP status code, an error description, an error ID, the affected endpoint, and for validation errors, the specific fields with messages.

4. What’s the difference between 400 and 422?

400 Bad Request is used when the request is syntactically invalid or the server cannot parse it. 422 Unprocessable Content means the request is syntactically correct but cannot be processed semantically.

5. When do you use 401 vs. 403?

401 Unauthorized indicates missing or invalid authentication. 403 Forbidden indicates the authenticated user lacks permission to access the resource.

6. What is 409 Conflict?

409 Conflict signals a conflict—for instance, concurrent edits to the same resource or a business rule violation. It’s more precise than 400 Bad Request.

7. Should you send stack traces in error responses?

No. Stack traces and internal paths should never appear in API responses. They can expose security-sensitive information and belong only in internal logs.

8. What is a correlation ID?

A correlation ID is a unique identifier that lets you track a request across multiple systems. Often sent as the X-Request-ID or X-Correlation-ID header, it helps with debugging.

9. What’s the advantage of application-specific error codes?

Application-specific codes like ORDER_NOT_FOUND or PAYMENT_DECLINED are more precise than generic HTTP status codes. They let clients respond to specific situations.

10. What is 429 Too Many Requests?

429 Too Many Requests indicates the client has sent too many requests in a given timeframe. The server can use Retry-After to tell the client when to retry.

11. How do you handle server-side errors?

Server-side errors are signaled with 5xx status codes. Clients should receive generic messages while details are logged internally. Monitoring systems trigger alerts.

12. What is the Retry-After header?

The Retry-After header tells the client how long to wait before retrying. It’s typically used with 429 or 503 and can contain a number of seconds or a timestamp.

13. Should error messages be localized?

Yes, error messages can be localized when clients declare their language via Accept-Language. The server responds with appropriate translations if available.

14. What’s the difference between title and detail?

title is a short, human-readable summary of the error type. detail describes the specific error in context. For example, title might be “Validation Error” and detail “Quantity must be at least 1.”

15. How do you test API error cases?

API error cases are tested with negative tests, contract tests, and schema validation. Simulate invalid inputs, missing authentication, conflicts, and overload, then verify the expected status codes and error formats.

Continuing your API learning path toward versioning

The next article in our API learning path covers API Versioning — strategies for REST, GraphQL, and gRPC, plus approaches to migrating between API versions.

References

  1. https://www.rfc-editor.org/rfc/rfc7807
  2. https://www.rfc-editor.org/rfc/rfc9110
  3. https://opensource.zalando.com/restful-api-guidelines/index.html

If you’d like to deepen your knowledge of API error handling, API design, and software architecture, consider these titles:

API Development

Books about API design, REST, GraphQL, OpenAPI and API architecture

Designing Data-Intensive Applications von Martin Kleppmann

Designing Data-Intensive Applications von Martin Kleppmann

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

API Design Patterns von JJ Geewax

API Design Patterns von JJ Geewax

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

Back to Blog
Share:

Related Posts