REST API Error Handling: Best Practices 
Error handling is one of the key components of REST API best practices.
Hope for the best, prepare for the worst.
In this article, we'll explore everything you need to know about handling errors in REST APIs.
Best practices of error handling in REST APIs consist of:
1. HTTP Status Codes
HTTP status codes are the most important indicator of errors in REST APIs.
Out of five categories of HTTP status codes, two are used for errors:
- 400 range: Client Errors - where something is wrong on the user's end
- 500 range: Protocol Errors - indicating issues from within in terms of fault processing.
Most common HTTP error status codes
Here is a table of the most common HTTP error codes and their explanations:
|HTTP Status Code||Explanation|
|400 Bad Request|
The request was malformed or invalid, and the server could not process it.
The request requires authentication, and the client did not provide valid credentials.
The client does not have permission to access the requested resource.
|404 Not Found||The requested resource could not be found on the server.|
|405 Method Not Allowed||The requested method is not supported by the resource.|
|429 Too Many Requests|
The client has made too many requests in a specified time period and is being rate-limited by the server.
|500 Internal Server Error|
An unexpected error occurred on the server, and it was unable to process the request.
|503 Service Unavailable|
The server is temporarily unable to handle the request due to maintenance or overloading.
Read more: HTTP Bad Request vs Not Found
HTTP error status codes tell us that the request failed, but they don't provide domain-specific details. That's why we add error codes to the response body.
2. REST API Error Codes
REST API error codes are domain-specific error identifiers that proved more detailed information about the error.
Error codes are communicated to the client in the response body along with a relevant error message.
3. REST API Error message
It's important to include the error message in the response body because it helps our API consumers understand the error context.
The error message is usually a one sentence that should tell more than what we know from the status code.
For example, returning the status code
401 Unauthorized with the error message Unauthorized request doesn't provide much information on why the request was unauthorized. A better error message could be This feature is not in your access scope.
The response body of an errored request should not contain the error stack trace.
4. Error Trace ID
An error trace ID is a unique identifier that is generated when an error occurs.
It can be used to track and trace the error throughout the system. The unique ID makes it easier for API developers to identify, diagnose, and resolve issues.
The error trace ID is typically included in the response body of an error response. It can also be logged by the API and other systems along the request-response path, providing a complete and detailed trace of the error.
Having a unique error trace ID is particularly useful in microservice architectures, where multiple services may be involved in processing a single request. The error trace ID can be used to correlate errors across multiple services and to trace the request-response path through the system.
5. Error Message Formatting
If you're using JSON, using the
application/problem+json (Problem Detail) media type is the best way to format the error response.
Using the "problem detail" response body just means putting together all the best practices we've talked about. The problem detail body must include the error:
- Type or status code - unique error identifier
- Detail - Brief error explanation.
Negative Testing REST API
Negative Testing is a REST API feature that lets API clients simulate errors.
The sandbox API defines request bodies you can use to guarantee a certain error response.
Negative Testing is crucial for developing a robust integration because it's impossible to organically test out all the error states.
HTTP Error Statuses vs Error Codes
The main difference between HTTP error status codes and error codes is that HTTP error status codes are standardized and widely recognized across the web, while error codes are specific to a particular application or service.
HTTP error status codes are three-digit codes that indicate the outcome of a request, such as success (200 OK), client error (4xx) or server error (5xx). They provide a basic level of error information and are widely understood by API clients.
Error codes, on the other hand, are custom codes that provide more detailed information about an error. They can be used to provide additional context about the error, such as indicating the specific validation error or the type of resource that caused the error. Error codes can be communicated to the client in the response body along with a relevant error message.
REST API Error Handling Best Practices Summary
- HTTP Status Codes: Use HTTP status codes to indicate errors in REST APIs.
- Error Codes: Use domain-specific error codes to provide more detailed information about the error.
- Error Messages: Include error messages in the response body to help API consumers understand the error context.
- Error Trace ID: Use a unique error trace ID to track and trace errors throughout the system.
- Error Message Format: Use the application/problem+json (Problem Detail) media type to format error responses in JSON.
FAQ: REST API Error Handling
Should the response body include the HTTP status code?
The response body should not include the HTTP status code.
Including it in the response body adds to the network payload and it is redundant.
Why is it important to use proper HTTP error status codes?
It's important to use proper HTTP error statuses because they are standardized across the web.
They are widely recognized and understood by API clients, tools, and services.
For example, Application Performance Monitoring tools (APM) automatically categorize errors based on their HTTP status codes and provide valuable insights into the performance and health of the API. If an error happens and we return the "200 OK" status, an APM wouldn't catch it.
Similarly, API gateways and load balancers can be configured to route requests based on the HTTP status code, allowing for fine-grained control over the API behavior.
Should error response include the exception message?
Based on RFC7807, error response should not include the exception message or stack trace:
Problem details are not a debugging tool for the underlying implementation; rather, they are a way to expose greater detail about the HTTP interface itself. - RFC7807
Josip Miskovic is a software developer at Americaneagle.com. Josip has 10+ years in experience in developing web applications, mobile apps, and games.Read more posts →
I've used these principles to increase my earnings by 63% in two years. So can you.
Dive into my 7 actionable steps to elevate your career.