Recently I’ve been working with HTTP APIs. In doing so, correctly handle errors or faulty behaviors resulting in carrying error response messages is a valuable and important aspect. To solve this challenge I strive to rely on HTTP status codes. However, sometimes they are not sufficient to communicate enough information to the clients.
In a practical example, an HTTP API returns a bad request (400) response informing the client of a malformed request. There could be many reasons for the server not to process the request due to something perceived as a client error. Maybe the request contains malformed syntax? Perhaps there is a deceptive request routing? Was the request too large? This can obviously lead to some ambiguity.
One could say, let’s add additional information to our system document responses and the clients should be able to easily understand what is the real problem with the request which originated in a given error message. This might introduce another problem; most of the HTTP API’s build this document responses differently without a standard way of specifying the errors.
Below are two examples of a bad request from the HTTP APIs of Strava and Stack Exchange:
You will notice that most of the response error structures are very different from each other when describing similar errors.
RFC 7807
The Internet Engineering Task Force published RFC 7807 to mitigate this type of problem.
This document defines a “problem detail” as a way to carry machine-readable details of errors in a HTTP response to avoid the need to define new error response formats for HTTP APIs.
Problem details object
The problem details object suports this standard and is a simple data model with the following members:
- Type (string): A URI reference that identifies the problem type.
- Title (string): A short human-readable summary about the problem.
- Detail (string): A human-readable explanation about the problem.
- Status (number): HTTP Status Code generated by the origin server for this occurrence of the problem.
- Instance (string): A URI reference that identifies the specific occurrence of the problem.
This specification is supported in known formats, such as XML or JSON:
Content-Type: application/problem+xml
Content-Type: application/problem+json
It can also be easily extended, here is a JSON example below:
Microsoft implemented this specification since ASP.NET Core 2.1 with the ProblemDetails
class. While working with ASP.NET Core you can benefit from this standard. Gladly, this is also supported in many other frameworks.
Relying on this specification ensures consistent error responses returned. The clearness and flexibility provided are a great way to handle errors and failure scenarios in your HTTP APIs.