Axios API

dilusha sandaruwani
3 min readJun 6, 2024

--

What is Axios

Axios is a popular JavaScript library that makes it easy to work with REST APIs. It is a promise-based HTTP client for the browser and Node.js. It’s based on the XMLHttpRequest object, but it provides a much more powerful and easy-to-use API.

With Axios, you can make various types of HTTP requests such as GET, POST, PUT, DELETE, and PATCH. It also supports a range of options including custom headers, timeouts, and authentication mechanisms.

Axios is a great choice for making HTTP requests in any JavaScript application. It’s easy to use, powerful, and flexible.

Setting Up Axios

To start using Axios, you’ll need to install it in your project. You can do this using NPM or a CDN.

Here’s an example of how to install Axios using NPM:

Once you’ve installed axios, you can include it in your HTML ot JavaScript code.

GET Request

let’s make a simple GET request to retirve data from an API using async/await syntax.
Here’s an example of how to make a GET request with axios using async/await.

We’re using the async/await keywords to create an asynchronous function and wait for the reponse from the API before logging the data to the console.

POST Request

Now, let’s make a simple POST request to send data.
Here’s an example of how to make a POST request with axios using async/await.

The data we’re sending is an object with two properties: name and age.
if the request is successful, the reponse data will be logged to the console.

Handling Errors

HTTP requests can fail due to various reasons such as network issues or server errors. It’s crucial to handle these errors gracefully. Axios offers several ways to manage errors and exceptions.

Here’s an example of handling a 404 error using async/await. This example checks if the HTTP response status is 404 (data not found) and logs a custom error message to the console. For other status codes, it logs the original error message.

Why Choose Axios for React?

  1. Simplistic Setup: Axios simplifies API connections, enhancing your project with minimal setup effort.
  2. Interceptors for Pre/Post Request Processing: Easily manage global transformations and error handling for requests and responses.
  3. Automatic JSON Data Transformation: Axios automatically handles JSON data parsing, making your code cleaner and more efficient.
  4. Cancellation of Requests: Improve user experience and performance by canceling unnecessary or redundant requests.

Happy Learning and Fun Coding!!!😊.

Sources:

--

--

dilusha sandaruwani

Software Engineering undergraduate at University of Kelaniya