Photo by Lautaro Andreani on Unsplash
Making HTTP requests with Axios - GET, POST, PUT, DELETE and much more.
Table of contents
Axios is a JavaScript library that allows you to make HTTP requests from a web page or a Node.js server. It is a lightweight, promise-based library that makes it easy to work with APIs and handle the responses.
With Axios, you can make various types of requests, such as GET, POST, PUT, and DELETE.
In this guide, we'll see how to install Axios and make HTTP requests using it with examples. Let's Dive right in!
What is Axios?
Axios is a JavaScript library that allows you to make HTTP requests from a web page or a Node.js server. It is a lightweight, promise-based library that makes it easy to work with APIs and handle the responses.
With Axios, you can make various types of requests, such as GET, POST, PUT, and DELETE. It also allows you to set headers, parameters, and other options for the request. Additionally, Axios automatically parses JSON responses, making it easy to work with the data.
One of the key features of Axios is its ability to handle errors and network errors. It returns a rejected promise when an error occurs, allowing you to handle errors consistently. It also has built-in support for canceling requests and handling request timeouts.
Axios is widely used in both front-end and back-end development. It's popular in React, Angular, and Vue.js for making API calls and handling responses. It's also commonly used in Node.js applications to make HTTP requests.
Why use Axios in React?
If you don't already know, there are a number of different libraries that you can use to make these requests so why choose Axios
Let me answer that with a few good reasons:
Ease of use: Axios is easy to use and has a simple API. It allows you to make HTTP requests with just a few lines of code, making it a great choice for developers who want to quickly and easily make API calls from their React components.
Handling errors: Axios makes it easy to handle errors that may occur when making API calls. It returns a rejected promise when an error occurs, allowing you to handle errors in a consistent way. This can make it easier to debug and troubleshoot your code.
Automatic JSON parsing: Axios automatically parses JSON responses, which can save you a lot of time and effort. This eliminates the need to manually parse the JSON data and makes it easy to work with the response data.
Integration with React lifecycle methods: Axios can be easily integrated with React's lifecycle methods, such as
componentDidMount
,componentDidUpdate
, etc. You can make an API call in these methods and update the component's state with the response data.Handling loading state: You can use the lifecycle methods or custom functions to make the API calls, and use the state to keep track of the loading state of the API calls. This can be useful for displaying a loading spinner or a message while the data is being fetched.
Support for request config and interceptors: Axios allows to set and manage request config, such as headers, base URL, timeout, etc. It also allows using of interceptors to add common functionality for all requests, such as authentication, logging, etc.
Installing Axios
Before installing Axios in React, make sure you have just the following three things as a base.
A React project.
Installed Axios with npm or yarn.
An API endpoint for making requests
Install Axios
To use Axios in your React application, you first need to install it by running the following command in the terminal: npm install axios
or yarn add axios
Import Axios
In the component where you want to make the API call, import Axios by adding the following line at the top of the file: import axios from 'axios';
Make the API call
You can make an API call by using one of the methods provided by Axios such as axios.get()
, axios.post()
, axios.put()
, axios.delete()
inside a component's lifecycle method or a custom function. These steps are discussed further below in detail
Quick React Snippet
By using JSON Placeholder API to get and change data. This code would set you up with a basic post-altering app in react.
import axios from "axios";
import React from "react";
const baseURL = "https://jsonplaceholder.typicode.com/posts/1";
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(() => {
axios.get(baseURL).then((response) => {
setPost(response.data);
});
}, []);
if (!post) return null;
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
Making a GET request
To make a GET request using Axios, you can use the axios.get()
method. This method takes in the URL of the API endpoint as the first parameter and an optional configuration object as the second parameter. The configuration object can be used to set headers, parameters, and other options.
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Making a POST request
To make a POST request, you can use the axios.post()
method. This method takes in the URL of the API endpoint as the first parameter, the data to be sent in the request as the second parameter, and an optional configuration object as the third parameter.
axios.post('https://jsonplaceholder.typicode.com/users', {
name: 'John Doe',
email: 'johndoe@example.com'
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Making a PUT request
To make a PUT request, you can use the axios.put()
method. This method takes in the URL of the API endpoint as the first parameter, the data to be sent in the request as the second parameter, and an optional configuration object as the third parameter.
axios.put('https://jsonplaceholder.typicode.com/users/1', {
name: 'Jane Doe',
email: 'janedoe@example.com'
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Making a DELETE request
To make a DELETE request, you can use the axios.delete()
method. This method takes in the URL of the API endpoint as the first parameter, an optional data to be sent in the request as the second parameter, and an optional configuration object as the third parameter.
axios.delete('https://jsonplaceholder.typicode.com/users/1')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
How to handle errors with Axios?
Handling errors with Axios is a simple process that can be done by chaining a .catch()
method to the API call. The .catch()
method is called when the API call returns a rejected promise, indicating that an error has occurred.
Here's an example
class MyComponent extends React.Component {
state = {
error: null
}
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
this.setState({ users: response.data });
})
.catch(error => {
this.setState({ error });
});
}
render() {
return (
<div>
{this.state.error && <div>{this.state.error.message}</div>}
{this.state.users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
}
}
How to Create an Axios Instance?
Axios provides the ability to create an instance of the axios client with a custom configuration. This can be useful when you need to make API calls to different servers or with different configurations.
Here's an example of how you can create an instance of the Axios client with a custom configuration:
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 1000,
});
instance.get('/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
In this example, we're creating an instance of the Axios client with a custom baseURL
and timeout
configuration. Once the instance is created, we can make API calls using the instance.get()
, instance.post()
, instance.put()
, instance.delete()
methods, which works the same way as the default Axios client.
You can also set default headers, auth, interceptors, etc. using the create
method.
const instance = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
headers: {'X-Custom-Header': 'foobar'}
auth: {
username: 'janedoe',
password: 's00pers3cret'
}
});
instance.interceptors.request.use(config => {
// Do something before request is sent
return config;
}, error => {
// Do something with request error
return Promise.reject(error);
});
Creating an instance of the Axios client with a custom configuration can be useful in situations where you need to make API calls to different servers or with different configurations. It allows you to configure the client once and use it throughout your application without having to repeat the same configuration for each API call.
Popular Axios libraries
With the increasing rise in popularity of Axios among developers, there have been variations and third-party releases of the Axios Library which extend the functionality of Axios furthermore.
I've curated a list of 10 such libraries:
axios-vcr: Record and replay requests in JavaScript.
axios-response-logger:Axios interceptor which logs responses.
axios-method-override:Axios request method override plugin.
axios-extensions:Axios extensions lib, including throttle and cache GET request features.
axios-cache-plugin: Helps you cache GET requests when using Axios.
axios-cookiejar-support: Add tough-cookie support to Axios.
react-hooks-axios: Custom React Hooks for Axios.
axios-curlirize: Log any Axios request as a curl command in the console/.
axios-actions: Bundle endpoints as callable, reusable services.
mocha-axios: HTTP assertions for Mocha using Axios.
Summing Up!
In conclusion, Axios is a powerful and easy-to-use JavaScript library that makes it simple to work with API functions. With Axios, you can quickly make GET, POST, PUT, and DELETE requests to different API endpoints and conveniently handle the response data.
Axios is a great library for making API calls in a React application. It is easy to use and integrates seamlessly with React's lifecycle methods. Remember to handle the loading state and error state of the API calls for a better user experience.
Congratulations now you have mastered one of the most important and powerful HTTP client libraries, you can now use this in your own React projects!
Want to add something, comment below.
Thanks for your time, I hope this article was helpful!