Physical Address
Sagipora Sopore Baramulla 193201 Jammu & Kashmir
Hello guys, hope you’ll be doing well. Today we are going to learn what are Fetch API and axios in javascript with real world examples. So let’s first understand what is an API.
API stands for Application Programming Interface. It helps one application interact and share data with another application.
Now that we know what an API is, here are the things we need to know before moving forward.
Also Read: JavaScript Higher Order Functions Simplified – map(), reduce() and filter()
Now let’s move to the main topic and see what are Fetch API and Axios in javascript in simple terms.
Fetch is a promise based JavaScript API for making asynchronous HTTP requests.
is a simple, powerful and flexible way to get or send data from/to a server.
Even if the name implies that you can only “fetch” data, you can actually make any type of request: GET, POST, PUT, PATCH, DELETE.
Each fetch call returns a promise. This allows you to easily handle the data that you receive and the errors you might get.
To make a request we use the fetch() method. It takes one mandatory argument, the path of the resource we want to fetch, usually an URL.
let’s say we need to get a list of users from the server:
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err))
We call fetch() and give it a request URL as its parameter. Since we know that fetch will return a promise, we use .then() to access the server’s response. The response object returned on line 2 contains all of the response’s data, including headers, status code, status message.
Since we know that we’re expecting a JSON response, we can call the .json() method to be able to access the actual data in the chained .then() call.
We can also use a .catch() block to handle possible errors thrown by the server.
Also Read: Latest JavaScript Features Every Web Developer Should Know
Not all calls will return JSON responses, so it’s useful to be aware that the response object returned by fetch has multiple methods you can use:
// creates a clone of the response
response.clone()
// creates a new response with a different URL
response.redirect()
// returns a promise that resolves with an ArrayBuffer
response.arrayBuffer()
// returns a promise that resolves with a form data object
response.formData()
// returns a promise that resolves with a blob
response.blob()
//returns a promise that resolves with a string
response.text()
//returns a promise that resolves with JSON
response.json()
Besides the methods we use to manipulate the data in our response, we also have access to some other fields that might hold useful information:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
// accessing response headers
console.log(response.headers.get('Clcontent-type'))
// the HTTP response status code
console.log(response.status)
// true if status code is returned 200 and 299
console.log(response.ok)
// status message of the response e.g. 'Not Found'
console.log(response.statusText)
// true if there was a redirect
console.log(response.redirect)
// the response type (e.g. 'basic', 'cors')
console.log(response.type)
// the full url of the request
console.log(response.url)
})
You can make POST, PUT or PATCH requests using fetch by adding a second parameter, an object that will contain the necessary details. Here’s how:
const user = {
username: 'Nasyx.Rakeeb',
password: 'dontknow'
}
const requestData = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
fetch('http://localhost:8000/users', requestData)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error('could not save'))
Done 👏🥳 You’ve just made a HTTP POST request to the server using fetch!
You can also delete resources with fetch by using DELETE as the method, like so:
const requestData = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
}
fetch('http://localhost:8000/users/6', requestData)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log('Could not delete'))
Here we add the user’s ID in the URL so that the server knows which user we want to delete and make the request.
Now you’re more than ready to work with the APIs using JavaScript fetch.
Also Read: Best VSCode Extensions you should consider in 2022
Axios is a promise-based HTTP client that works both in the browser and in a NodeJS environment.
Add the following CDN script link to your index.html
To perform a request with axios here’s what we do.
We will send a request to the https://icanhazdadjoke.com/ API. It takes two headers Content-Type and Accept.
Let’s see how we can pass query string using axios to APIs
For this example we’ll use the Agify APIs https://api.agify.io/ endpoint
Here we’ll pass on a name as a query, to predict their age.
Let’s get to it
axios.get('https://api.agify.io/', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
params": {name: 'Nasyx'}
})
.then(res => console.log(res.data))
.catch(err => console.log(err)
Also Read: What is Call Stack In Javascript And Why Its Important
Here we will see how we can pass a POST request with Axios along a body. we will use the https://reqres.in/ API
axios.post('https://reqres.in/api/users',
{
"name": "Nasyx",
"job": "developer"
}
)
.then(res => console.log(res.data))
.catch(err => console.log(err))
Now let’s see how we can pass a PATCH request with Axios along with a body. We will use the https://reqres.in/ API
axios.patch('https://reqres.in/api/users/2',
{
"name": "Nasyx",
"job": developer"
}
)
.then(res => console.log(res.data))
.catch(err => console.log(err))
Now let’s see how to pass a PUT request with Axios along with a body. Here we will use the https://reqres.in/ same previous API
axios.put('https://reqres.in/api/users/2',
{
"name": "Nasyx",
"job": "developer"
}
)
.then(res => console.log(res.data))
.catch(err => console.log(err))
Here we’ll see how to make DELETE request with Axios along with a body.
We will be using the same API https://reqres.in/
axios.delete('https://reqres.in/api/users/2')
.then(res => console.log(res))
.catch(err => console.log(err))
Thats it for this post guys, i tried to explain fetch api and axios in javascript in simple words so that a beginner could also understand this article. Hope you learned something new from here today, if so don’t forget to share and if you have any doubt c veryomment section is open below.
Want more content like this click here
Related Links
[…] Related: Fetch API and AXIOS in JavaScript […]
[…] Fetch API and AXIOS in JavaScript March 21, 2022 […]