Have you ever seen an API in your project and wondered how you would access the data from it?
If yes, then here's where I come in. After reading this article, you will be able to obtain data through the API and believe me, You are Awesome!π
I hope you all are well, I'm Jay Khatri and let's dive into Fetch API.
Fetch API
The Fetch API is a simpler, easier-to-use version of XMLHttpRequest that consumes resources asynchronously. Fetch allows you to interact with your REST API with additional options such as caching data, reading streaming responses, and more.
In simpler terms :
The Fetch API is a Promise-based interface for retrieving resources via HTTP requests to web browser servers. This is similar to XML HTTP requests but better and more powerful.
Fetch() Method
The Fetch API includes a fetch()
the method that can be used to retrieve data from any location and manipulate the retrieved data. You can make HTTP requests. i.o Either a GET
request (to retrieve data) or a POST
request (to post data). A basic fetch request can be illustrated by the following code.
fetch('url')
.then((response) => {
// handle response
console.log(response);
})
.then((data) => {
// handle data
console.log(data)
})
.catch((error) => {
//handle error
console.log(error)
})
Promise
Let's have a look at one of the key benefits of using the Fetch API.
Each fetch()
the call will result in the return of a JavaScript Promise object, which is by default asynchronous. This means you can securely and confidently assure that your code will only run after a successful network request answer.
Assuming we are returning plain text in response to our fetch request, we can obtain the result by using .then() after the fetch:
fetch('http://example.com/data')
.then(response => response.text())
.then(text => console.log(text))
As you can see, the code is significantly easier and more concise than when using XHR. Furthermore, this is all ready to use in JavaScript without the need to load any external third-party libraries.
Response
The response returned by the.then()
the function is a JavaScript Response object. This means we can parse a JSON result straight on the Response object without first reading it.
Assume the following request is expecting a JSON response:
fetch('https://example.com/usersdata/1')
.then(response => response.json())
.then(user => console.log(user.name))
You can read additional helpful attributes in the response to determine the state of the response. Among the more typical ones are:
a) Response.ok
Return a Boolean value of true or false to indicate whether the response was successful. If a status is in the 200β299 range, it will return true; otherwise, it will return false.
b) Response.status
the response's status code specifically. Examples include 200, 404, 500, etc.
c) Response.statusText
the status code's corresponding status message. For instance, OK for an answer of 200.
Here is an illustration of how to apply them:
fetch('https://example.com/users/1')
.then(response => {
if (!response.ok && response.statusText != 'OK') {
if (response.status == 404) {
console.log('Resource not found!')
}
}
})
Error Handling
Simply add a.catch()
method to the chain to handle any connection errors:
fetch('https://invalidurl')
.then(response => response.json())
... // other .then()
.catch((error) => console.log(error))
βοΈ Fetch only returns an error if the network request fails for any reason, such as an unreachable host or a broken connection. Fetch considers a 500 status answer (or 200, 400, etc.) to indicate a successful request, and it should be handled in your response instead.
POST Request
So far, all of the samples we've seen have just been made GET
requests. Even though we did not specify any options for our fetch request, it has completed several scenarios.
To send a POST
request, we need to set a few arguments in the second parameter of our fetch()
function. Consider the following example of transmitting JSON data via POST.
fetch('https://example.com/posts', {
method: 'POST',
headers: {
'Content-type': 'application/json; charset=UTF-8'
},
body: JSON.stringify({
title: 'New Post',
content: 'Hello world!'
}),
})
.then((response) => response.json())
.then((json) => console.log(json));
Because the Content-Type header is by default set to text/plain; charset=UTF-8, you will most likely need to provide one based on the content of your request.
For example, in the case of a form data request:
fetch('https://example.com/login', {
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: 'username=admin&password=secret'
})
.then(response => response.text())
.then(text => console.log(text))
Conclusion π
I am sure now you are ready to get and post any API using fetch() API!
Certainly, there are many more elements of the Fetch API that I have yet to discuss. Hopefully, this article has shown you how strong and modern the Fetch API is when compared to XHR. π
If you want to go deeper, check out the link I've included in the Resource section below.
Thank you for reading π; if you found this post useful, please share it with your friends or connections.
Resource π
JavaScript