Society & Everyday Knowledge

How to Use Axios for API Requests

In modern web development, connecting your application to external data is a fundamental task. Whether you are building a weather app, a social media dashboard, or an e-commerce platform, your code needs a way to talk to servers. This is where Axios comes in. Axios is a popular, promise-based HTTP client that works in both the browser and Node.js environments. It simplifies the process of sending asynchronous HTTP requests to REST endpoints and performing CRUD operations (Create, Read, Update, Delete).

Using Axios has become a standard for many developers because of its clean syntax and powerful features. It automatically handles many of the repetitive tasks that used to require manual coding, such as transforming JSON data and handling different types of errors. In this guide, we will explore everything you need to know to get started with Axios, from installation to advanced configuration.

What is Axios and Why Use It?

Axios is a library that allows you to make requests to a server to retrieve or send data. While modern browsers have a built-in tool called the Fetch API, many developers prefer Axios for several reasons. First, Axios has a more concise syntax that often requires fewer lines of code. Second, it provides better support for older browsers without needing extra polyfills.

Another significant advantage is how Axios handles data. When you receive a response from a server, Axios automatically converts it into a JavaScript object. With the Fetch API, you usually have to call an extra function to parse the data as JSON. Additionally, Axios makes it easier to set up global configurations, intercept requests before they are sent, and cancel requests that are no longer needed.

How to Install Axios in Your Project

Before you can start making requests, you need to add Axios to your project. There are several ways to do this depending on your development environment. If you are working on a modern JavaScript project using a package manager, you can install it via the terminal.

Using NPM or Yarn

For projects using Node.js or frameworks like React, Vue, and Angular, the package manager is the most common method. Open your terminal in your project folder and run one of the following commands:

  • Using NPM: npm install axios
  • Using Yarn: yarn add axios

Once the installation is complete, you can import Axios into your JavaScript files by adding import axios from ‘axios’; at the top of the script.

Using a Content Delivery Network (CDN)

If you are working on a simple HTML file without a build tool, you can include Axios using a script tag. This is the fastest way to test the library without setting up a full development environment. Simply add the following line inside your HTML head or before the closing body tag:

<script src=”https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js”></script>

Making Your First GET Request

The most common type of HTTP request is a GET request, which is used to retrieve data from a specific source. With Axios, making a GET request is straightforward. You call the axios.get() method and pass the URL of the API you want to access.

Axios returns a “promise,” which is a JavaScript object representing the eventual completion of an asynchronous operation. You can handle the results using the .then() and .catch() methods. The .then() block runs if the request is successful, while the .catch() block handles any errors that occur during the process.

For example, if you wanted to fetch a list of users from a placeholder API, your code would look like this:

axios.get(‘https://api.example.com/users’)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(‘There was an error fetching the data!’, error);
});

Sending Data with POST Requests

While GET requests are for reading data, POST requests are used to send data to a server, such as when creating a new user account or submitting a contact form. In Axios, you use the axios.post() method. This method takes two main arguments: the URL of the API and the data object you want to send.

When you send data this way, Axios automatically sets the correct headers and stringifies the data into JSON format. This saves you from having to manually configure the request body. Once the server processes the data, it usually sends back a response confirming that the new resource was created successfully.

Example of a POST Request

Imagine you want to add a new post to a blog. You would create a JavaScript object with the post details and pass it to the Axios method:

const newPost = {
title: ‘My New Blog Post’,
body: ‘This is the content of the post.’,
userId: 1
};

axios.post(‘https://api.example.com/posts’, newPost)
.then(response => {
console.log(‘Post created with ID:’, response.data.id);
})
.catch(error => {
console.error(‘Error creating post:’, error);
});

Using Async and Await with Axios

While .then() and .catch() work perfectly fine, many modern developers prefer using async and await. This syntax makes asynchronous code look and behave more like synchronous code, which can make it easier to read and maintain. To use this approach, you must wrap your Axios call inside a function marked with the async keyword.

Inside the function, you use the await keyword before the Axios call. This tells the code to wait until the request is finished before moving to the next line. To handle errors in this setup, you use a try…catch block.

async function fetchData() {
try {
const response = await axios.get(‘https://api.example.com/data’);
console.log(response.data);
} catch (error) {
console.error(‘Error:’, error);
}
}

Handling Errors Effectively

One of the best features of Axios is its robust error handling. When a request fails, Axios provides an error object that contains a lot of useful information. This helps you diagnose exactly what went wrong. The error object includes the response status code, the headers, and the data returned by the server.

Common errors include 404 (Not Found), 500 (Internal Server Error), and network timeouts. By checking the error.response property, you can give your users specific feedback, such as “Invalid password” or “The server is currently down.” If the request was made but no response was received, you can check error.request to see if there is a problem with the user’s internet connection.

Configuring Axios Defaults

If your application makes many requests to the same API, you might find yourself repeating the same URL or headers over and over again. Axios allows you to set global defaults to keep your code clean. For instance, you can set a “Base URL” so that you only have to provide the specific endpoint in your individual requests.

You can also set common headers, such as authorization tokens, that will be sent with every single request. This is usually done in a central configuration file at the start of your application. By setting axios.defaults.baseURL = ‘https://api.example.com’;, any future call to axios.get(‘/profile’) will automatically point to the full URL.

Conclusion

Axios is a versatile and reliable tool that simplifies how your web applications interact with the world. By offering a clean API, automatic JSON transformation, and excellent error handling, it removes much of the complexity associated with making HTTP requests. Whether you are a beginner just learning about APIs or an experienced developer building a large-scale application, mastering Axios will make your development process smoother and more efficient.

Now that you understand the basics of GET and POST requests, as well as how to handle errors and use modern async syntax, you are ready to start integrating real-world data into your projects. To further improve your skills, consider exploring more advanced topics like Axios interceptors and request cancellation. For more helpful guides on web development and digital tools, feel free to explore our other articles.