1. Overview
REST is a stateless architecture in which clients can access and manipulate resources on a server. Generally, REST services utilize HTTP to advertise a set of resources that they manage and provide an API that allows clients to obtain or alter the state of these resources.
In this tutorial, we’ll learn about some of the best practices for handling REST API errors, including useful approaches for providing users with relevant information, examples from large-scale websites and a concrete implementation using an example Spring REST application.
2. HTTP Status Codes
When a client makes a request to an HTTP server — and the server successfully receives the request — the server must notify the client if the request was successfully handled or not.
HTTP accomplishes this with five categories of status codes:
- 100-level (Informational) – server acknowledges a request
- 200-level (Success) – server completed the request as expected
- 300-level (Redirection) – client needs to perform further actions to complete the request
- 400-level (Client error) – client sent an invalid request
- 500-level (Server error) – server failed to fulfill a valid request due to an error with server
Based on the response code, a client can surmise the result of a particular request.
3. Handling Errors
The first step in handling errors is to provide a client with a proper status code. Additionally, we may need to provide more information in the response body.
3.1. Basic Responses
The simplest way we handle errors is to respond with an appropriate status code.
Here are some common response codes:
- 400 Bad Request – client sent an invalid request, such as lacking required request body or parameter
- 401 Unauthorized – client failed to authenticate with the server
- 403 Forbidden – client authenticated but does not have permission to access the requested resource
- 404 Not Found – the requested resource does not exist
- 412 Precondition Failed – one or more conditions in the request header fields evaluated to false
- 500 Internal Server Error – a generic error occurred on the server
- 503 Service Unavailable – the requested service is not available
While basic, these codes allow a client to understand the broad nature of the error that occurred. We know that if we receive a 403 error, for example, we lack permissions to access the resource we requested. In many cases, though, we need to provide supplemental details in our responses.
500 errors signal that some issues or exceptions occurred on the server while handling a request. Generally, this internal error is not our client’s business.
Therefore, to minimize these kinds of responses to the client, we should diligently attempt to handle or catch internal errors and respond with other appropriate status codes wherever possible.
For example, if an exception occurs because a requested resource doesn’t exist, we should expose this as a 404 rather than a 500 error.
This is not to say that 500 should never be returned, only that it should be used for unexpected conditions — such as a service outage — that prevent the server from carrying out the request.
3.2. Default Spring Error Responses
These principles are so ubiquitous that Spring has codified them in its default error handling mechanism.
To demonstrate, suppose we have a simple Spring REST application that manages books, with an endpoint to retrieve a book by its ID:
curl -X GET -H "Accept: application/json" http://localhost:8082/spring-rest/api/book/1
If there is no book with an ID of 1, we expect that our controller will throw a BookNotFoundException.
Performing a GET on this endpoint, we see that this exception was thrown, and this is the response body:
{
"timestamp":"2019-09-16T22:14:45.624+0000",
"status":500,
"error":"Internal Server Error",
"message":"No message available",
"path":"/api/book/1"
}
Note that this default error handler includes a timestamp of when the error occurred, the HTTP status code, a title (the error field), a message if messages are enabled in the default error (and is blank by default), and the URL path where the error occurred.
These fields provide a client or developer with information to help troubleshoot the problem and also constitute a few of the fields that make up standard error handling mechanisms.
Also note that Spring automatically returns an HTTP status code of 500 when our BookNotFoundException is thrown. Although some APIs will return a 500 status code or other generic ones, as we will see with the Facebook and Twitter APIs, for all errors for the sake of simplicity, it is best to use the most specific error code when possible.
In our example, we can add a @ControllerAdvice so that when a BookNotFoundException is thrown, our API gives back a status of 404 to denote Not Found instead of 500 Internal Server Error.
3.3. More Detailed Responses
As seen in the above Spring example, sometimes a status code is not enough to show the specifics of the error. When needed, we can use the body of the response to provide the client with additional information.
When providing detailed responses, we should include:
- Error – a unique identifier for the error
- Message – a brief human-readable message
- Detail – a lengthier explanation of the error
For example, if a client sends a request with incorrect credentials, we can send a 401 response with this body:
{
"error": "auth-0001",
"message": "Incorrect username and password",
"detail": "Ensure that the username and password included in the request are correct"
}
The error field should not match the response code. Instead, it should be an error code unique to our application. Generally, there is no convention for the error field, expect that it be unique.
Usually, this field contains only alphanumerics and connecting characters, such as dashes or underscores. For example, 0001, auth-0001 and incorrect-user-pass are canonical examples of error codes.
The message portion of the body is usually considered presentable on user interfaces. Therefore, we should translate this title if we support internationalization. So if a client sends a request with an Accept-Language header corresponding to French, the title value should be translated to French.
The detail portion is intended for use by developers of clients and not the end user, so the translation is not necessary.
Additionally, we could also provide a URL — such as the help field — that clients can follow to discover more information:
{
"error": "auth-0001",
"message": "Incorrect username and password",
"detail": "Ensure that the username and password included in the request are correct",
"help": "https://example.com/help/error/auth-0001"
}
Sometimes, we may want to report more than one error for a request.
In this case, we should return the errors in a list:
{
"errors": [
{
"error": "auth-0001",
"message": "Incorrect username and password",
"detail": "Ensure that the username and password included in the request are correct",
"help": "https://example.com/help/error/auth-0001"
},
...
]
}
And when a single error occurs, we respond with a list containing one element.
Note that responding with multiple errors may be too complicated for simple applications. In many cases, responding with the first or most significant error is sufficient.
3.4. Standardized Response Bodies
While most REST APIs follow similar conventions, specifics usually vary, including the names of fields and the information included in the response body. These differences make it difficult for libraries and frameworks to handle errors uniformly.
In an effort to standardize REST API error handling, the IETF devised RFC 7807, which creates a generalized error-handling schema.
This schema is composed of five parts:
- type – a URI identifier that categorizes the error
- title – a brief, human-readable message about the error
- status – the HTTP response code (optional)
- detail – a human-readable explanation of the error
- instance – a URI that identifies the specific occurrence of the error
Instead of using our custom error response body, we can convert our body:
{
"type": "/errors/incorrect-user-pass",
"title": "Incorrect username or password.",
"status": 401,
"detail": "Authentication failed due to incorrect username or password.",
"instance": "/login/log/abc123"
}
Note that the type field categorizes the type of error, while instance identifies a specific occurrence of the error in a similar fashion to classes and objects, respectively.
By using URIs, clients can follow these paths to find more information about the error in the same way that HATEOAS links can be used to navigate a REST API.
Adhering to RFC 7807 is optional, but it is advantageous if uniformity is desired.
4. Examples
The above practices are common throughout some of the most popular REST APIs. While the specific names of fields or formats may vary between sites, the general patterns are nearly universal.
4.1. Twitter
Let’s send a GET request without supplying the required authentication data:
curl -X GET https://api.twitter.com/1.1/statuses/update.json?include_entities=true
The Twitter API responds with an error with this body:
{
"errors": [
{
"code":215,
"message":"Bad Authentication data."
}
]
}
This response includes a list containing a single error, with its error code and message. In Twitter’s case, no detailed message is present, and a general error — rather than a more specific 401 error — is used to denote that authentication failed.
Sometimes a more general status code is easier to implement, as we’ll see in our Spring example below. It allows developers to catch groups of exceptions and not differentiate the status code that should be returned. When possible, though, the most specific status code should be used.
4.2. Facebook
Similar to Twitter, Facebook’s Graph REST API also includes detailed information in its responses.
Let’s perform a POST request to authenticate with the Facebook Graph API:
curl -X GET https://graph.facebook.com/oauth/access_token?client_id=foo&client_secret=bar&grant_type=baz
We receive this error:
{
"error": {
"message": "Missing redirect_uri parameter.",
"type": "OAuthException",
"code": 191,
"fbtrace_id": "AWswcVwbcqfgrSgjG80MtqJ"
}
}
Like Twitter, Facebook also uses a generic error — rather than a more specific 400-level error — to denote a failure. In addition to a message and numeric code, Facebook also includes a type field that categorizes the error and a trace ID (fbtrace_id) that acts as an internal support identifier.
5. Conclusion
In this article, we examined some of the best practices of REST API error handling:
- Providing specific status codes
- Including additional information in response bodies
- Handling exceptions in a uniform manner
While the details of error handling will vary by application, these general principles apply to nearly all REST APIs and should be adhered to when possible.
Not only does this allow clients to handle errors in a consistent manner, but it also simplifies the code we create when implementing a REST API.
The code referenced in this article is available over on GitHub.