For many of us, when we consume an API in our application, we tend to go with something similar to writing functions that encompass the happy path, such as:

// Fetch some remote contents function getIp () { return json_decode ( file_get_contents ( 'http://httpbin.org/ip' ) ) ; }

function getIp () { return fetch ( 'http://httpbin.org/ip' ) .then ( res => res.json () ) }

;; Fetch some remote contents ( require ' [ cheshire.core :as json ] ) ( defn get-ip [] ( -> ( slurp "http://httpbin.org/ip" ) json /parse-string ) )

However, that leaves a lot to be desired - in fact, if that's all you wish to do in your software when consuming a resource you don't control, you may as well stop now and just call 'curl | jq .' in a bash script (not that there's anything wrong with that - it has it's place, but usually not as a deeper part of a larger system).

There are many things that could go wrong:

Remote sends back a 2xx message in an unanticipated format

Remote never responds (or it exceeds some acceptable timeout)

Remote sends back a non-2xx message

As such, it's our duty to ensure that we handle all possible paths, not just how the API performed on a good day of testing (afterall, if you were writing in a language with manual memory allocation, you wouldn't tend to malloc without confirming you claimed the memory you asked for, before proceeding - would you?).

What you may notice is that in some teams, the prioritization of "handled errors" tends to work in the opposite order that bullet list read (a team may handle non 2xx status codes if you're lucky - if you're very lucky, they may even handle consideration for timeouts - if you're close to a lotto winner, they also actually verify the format of the remote response!).

However - if you work in the opposite order (strong assertions on schema / properties / keys for your "good" responses) you can end up with most of the third item (non 2xx) taken care of for you for free (if the remote gives data in an unacceptable format, you immediately know at the least to trigger the error conditions showing the data is in a bad state).