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