<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Pedro Felix</title>
    <description>The latest articles on DEV Community by Pedro Felix (@pmhsfelix).</description>
    <link>https://dev.to/pmhsfelix</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F454757%2Ffade2061-fba1-47fb-881a-7a2c10a5fe77.png</url>
      <title>DEV Community: Pedro Felix</title>
      <link>https://dev.to/pmhsfelix</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/pmhsfelix"/>
    <language>en</language>
    <item>
      <title>Should I PUT or should I POST</title>
      <dc:creator>Pedro Felix</dc:creator>
      <pubDate>Wed, 30 Sep 2020 17:57:31 +0000</pubDate>
      <link>https://dev.to/pmhsfelix/should-i-put-or-should-i-post-344m</link>
      <guid>https://dev.to/pmhsfelix/should-i-put-or-should-i-post-344m</guid>
      <description>&lt;p&gt;Selecting the proper methods (e.g. GET, POST, PUT, ...) to use when designing HTTP based APIS is typically a subject of much debate, and eventually some bike-shedding. In this note I briefly present the rules that I normally follow when faced with this design task.&lt;/p&gt;

&lt;h1&gt;
  
  
  Don't go against the HTTP specification
&lt;/h1&gt;

&lt;p&gt;First and foremost, make sure the properties of the chosen methods aren't violated on the scenario under analysis. &lt;br&gt;
The typical offender is using &lt;code&gt;GET&lt;/code&gt; for an interaction that requests a state change on the server.&lt;br&gt;
Why is this bad, you may ask. Because GET is defined to have the safe property, defined as&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Request methods are considered "safe" if their defined semantics are essentially read-only; i.e., the client does not request, and does not expect, any state change on the origin server as a result of applying a safe method to a target resource.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Another example is choosing `PUT for requests that aren't idempotent, such as appending an item to a collection.&lt;br&gt;
The idempotent property is defined by &lt;a href="https://tools.ietf.org/html/rfc7231"&gt;RFC 7231&lt;/a&gt; as&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Breaking these properties is harmful because there may exist system components whose correct behavior depends on them being true. &lt;br&gt;
An example is a crawler program that freely follows all &lt;code&gt;GET&lt;/code&gt; links in a document, assuming that no state change will be performed by these requests, and that ends up changing the system state.&lt;/p&gt;

&lt;p&gt;Another example is an intermediary (e.g. reverse proxy) that automatically retries any failed &lt;code&gt;PUT&lt;/code&gt; request (e.g. on timeout), assuming they are idempotent. If the &lt;code&gt;PUT&lt;/code&gt; is appending items to a collection (append is not idempotent), and the first &lt;code&gt;PUT&lt;/code&gt; request was successfully performed and only the response message was lost, then the retry will end up adding two replicated items to the collection.&lt;/p&gt;

&lt;p&gt;This violation can also have security implications. For instance, most server frameworks don't protect GET requests agains CSRF (Cross-Site Request Forgery) attacks because the GET method is not supposed to change state and reads are already protected by the same-origin browser policy.&lt;/p&gt;

&lt;h1&gt;
  
  
  Take advantage of the method properties
&lt;/h1&gt;

&lt;p&gt;After ensuring the correctness concerns, i.e., ensuring requests don't violate any property of chosen methods, we can revert our analysis and check if there aren't any methods that best fit the intended functionality. &lt;br&gt;
After having ensured correctness, in this stage our main concern is going to be optimisation.&lt;/p&gt;

&lt;p&gt;For instance, if a request defines the complete state for a resource and is idempotent, perhaps a PUT is a better fit than a POST. &lt;br&gt;
This is not because a POST will produce incorrect behavior but because using a PUT may induce better system properties. For instance, an intermediary (e.g. reverse proxy or framework middleware) may automatically retry failed requests, and by this provide some fault recovery.&lt;/p&gt;

&lt;h1&gt;
  
  
  When nothing else fits, use POST
&lt;/h1&gt;

&lt;p&gt;Contrary to some HTTP myths, the POST is not solely intended to create resources. &lt;br&gt;
In fact, the newer &lt;a href="https://tools.ietf.org/html/rfc7231"&gt;RFC 7231&lt;/a&gt; states&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The "according to the resource's own specific semantics" effectively allows us to use POST for requests with any semantics. However the fact that it allows us doesn't mean that we always should. &lt;br&gt;
Again, if another method (e.g. &lt;code&gt;GET&lt;/code&gt; or &lt;code&gt;PUT&lt;/code&gt;) best fits the request purpose, not choosing it may mean throwing away interesting properties, such as caching or fault recovery.&lt;/p&gt;

&lt;h1&gt;
  
  
  Does my API look RESTful in this method?
&lt;/h1&gt;

&lt;p&gt;One thing that I always avoid is deciding based on the apparent "RESTfullness" of the method - For instance, an API doesn't have to use PUT to be RESTful.&lt;/p&gt;

&lt;p&gt;First and foremost we should think in terms of system properties and use HTTP accordingly. That implies:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Not violating its rules - E.g. what can go wrong if I choose PUT for this request?&lt;/li&gt;
&lt;li&gt;Taking advantage of its benefits - E.g. what do I loose if I don't choose PUT for this request?&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
    </item>
    <item>
      <title>How to fail in HTTP APIs</title>
      <dc:creator>Pedro Felix</dc:creator>
      <pubDate>Tue, 18 Aug 2020 18:50:57 +0000</pubDate>
      <link>https://dev.to/pmhsfelix/how-to-fail-in-http-apis-3jo</link>
      <guid>https://dev.to/pmhsfelix/how-to-fail-in-http-apis-3jo</guid>
      <description>&lt;p&gt;In the HTTP protocol, clients use &lt;em&gt;request messages&lt;/em&gt; to perform operations, defined by &lt;em&gt;request methods&lt;/em&gt;, on resources identified by &lt;em&gt;request URIs&lt;/em&gt;.&lt;br&gt;
However, servers aren't always able or willing to completely and successfully perform these requested operations.&lt;br&gt;
The subject of this post is to present proper ways for HTTP servers to express these non-success outcomes.&lt;/p&gt;
&lt;h1&gt;
  
  
  Status codes
&lt;/h1&gt;

&lt;p&gt;The primary way to communicate the request completion result is via the response message's status code.&lt;br&gt;
The status code is a three-digit integer divided into five classes, (list adapted from &lt;a href="https://tools.ietf.org/html/rfc7231#section-6"&gt;RFC 7231&lt;/a&gt;):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;1xx (Informational): The request was received, continuing process&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;2xx (Successful): The request was successfully received, understood, and accepted&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;3xx (Redirection): Further action needs to be taken in order to complete the request&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;4xx (Client Error): The request contains bad syntax or cannot be fulfilled&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;5xx (Server Error): The server failed to fulfill an apparently valid request&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The last two of these five classes, &lt;code&gt;4xx&lt;/code&gt; and &lt;code&gt;5xx&lt;/code&gt;, are used to represent non-success outcomes.&lt;br&gt;
The &lt;code&gt;4xx&lt;/code&gt; class is used when the request is not completely understood by the server (e.g. incorrect HTTP syntax) or fails to satisfy the server requirements for successful handling (e.g. client must be authenticated).&lt;br&gt;
These are commonly referred as client errors.&lt;/p&gt;

&lt;p&gt;On the other hand, &lt;code&gt;5xx&lt;/code&gt; codes should be strictly reserved for server errors, i.e., situations where the request is not successfully completed due to a abnormal behavior on the server.&lt;/p&gt;

&lt;p&gt;Here are some of basic rules that I tend to use when choosing status codes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Never use a &lt;code&gt;2xx&lt;/code&gt; to represent a non-success outcome.&lt;br&gt;
Namely, always use a &lt;code&gt;4xx&lt;/code&gt; or &lt;code&gt;5xx&lt;/code&gt; to represent those situations, except when the request can be completed by taking further actions, in which a &lt;code&gt;3xx&lt;/code&gt; could be used.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Reserve the &lt;code&gt;5xx&lt;/code&gt; status code for errors where the fault is indeed on the server side.&lt;br&gt;
Examples are infrastructural problems, such as the inability to connect to external systems, such as a database or service, or programming errors such as an indexation out of bounds or a null dereference.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inability to successfully fulfill a request due to malformed or invalid information in the request must instead be signaled with &lt;code&gt;4xx&lt;/code&gt; status codes.&lt;br&gt;
Some examples are: the request URI does not match any known resource; the request body uses an unsupported format; the request body has invalid information.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;As a rule of thumb, and perhaps a little hyperbolically, if an error does not require waking up someone in the middle of night then probably it shouldn't be signaled using a 5xx class code, because it does not signals a server malfunction.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The HTTP specification also defines a set of 41 concrete status codes and associated semantics, from which 19 belong to the &lt;code&gt;4xx&lt;/code&gt; class and 6 belong to the &lt;code&gt;5xx&lt;/code&gt; class.&lt;br&gt;
These standard codes are a valuable resource for the Web API designer, which should simultaneously respect and take advantage of this semantic richness when designing the API responses.&lt;br&gt;
Here are some rule of thumb:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Use &lt;code&gt;500&lt;/code&gt; for server unexpected errors, reserving &lt;code&gt;503&lt;/code&gt; for planned service unavailability.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Reserve the &lt;code&gt;502&lt;/code&gt; and &lt;code&gt;504&lt;/code&gt; codes for reverse proxies.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A failure when contacting an internal third-party system should still use a &lt;code&gt;500&lt;/code&gt; when this internal system is not visible to the client.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use &lt;code&gt;401&lt;/code&gt; when the request has invalid or missing authentication/authorization information required to perform the operation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If this authentication/authorization information is valid but the operation is still not allowed, then use &lt;code&gt;403&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use &lt;code&gt;404&lt;/code&gt; when the resource identified by the request URI does not exist or the server does not want to reveal its existence. For resources represented as lists, an empty list should use &lt;code&gt;200&lt;/code&gt; and not &lt;code&gt;404&lt;/code&gt;, since the resource does exist.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use &lt;code&gt;400&lt;/code&gt; if parts of the request are not valid, such as fields in the request body.&lt;br&gt;
For invalid query string parameters I tend to use &lt;code&gt;404&lt;/code&gt; since the query string is an integral part of the URI, however using &lt;code&gt;400&lt;/code&gt; is also acceptable.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;HTTP status codes are extensible, meaning that other specifications, such as WebDav can define additional values.&lt;br&gt;
The complete list of codes is maintained by IANA at the &lt;a href="https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml"&gt;Hypertext Transfer Protocol (HTTP) Status Code Registry&lt;/a&gt;.&lt;br&gt;
This extensibility means that HTTP clients and intermediaries are not obliged to understand all status codes.&lt;br&gt;
However, they must understand each code class semantics.&lt;br&gt;
For instance, if a client receives the (not yet defined) 499 status code, then it should treat it as a 400 and not as a 200 or a 500.&lt;/p&gt;

&lt;p&gt;Despite its richness, there aren't HTTP status code for all possible failure scenarios.&lt;br&gt;
Namely, by being uniform, these status code don't have any domain-specific semantics.&lt;br&gt;
However, there are scenarios where the server needs to provide the client with a more detailed error cause, namely using domain-specific information.&lt;/p&gt;

&lt;p&gt;Two common anti-patterns are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Redefining the meaning of standard code for a particular set of resources.&lt;br&gt;
This solution breaks the uniform interface contract: the semantics of the status code should be the same independently of the request's target resource.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using an unassigned status code in the 4xx or 5xx classes.&lt;br&gt;
Unless this is done via a proper registration of the new status code in IANA, this decision will hinder evolution and most probably will collide with future extensions to the HTTP protocol.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h1&gt;
  
  
  Error representations
&lt;/h1&gt;

&lt;p&gt;Instead of fiddling with status codes, a better solution is to use the response payload to provide a complementary representation of the error cause.&lt;br&gt;
And yes, a response message may (and probably should) contain a body even when it represents an error outcome - response bodies are not exclusive of successful responses.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://tools.ietf.org/html/rfc7807"&gt;RFC 7807 - Problem Details for HTTP APIs&lt;/a&gt; is an IETF specification defining JSON and XML formats to represent such error information.&lt;br&gt;
The following excerpt, taken from the specification document, exemplifies how further information can be conveyed on a response with 403 (Forbidden) status code, stating the domain specific reason for the request prohibition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HTTP/1.1 403 Forbidden
Content-Type: application/problem+json
Content-Language: en

{
    "type": "https://example.com/probs/out-of-credit",
    "title": "You do not have enough credit.",
    "detail": "Your current balance is 30, but that costs 50.",
    "instance": "/account/12345/msgs/abc",
    "balance": 30,
    "accounts": ["/account/12345","/account/67890"]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;br&gt;
`&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;application/problem+json&lt;/code&gt; media type informs the receiver that the payload is using this format and should be processed according to its rules.&lt;br&gt;
The payload is comprised by a JSON object containing both fields defined by the specification and fields that are kept domain specific.&lt;br&gt;
The &lt;code&gt;type&lt;/code&gt;, &lt;code&gt;title&lt;/code&gt;, &lt;code&gt;detail&lt;/code&gt; and &lt;code&gt;instance&lt;/code&gt; are of the first type, having their semantics defined by the specification&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;type&lt;/code&gt; - URI identifier defining the domain-specific error type. If it is URL, then its dereference &lt;em&gt;can&lt;/em&gt; provide further information on the error type.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;title&lt;/code&gt; - Human-readable description of the error type.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;detail&lt;/code&gt; - Human-readable description of this specific error occurrence.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;instance&lt;/code&gt; - URI identifier for this specific error occurrence.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On the other hand, the &lt;code&gt;balance&lt;/code&gt; and &lt;code&gt;accounts&lt;/code&gt; fields are domain specific extensions and their semantics is scoped to the &lt;code&gt;type&lt;/code&gt; identifier.&lt;br&gt;
This allows the same extensions to be used by different HTTPs APIS with different semantics as long as the used &lt;code&gt;type&lt;/code&gt; identifiers are different.&lt;br&gt;
I recommend an HTTP API to have a central place documenting all &lt;code&gt;type&lt;/code&gt; values as well as the domain specific fields associated to each one of these values.&lt;/p&gt;

&lt;p&gt;Using this format presents several advantages when compared with constantly "reinventing the wheel" with ad-hoc formats:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Taking advantage of rich and well defined semantics for the specification defined fields - &lt;code&gt;type&lt;/code&gt;, &lt;code&gt;title&lt;/code&gt;, &lt;code&gt;detail&lt;/code&gt; and &lt;code&gt;instance&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Making the non-success responses easier to understand and handle, namely for developers that are familiar with this common format.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Being able to use common libraries to produce and consume this format.&lt;br&gt;
When using a response payload to represent the error details one might wonder if there is still a need to use proper &lt;code&gt;4xx&lt;/code&gt; or &lt;code&gt;5xx&lt;/code&gt; class codes to represents error.&lt;br&gt;
Namely, can't we just use &lt;code&gt;200&lt;/code&gt; for every response, independently of the outcome and have the client use the payload to distinguish them?&lt;br&gt;
My answer is an emphatic &lt;strong&gt;no&lt;/strong&gt;: using &lt;code&gt;2xx&lt;/code&gt; status to represent non-success breaks the HTTP contract, which can have consequences on the behavior of intermediary components.&lt;br&gt;
For instance, a cache will happily cache a &lt;code&gt;200&lt;/code&gt; response even it's payload is in the &lt;code&gt;application/problem+json&lt;/code&gt; format.&lt;br&gt;
Notice that the operation of most intermediaries is independent of the messages payload.&lt;br&gt;
And yes, HTTP intermediaries are still relevant on an HTTPS world: intermediaries can live before (e.g. client caching) and after (e.g. output caching) the TLS connection endpoints.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The HTTP protocol and associated ecosystem provides richer ways to express non-success outcomes, via response status codes and error representations.&lt;br&gt;
Taking advantage of those is harnessing the power of the Web for HTTP APIs.&lt;/p&gt;

&lt;h1&gt;
  
  
  Additional Resources
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.mnot.net/blog/2013/05/15/http_problem"&gt;Indicating Problems in HTTP APIs&lt;/a&gt; - a post by Mark Nottingham, co-author of &lt;a href="https://tools.ietf.org/html/rfc7807"&gt;RFC 7807 - Problem Details for HTTP APIs&lt;/a&gt;, introducing this specification.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://vimeo.com/131632607"&gt;Succeeding in Failing&lt;/a&gt; - a video by Darrel Miller, presented at NDC Oslo 2015.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>http</category>
      <category>api</category>
    </item>
  </channel>
</rss>
