API responses are similar to receiving a reply from a friend when you ask a question. This reply, known as an API Response, is packed with useful information: the data you asked for, a status code (a mini report on how the request went), headers (like additional information about the data), and more.
Most often, the data returned by APIs is in a format called JSON (JavaScript Object Notation), an easy to use, neatly organized data format.
When fetching data, JavaScript's Fetch API offers a Promise. Once resolved, it provides a Response object. An example API and its response can be seen as follows:
The fetch function takes an API URL, then returns a Promise. The Promise then resolves to present a Response object, which is logged to the console.
API requests can return varying outcomes, leading to success, a resource being not found, a server error, and so on. These statuses of an API request are denoted by HTTP status codes, like a mini report card for our API request.
HTTP status codes are grouped into five classes:
- 1xx (Informational): The API received the request, and the process is continuing.
- 2xx (Successful): The request was successfully received, understood, and accepted.
- 3xx (Redirection): Extra action must be taken to complete the request
- 4xx (Client Error): The request has bad syntax or cannot be fulfilled.
- 5xx (Server Error): The server failed to complete a valid request.
We can fetch the status code of an API response like this:
With API requests, errors may occur. Just like we handle adversities in our lives, we need to handle these errors in our code. We can handle these errors in JavaScript using the try...catch statement, which is like saying, "Try this, but if there's a problem, don't panic, do this instead."
Let's see how to apply this when making API requests:
In the code above, "if the response is not Ok (meaning, if the status code does not start with 2), we throw an error which is later caught and logged.
Note that the error on line 6 refers to a situation where we intentionally throw an error if the API request is not successful. In this case, if the HTTP status code of the response is not 2xx (meaning the request is not successfully processed), we throw a new Error with a custom message API request failed with status ' + response.status. This is our way of handling unsuccessful API requests and providing a meaningful error message.
On the other hand, the error on line 8 refers to any unforeseen error that happens within the try block. This could range from network issues, coding errors, to unexpected application behaviour. The catch block catches any exception or error that occurs in the try block and executes statements within the catch block. Here we're catching that error and logging it to console. This ensures our code doesn't stop running unexpectedly, and we're informed about any errors that occur.
