DEV Community

Luis A.
Luis A.

Posted on

Fetch This! How to Make API Calls So Dope, Even Your Dog Will Be Impressed πŸΆπŸš€

What's up, code wranglers? 🀠 Get ready for some paws-itively mind-blowing JavaScript knowledge! 🐾 Today, we're diving into the fetch() method, a super cool way to make API calls that'll leave your doggo howling with envy. πŸΆπŸš€ So, buckle up, and let's fetch ourselves some awesome API skills!

In my pervious post, we explored the wild world of JavaScript Promises. Now, we're gonna put those Promises to work, using the fetch() method. By the end of this article, you'll be making API calls so slick, even your four-legged friend will be impressed! πŸ•πŸ’¨ So, let's get our paws dirty and dig in! 🦴

What's fetch()? πŸ€”

The window.fetch() method is a rad way to make Ajax requests, like calling an API or snagging a remote resource or HTML file from a server. Pretty dope, huh?

For this lesson, we'll be using JSON Placeholder to make some real API requests. 😎

Let's say you wanted to get a list of posts from the API using the https://jsonplaceholder.typicode.com/posts endpoint. First, you'd pass that into the fetch() method as an argument.


fetch('https://jsonplaceholder.typicode.com/posts');
Enter fullscreen mode Exit fullscreen mode

The fetch() method gives us back a Promise. We can deal with API responses by chaining Promise.then() and Promise.catch() methods to it. Let's pass the response object into our Promise.then() callback function, and log it to the console.

fetch('https://jsonplaceholder.typicode.com/posts').then(function (response) {
    // The API call was successful!
    console.log(response);
}).catch(function (error) {
    // There was an error
    console.warn(error);
});
Enter fullscreen mode Exit fullscreen mode

If you peep at the response in the console, you'll see that the response.body ain't usable text or JSON. It's something called a ReadableStream. The fetch() method is all about those streams.

To get our API data as text or a JSON object, we can use one of two methods native to the Fetch object: Body.text() and Body.json(). The Body.text() method gets the body data as a text string, while the Body.json() method gets it as a JSON object. Both return a Promise. Noice! 😎

In most cases, you'll probs want JSON data. Call the method on the response object, and return. We can then work with the actual response JSON in a chained Promise.then() method.

fetch('https://jsonplaceholder.typicode.com/posts').then(function (response) {
    // The API call was successful!
    return response.json();
}).then(function (data) {
    // This is the JSON from our response
    console.log(data);
}).catch(function (error) {
    // There was an error
    console.warn(error);
});
Enter fullscreen mode Exit fullscreen mode

Catching errors with the Fetch API 🎣πŸ’₯

Since it returns a Promise, the Fetch API deals with errors using the Promise.catch() method.

However, the Promise only goes bonkers and triggers the Promise.catch() method if the request fails to resolve. If there's a response from the server, even if it's a 404 or 500 error, the Promise.then() methods still run. Sneaky, huh? πŸ•΅οΈβ€β™€οΈ

For example, in this request below, I've goofed and misspelled /posts as /postses, causing a 404 error.

fetch('https://jsonplaceholder.typicode.com/postses').then(function (response) {
    // The API call was successful
    // (wait, it was?)
    console.log(response.status);
    return response.json();
}).then(function (data) {
    // This is the JSON from our response
    console.log(data);
}).catch(function (error) {
    // There was an error
    console.warn(error);
});

Enter fullscreen mode Exit fullscreen mode

If you try this yourself, you'll notice that an empty JSON object is logged, and our warning doesn't show in the console. πŸ˜’

The response.ok property πŸ‘Œ

The Response.ok property returns a boolean, with a value of true if the response has a status code between 200 and 299, and false if it does not.

If the response.ok property is true, we can return response.json() just like before. If not, we can throw response to trigger the Promise.catch() method.

fetch('https://jsonplaceholder.typicode.com/postses').then(function (response) {

    // If the response is successful, get the JSON
    if (response.ok) {
        return response.json();
    }

    // Otherwise, throw an error
    throw response.status;

}).then(function (data) {
    // This is the JSON from our response
    console.log(data);
}).catch(function (error) {
    // There was an error
    console.warn(error);
});
Enter fullscreen mode Exit fullscreen mode

While that triggers the Promise.catch() handler, the error parameter is the response object. Sometimes the response.status code or the response.statusText are all you need. But often, details about the error are in the response.body.

Instead of immediately running throw, you can instead return response.json() or response.text() with a chained Promise.then() function. Inside its callback function, throw the parsed JSON or text to trigger the Promise.catch() method, with the error data as the error argument.


fetch('https://jsonplaceholder.typicode.com/postses').then(function (response) {

    // If the response is successful, get the JSON
    if (response.ok) {
        return response.json();
    }

    // Otherwise, throw an error
    return response.json().then(function (json) {
        throw json;
    });

}).then(function (data) {
    // This is the JSON from our response
    console.log(data);
}).catch(function (error) {
    // There was an error
    console.warn(error);
});
Enter fullscreen mode Exit fullscreen mode

Some APIs return a simple string error message instead of an object. If that's the case, you'll get a JSON error in the console. πŸ™„

For APIs that don't return an error object, use response.text() instead of response.json().


// Otherwise, throw an error
return response.text().then(function (msg) {
    throw msg;
});

Enter fullscreen mode Exit fullscreen mode

Tomorrow, we'll look at the async and await keywords, and how they can make Promises a bit easier to work with. It'll be like a magic trick for your code! πŸ§™β€β™‚οΈ

In conclusion, the fetch() method is a super useful tool for making API calls and handling remote resources. By using Promises and chaining .then() and .catch() methods, we can handle successes and errors with style. Remember to check the response.ok property to avoid any sneaky false positives, and you'll be well on your way to mastering the JavaScript fetch method. πŸš€

That's all for today, folks! Tune in tomorrow for more JavaScript awesomeness, and keep on fetching! 🎣🀘

Top comments (0)