Fetch vs. Axios for making HTTP requests
What is API? Why do we need them?
API stands for “Application Programming Interface,” which is a software intermediary that allows two applications to talk to each other. APIs simplify how developers integrate new application components into existing architecture, they help business and IT teams collaborate. Business needs often change quickly in response to ever-shifting digital markets, where new competitors can change a whole industry with a new app.
CRUD Operations in API-
- Create: Inserts a new data
- Read: Read the data
- Update: Update the existing data
- Delete: Delete the existing data
List of HTTP Request methods
- POST – is used to send data to a server to create a resource.
- GET – is used to request data from a specified resource.
- PUT – is used to send data to a server to update a resource.
- DELETE – is used to delete the specified resource.
Let’s take an example of how we can use APIs.
Using Fetch –
Fetch API provides a fetch() method defined on the window object. It uses body property.
It means that you don’t need to install fetch; it comes with ES6 as a built-in functionality.
Fetch Code Example –
fetch("URL") // The fetch() method returns a Promise. After the fetch() method, include the Promise method then() // A Promise is an object representing the eventual completion or failure of an asynchronous operation // Call the fetch function passing the url of the API as a parameter .then(() => { // Your code for handling the data you get from the API }) .catch(()=> { // This is where you run code if the server returns any errors });
.then – If the Promise returned is resolved, the function within the then() method is executed. That function contains the code for handling the data received from the API.
.catch – The API you call using fetch() may be down, or other errors may occur. If this happens, the reject promise will be returned. The catch method is used to handle reject. The code within the catch() will be executed if an error occurs when calling the API of your choice.
GET Api using Fetch-
// Get the Data from the URL fetch("URL") // Transform the data into json .then((res) => res.json()) .then((data) => { console.log(data); }) .catch((error)=> { console.log(error); });
//In fetch API default is GET method.
CREATE Api using Fetch-
Method – ‘ POST ’
fetch("URL",{ // method changes method: 'POST', body: JSON.stringify({ title: 'foo', body: 'bar', userId: 0 }), headers: { "Content-type": "application/json; charset=UTF-8" } }) // Transform the data into json .then((res) => res.json()) .then((data) => { console.log(data); }) .catch((error)=> { console.log(error); });
UPDATE Api using Fetch-
Method – ‘ PUT ’
fetch("URL",{ // method changes method: 'PUT', body: JSON.stringify({ title: 'foo', body: 'bar', userId: 0 }), headers: { "Content-type": "application/json; charset=UTF-8" } }) // Transform the data into json .then((res) => res.json()) .then((data) => { console.log(data); }) .catch((error)=> { console.log(error); });
DELETE Api using Fetch-
Method – ‘ DELETE ’
fetch("URL", { method: 'DELETE' } )
Using Axios –
Axios is a stand-alone third-party package that uses data property. To use it, we need to install the axios package from npm.
$ npm i axios // This will download the axios
Axios API Code Example –
axios.get("URL") //handling the response .then(() => { // the code for handling the data you get from api }) .catch((error) => { //for handling the error thrown console.log(error); });
GET Api using Axios –
axios.get("URL") .then(res => { console.log(res.data); }) //In axios API also default is GET method
POST Api using Axios-
const employee = { name: this.state.name, age: this.state.age, salary: this.state.salary, } // method .post axios.post("URL", employee) .then(res => console.log(res.data));
UPDATE Api using Axios-
const employee = { name: this.state.name, age: this.state.age, salary: this.state.salary, } // method .put axios.put("URL", employee) .then(res => console.log(res.data));
DELETE Api using Axios-
// method .delete axios.delete("URL") .then(res => console.log(res.data));
Async-Await Syntax-
Using Async/Await, we can write asynchronous code synchronously.
The async keyword before a function has two effects:
- Make it always return a promise.
- Allows awaiting to be used in it.
The await keyword before a promise makes JavaScript wait until that promise settles, and then:
- If it’s an error, the exception is generated.
- Otherwise, it returns the result.
Code for fetch Async/await- // declare the async data fetching function const fetchData = async() => { try{ // get the data from the api const get_data = await fetch('URL'); // convert the data to json const json = await get_data.json(); } catch(error){ // make sure to catch any error console.log(error) } } // call the function fetchData()
Code for Axios Async/await- const fetchData = async() => { try{ const get_data = await axios.get("URL") //remember in axios data is pre stored in json format } catch(error){ console.log(error); } } // call the function fetchData()
This is how Axios fetches in data you have your array objects
This is how fetch fetch data in async/await
Both Axios and Fetch are almost similar in functionality, but some prefer Axios over Fetch for their built-in APIs for its ease of use.
In both the APIs result is same but there are some differences which are –
- Fetch API does not directly convert the data to json format. We have to tell it.
- But Axios converts data to json format for better readability.
- Axios has built-in XSRF(Cross-Site Request Forgery) protection, while Fetch does not.
- Axios has the ability to intercept HTTP requests but Fetch, by default, does not.
- Axios allows canceling requests and request timeout but fetch does not.