Axios

Gabriel Castro
2 min readApr 18, 2021

For a developer, having access to API’s in order to create amazing websites is a critical part of what we do. Usually pulling information from these treasure troves involved some kind of fetch() call to retrieve the information via JSON, and from there we parse the JSON for the information we need.

Example:

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))

returns the follow…

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}

This way has been tried and true, but what if there was a better way? Introduce Axios, a promise based HTTP client for the browser and node.js. What exactly is a promise? good question, anytime we are making a fetch request we are expecting something back in return in our asynchronous call, this is our promise. This may be a failure to to reach the designated API or a successful call which would return the data we are attempting to output.

Getting Started

Ok lets get started. Great thing about Axios is it comes with its own library, in react simply run:

$ npm install axios

and your good to go!

Once installed we can go ahead and import axios in our application to create a call…

import react from 'react'
import axios from 'axios'
const App =() => {const fetchTodos = async () => {
const res = await axios.get(`https://jsonplaceholder.typicode.com/todos/1`);
console.log(res)
}
fetchTodos()
.....

Lets break this down. Firstly, we are setting our fetch to an async function, async and await make sure that we receive something back in return from out fetch, also allows us to avoid the .then in our typical fetch. Secondly, we are simply using axois syntax axios.get along with our HTTP request to API we are attempintg to ping. Lastly, we are simply console logging our outcome. Once you pull up your console, you will see more then just the data that was fetched.

This information is return due to Axios, which is of great value when you get to starting needing to send/recieve information using Axios.

This is a quick look at axios and how to get started.

Happy Coding!!

--

--

Gabriel Castro

Full Stack, Software Engineer. Focus in Rails, JavaScript and React.