API Calls Using Axios and fetch

Zainab Omar
1 min readAug 6, 2021

--

Axios and fetch both are used to send request to APIs. The differences between them are:

  1. Axios: has url request object and it is a stand-alone package that can be easily installed. Axios has wide browser support.
  2. Fetch: has no url in request object and is build into most modern browsers. Fetch only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+

Basic Get Request

in fetch request we have to use json() method to convert data to JSON format

fetch('http://example.com')
.then(response => response.json())
.then(data => console.log(data));

in Axios data automatically converts to JSON; first we need to install axios

$ npm install axios

and then import into our component

import Axios from 'axios'

get request will look like this:

axios.get('http://example.com')
.then(function (response) {
console.log(response);
})

Basic POST request

fetch use the body property to send data, data in fetch is stringified.

fetch('http://example.com', {headers: {'Content-Type': 'application/json','Accept': 'application/json'},method: 'POST',body: JSON.stringify(data)}).then(response => response.json())

axios uses the data property

axios({
method: 'post',
url: 'http://example.com',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});

check axios on github for more information

more information about fetch

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response