<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zhebrunov Grigorii on Medium]]></title>
        <description><![CDATA[Stories by Zhebrunov Grigorii on Medium]]></description>
        <link>https://medium.com/@gzhebrunov?source=rss-dd6d8be1ae63------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JvX9VW82y3i0YNjpoalkvA.jpeg</url>
            <title>Stories by Zhebrunov Grigorii on Medium</title>
            <link>https://medium.com/@gzhebrunov?source=rss-dd6d8be1ae63------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:33:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gzhebrunov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[REST API Error Handling]]></title>
            <link>https://medium.com/@gzhebrunov/rest-api-error-handling-9743c452f583?source=rss-dd6d8be1ae63------2</link>
            <guid isPermaLink="false">https://medium.com/p/9743c452f583</guid>
            <category><![CDATA[hateoas]]></category>
            <category><![CDATA[hal]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Zhebrunov Grigorii]]></dc:creator>
            <pubDate>Tue, 02 Jan 2018 01:09:55 GMT</pubDate>
            <atom:updated>2018-01-04T01:43:31.837Z</atom:updated>
            <content:encoded><![CDATA[<p>The bigger the application, the more errors it is bound to have. — Unknown author</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*vWng4Q_CJO9sGwUL.png" /></figure><p>In the enterprise world, an API is a bridge between systems. APIs facilitate the communication of company business processes and data with client applications and end users. In common distributed architectures, API systems communicate to each other using standard protocols and data formats. End user applications use these API services to perform their operations, effectively decoupling their application from the internal logic of the API. This decoupling means an API doesn’t know about its own consumers, a fact that produces interesting challenges for API developers. Ultimately, API developers are required to think about the many use cases for different types of systems, services, and platforms they develop for such as mobile, web, etc. APIs become the core of the distributed system and should be a comfortable experience for developers who are building end user applications on top of it.</p><p>One aspect of a well-designed API is how that service responds to errors. Regardless of the reason, an error response from an API should have enough information for the consumer of the API to understand what is going on. The API could produce a user friendly message to assist in debugging.</p><p>Lets try to design a “good” error format for a REST service.</p><p>Such as most REST services are using HTTP 1.1 as a transport layer (the most common version at the time of writing), it is also a common approach to use HTTP status codes in the response message’s header to indicate a request error or service failure. For a brief overview of HTTP/1.1 (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html), status codes are grouped by categories, with two categories related to responses with an error — 4XX and 5XX. In other words, a 4XX status code means the client did something wrong in the request, i.e. trying to access secured service without passing authentication headers (resulting in a 401), or trying to access a non-existing resource (resulting in a 404). Respectively, 5XX status codes mean the client request was ok, but something went wrong on the server. Examples of 5XX errors could be that the server lost connection (resulting in a 503), or an unexpected code exception appears (resulting in a 500).</p><p>In my practice, the most useful HTTP error codes are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*rUEEFksDzXFQxZ7WmydFDw.png" /></figure><p>API should be designed in the way that most of the requests with response error codes 5XX supposed to be retriable. It’s may be tricky or sometimes impossible for error 500.</p><p>An API should be designed in a way that most of the requests with response error codes in the 5XX category should be retriable. It may be tricky (or sometimes impossible) to retry for a 500 error. Also, as different companies use different subsets of error codes, there is no standard (except HTTP) which may say what codes should be returned for each case within an application. A basic idea, then, would be to use a subset of error codes, and keep this as small as possible while at the same time having enough codes to separate the different types of errors your API may encounter. Thus, we can imagine HTTP error codes as basic error categories.</p><p>Let see some examples. For the request:</p><blockquote><strong>GET </strong><a href="http://myapi.com/v1/employee/123%20HTTP/1.1"><strong>http://myapi.com/v1/employees/123 HTTP/1.1</strong></a></blockquote><blockquote><strong>Content-Type: application/json</strong></blockquote><p>If employee resource with identity 123 does not exists, the response can be:</p><blockquote><strong>HTTP/1.1 404 Not Found</strong></blockquote><blockquote><strong>Content-Type: application/json;charset=UTF-8</strong></blockquote><pre>{<br>     &quot;error&quot;: &quot;Employee with Id 123 was not found&quot;<br>}</pre><p>This is a server responding with an HTTP status code of 404 along with an error message serialized as JSON. Ideally, the server should not answer with plain text, XML or something other than JSON since the client requested content-type “application/json” in the request.</p><p>Error messages returned by an API service should be a readable, user friendly text with enough information to understand what is exactly happening. There are at least few things related to this message to worry about on service side:</p><p>1) Although messages should be concise and user friendly, it’s bad practice to show this error message to the end user. The client should not trust the API service and must override the error messages depending on context, possibly providing a more generic message (i.e. “Employee was not found.”). At the same time, this error should be logged in the server logs as it can be useful for service debugging purposes. This is why it’s important to provide both a user friendly and detailed message.</p><p>2) For security reasons, any piece of code or error stack should not be provided as a part of the message.</p><p>3) Error messages must follow company policies related to business and customers information distribution to the third parties (i.e. Social Security Number must not be part of this message).</p><p>The language of the message can be leveraged by the request header “Accept-Language” (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language). If this header is not provided, the header value is a wildcard (*). If the requested language is not supported then the default language must be used.</p><p>Is it enough to provide just an error message to the consumer? Well, it depends. For small services, where the consumers are only applications built inside the organization, an error message can be enough. In most cases it is not.</p><p>There are a couple of failings in this approach. First of all you miss out on a good opportunity to have some kind of message, with which a consumer will then be able to show to their end users, which could be a System Message. Another thing is, it is good to provide more technical details as to simplify debugging services. Plus, in the world of REST services and a linked web, it would be useful if a service would give some information about a resource within the web (perhaps within the URL?), another place where more information can be found.</p><p>What about a response like this:</p><blockquote><strong>HTTP/1.1 404 Not Found</strong></blockquote><blockquote><strong>Content-Type: application/json;charset=UTF-8</strong></blockquote><pre>{<br>   &quot;statusCode&quot;: &quot;404&quot;,<br>   &quot;errorCode&quot;: &quot;EeNotFound_10&quot;,<br>   &quot;message&quot;: &quot;Requested resource was not found&quot;,<br>   &quot;developerMessage&quot;: &quot;Employee with Id 123 was not found in the company 700&quot;,<br>   &quot;timestamp&quot;: &quot;Wed, 05 Jul 2017 23:16:16 GMT&quot;,<br>   &quot;moreInfo&quot;: &quot;http://documentationportal.com/api/errors?code=EmployeeNotFound_10&quot;<br>}</pre><p><strong>statusCode</strong> — In this example, statusCode is supposed to duplicate the HTTP status code. This will help to simplify life for client application developers.</p><p><strong>errorCode — </strong>This property is an alphanumeric code related to the problem. It is more specific than statusCode and also carries business meaning. The errorCode must be concise aiming to help consumers by categorizing reasons for problems. This can then be used by an API consumer’s code to generate user friendly messages.</p><p><strong>message — </strong>Continuing with the previous example, the message property is similar to errorCode, except that message can be used by a consumer application, presenting as a System Message to the end user. Consumer applications still should not trust this message as something enough for an end user.</p><p><strong>developerMessage </strong>— As the name of this property implies, developerMessage is a message that should be logged and used for debugging service behavior. It should follow the same restrictions related to acceptable text like errorCode.</p><p><strong>timestamp</strong> — Another property to include in your error response is a server timestamp in UTC timezone, which can be useful to both service and client developers for debugging issues in asynchronous scenarios.</p><p><strong>moreInfo</strong> — Reference to the documentation from which developers can find more information about the error should also be included.</p><p>Another things to keep in mind with both the message and developerMessage properties is to use the “Accept-Language” HTTP header to determine the language of the returned messages. Now, the response looks much better and has a lot of information for debugging and producing error handlers on the client side.</p><p>From the point of implementation a couple of things are still a concern — (1) some of the structured, useful information is in plain text (developerMessage), (2) the moreInfo property is a link to another resource, but this doesn’t follow the best practices of the RFC5988 (Web Linking) (<a href="https://tools.ietf.org/html/rfc5988">https://tools.ietf.org/html/rfc5988</a>).</p><p>RFC5988 specification recommends to provide the following set of the information related to the linked resource — a link to the resource (URL), a named relation of the linked resource to current resource (i.e. help), and a title (human readable label for the link destination, this attribute is optional).</p><p>Therefore, a revised JSON may looks like this:</p><pre>{<br>...<br>   &quot;moreInfo&quot;: {<br>       &quot;link&quot;: &quot;<a href="http://documentationportal.com/api/errors?code=EmployeeNotFound_10">http://documentationportal.com/api/errors?code=EmployeeNotFound_10</a>&quot;,<br>       &quot;rel&quot;: &quot;help&quot;,<br>       &quot;title&quot;: &quot;Employee Not Found&quot;   <br>   }<br>}</pre><p>This concept is very similar to the RESTful architectural style Hypermedia as the Engine of Application State (HATEOAS) and moves APIs to the 3rd level of Richardson Maturity Model (https://martinfowler.com/articles/richardsonMaturityModel.html).</p><blockquote><strong>HATEOAS</strong>, an abbreviation for <strong>Hypermedia As The Engine Of Application State</strong>, is a constraint of the REST application architecture that distinguishes it from most other network application architectures. The principle is that a client interacts with a network application entirely through hypermedia provided dynamically by application servers. A REST client would then not need any prior knowledge about how to interact with a particular application or server beyond requiring a generic understanding of hypermedia. (https://en.wikipedia.org/wiki/HATEOAS)</blockquote><p>I will skip details about what HATEOAS is and how it works, let us look how it will affect implementations of error responses.</p><p>HATEOAS has many popular implementations which are ready to use, like HAL (Hypermedia Application Language) (https://tools.ietf.org/html/draft-kelly-json-hal-08), JSON for Linked Documents (JSON-LD) (https://www.w3.org/TR/json-ld/), Collection+JSON (https://github.com/collection-json/spec) and others.</p><p>HAL looks like the simplest solution for the current problem. Technically, HAL is just a custom media type (application/hal+json or application/hal+xml) which provides a general and simple way of describing linked resources.</p><p>Using a HAL request-response would looks like:</p><blockquote><strong>GET </strong><a href="http://myapi.com/v1/employee/123%20HTTP/1.1"><strong>http://myapi.com/v1/employees/123 HTTP/1.1</strong></a></blockquote><blockquote><strong>Content-Type: application/hal+json</strong></blockquote><blockquote><strong>Accept-Language: en-US;q=1</strong></blockquote><p>Response:</p><pre>{  <br>   &quot;statusCode&quot;: &quot;404&quot;,<br>   &quot;errorCode&quot;: &quot;EeNotFound_10&quot;,<br>   &quot;message&quot;: &quot;Requested resource was not found&quot;,<br>   &quot;developerMessage&quot;: &quot;Employee with Id 123 was not found in the company 700&quot;,<br>   &quot;timestamp&quot;: &quot;Wed, 05 Jul 2017 23:16:16 GMT&quot;,<br>   &quot;_links&quot;: {<br>      &quot;self&quot;: { &quot;href&quot;: &quot;/employees/123&quot; },<br>      &quot;help&quot;: { <br>         &quot;href&quot;: &quot;<a href="http://documentationportal.com/api/errors?code=EmployeeNotFound_10">http://documentationportal.com/api/errors?code=EmployeeNotFound_10</a>&quot;, <br>         &quot;type&quot;: &quot;text/html&quot;, <br>         &quot;title&quot;: &quot;Employee Not Found&quot; <br>      }<br>   }<br>}</pre><p>In terms of HAL, relation is the name of the JSON properties under the <strong>_links</strong> property. URL is provided by <strong>href</strong> property, <strong>title </strong>is presented as well. A useful addition is the media type of the linked resource (the <strong>type</strong> property).</p><p>Ok, links look much better now, but what about developerMessage? It’s still the only way to get some additional structural information from plain text, which does not sound like a good solution for API consumers. Let us expose this information as separate objects. In HAL it would looks like this:</p><pre>{<br>   …<br>   &quot;developerMessage&quot;: &quot;Employee with Id 123 was not found in the company 700&quot;,<br>   &quot;_links&quot;: {<br>      &quot;self&quot;: { &quot;href&quot;: &quot;/employee/123&quot; },<br>         &quot;help&quot;: { <br>             &quot;href&quot;: &quot;<a href="http://documentationportal.com/api/errors?code=EmployeeNotFound_10">http://documentationportal.com/api/errors?code=EmployeeNotFound_10</a>&quot;, <br>             &quot;type&quot;: &quot;text/html&quot;, <br>             &quot;title&quot;: &quot;Employee Not Found&quot; <br>         },<br>         &quot;company&quot;: { &quot;href&quot;: &quot;/companies/700&quot; }<br>      }<br>   }<br>}</pre><p>Now we are exposing a link to the company resource where the system tried to find an employee, but from the API consumer’s perspective it’s useful to display a company name. This could be retrieved by a second request, but a round-trip to the server is not the best way for building an error message. Why not just provide this information as part HAL response?</p><pre>{<br>   &quot;statusCode&quot;: &quot;404&quot;,   <br>   &quot;errorCode&quot;: &quot;EeNotFound_10&quot;,<br>   &quot;message&quot;: &quot;Requested resource was not found&quot;,<br>   &quot;developerMessage&quot;: &quot;Employee with Id 123 was not found in the company 700&quot;,<br>   &quot;timestamp&quot;: &quot;Wed, 05 Jul 2017 23:16:16 GMT&quot;,<br>   &quot;_links&quot;: {<br>      &quot;self&quot;: { &quot;href&quot;: &quot;/employees/123&quot; },<br>         &quot;help&quot;: { <br>            &quot;href&quot;: &quot;<a href="http://documentationportal.com/api/errors?code=EmployeeNotFound_10">http://documentationportal.com/api/errors?code=EmployeeNotFound_10</a>&quot;, <br>            &quot;type&quot;: &quot;text/html&quot;, <br>            &quot;title&quot;: &quot;Employee Not Found&quot; <br>         },<br>         &quot;company&quot;: { &quot;href&quot;: &quot;/companies/700&quot; }<br>   },<br>   &quot;_embedded&quot;: {<br>      &quot;companies&quot;: [{<br>         &quot;_links&quot;: {<br>            &quot;self&quot;: { &quot;href&quot;: &quot;/companies/700&quot; }<br>         },<br>         &quot;id&quot;: 700,<br>         &quot;name&quot;: &quot;Company With No Employee&quot;<br>      }]<br>   }<br>}</pre><p>The final response is providing a lot of interesting benefits for an API consumer:</p><ul><li>HTTP status code can be accessed from the response body without the need to check the HTTP header.</li><li>Every error category has a stable error code, which can be mapped in client code to the error templates.</li><li>Response exposes a message which can be used as system error message for the end users.</li><li>For service tracing and debugging, “timestamp” and “developerMessage” objects are provided.</li><li>Response has a link to the help resource in generic way.</li><li>Response exposes links for everyone related to problem resources, plus provides quick access to a minimal subset of the fields related to those resources.</li></ul><p>As usual it’s not a trivial task to understand how much information needs to be exposed in a response. API developers have interesting challenges between integrity and performance.</p><p>HAL is just an example of building a semantic layer for API error responses, though any other HATEOAS implementation (including custom ones) can be used instead.</p><p>This blog post was made possible by the diligent work of Jeffrey Jean-Pierre. I really appreciate the contributions you made to this article.</p><p><strong>Asure Software, Inc., headquartered in Austin, Texas, offers intuitive and innovative solutions designed to help organizations of all sizes and complexities build companies of the future. Our cloud platforms enable more than 80,000 clients worldwide to better manage their people and space in a mobile, digital, multi-generational, and global workplace. Asure Software’s offerings include a fully-integrated HCM platform, flexible benefits and compliance administration, HR consulting, and time and labor management as well as a full suite of workspace management solutions for conference room scheduling, desk sharing programs, and real estate optimization.</strong></p><p><a href="http://www.asuresoftware.com/"><strong>www.asuresoftware.com</strong></a></p><p><strong>Useful links</strong></p><ul><li><a href="https://martinfowler.com/articles/richardsonMaturityModel.html">https://martinfowler.com/articles/richardsonMaturityModel.html</a></li><li><a href="https://en.wikipedia.org/wiki/HATEOAS">https://en.wikipedia.org/wiki/HATEOAS</a></li><li><a href="http://restfulapi.net/hateoas/">http://restfulapi.net/hateoas/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9743c452f583" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>