Fetch This! How to Make API Calls So Dope, Even Your Dog Will Be Impressed 🐶🚀
Tags: tutorial, javascript, programming, webdev
Published: 2023-03-26 12:41:24

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! 🦴
<img width="100%" style="width:100%" src="https://media.giphy.com/media/5b5Q2LZYbPiLW74rBK/giphy.gif">

## **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?
<img width="100%" style="width:100%" src="https://media.giphy.com/media/xlYKItjhiDsY/giphy.gif">

For this lesson, we'll be using **[JSON Placeholder](https://jsonplaceholder.typicode.com/)** 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.

```jsx

fetch('https://jsonplaceholder.typicode.com/posts');
```

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.

```jsx
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);
});
```

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.

```jsx
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);
});
```

## **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.

```jsx
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);
});

```

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.

```jsx
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);
});
```

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.

```jsx

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);
});
```

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()`**.

```jsx

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

```

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! 🎣🤘
<img width="100%" style="width:100%" src="https://media.giphy.com/media/DnMMGxEvniha7CvASq/giphy.gif">