A brief introduction to Axios

Fri Apr 07 2023

3 min read

Axios is a lightweight yet powerful JavaScript library that simplifies the process of making HTTP requests both on client-side and server-side JavaScript applications.

In this guide, we'll provide a brief introduction to Axios and explore some of its key features that make it an essential tool for any web developer.

What is Axios

Axios makes it easy to send HTTP requests and handle responses in web applications. It provides a simple and intuitive API that makes it easy to perform common HTTP operations like GET, POST, and DELETE. It can be easily configured to work with a wide range of web APIs.

Additionally, Axios has built-in support for handling request and response interceptors, cancellation of requests, and automatic JSON parsing, which makes it a powerful and flexible library for managing API requests in web applications.

Getting started with Axios

Axios can be used both in the browser and in Node.js environments. To install Axios, you can use either npm or Yarn package managers by running the following command

sh
npm install axios

Once Axios is installed, you can create an instance of it with default configuration options, or you can customize the configuration to suit your specific needs.

Making HTTP requests using Axios

In this section, you will learn how to use Axios to make GET and PUT requests to a public API. To make things more interesting, we will be using the Hotels API from Rapid API Hub.

Loading component...

GET

This is a request to retrieve data from a server using a specific URL. In the example, we're making a GET request to the Hotels API to search for hotel locations in New York. It uses the params object to pass query parameters to the API.

js
axios.get('https://hotels4.p.rapidapi.com/locations/v3/search', {
params: {
q: 'new york',
locale: 'en_US',
langid: '1033',
siteid: '300000001'
},
headers: {
'X-RapidAPI-Key': 'your-api-key',
'X-RapidAPI-Host': 'hotels4.p.rapidapi.com'
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});

POST

In this example, we're using Axios to make a POST request to JSONPlaceholder's /posts endpoint. We're passing in an object that contains the data we want to create a new post with: a title, body, and userId.

js
import axios from 'axios';
const url = 'https://jsonplaceholder.typicode.com/posts';
axios.post(url, {
title: 'New post',
body: 'This is a new post.',
userId: 1
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});

Wrap up

Axios has several advantages over other libraries, including its simplicity, consistency, and ability to handle both browser and server-side environments. By using Axios, developers can improve their productivity and streamline their workflows.

Loading component...