Image for post
Image for post

Getting Started With Axios

This post has been published first on

Accessing REST Web Services / HTTP APIs in JavaScript

Axios is a Promise-based HTTP client for JavaScript which can be used in your front-end application and in your Node.js backend.

By using Axios it’s easy to send asynchronous HTTP request to REST endpoints and perform CRUD operations. The Axios library can be used in your plain JavaScript application or can be used together with more advanced frameworks like Vue.js.

Here is the full feature list of Axios is stated in the project’s website

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

In the following tutorial, you’ll learn how to install and add Axios to your project and perform asynchronous HTTP request. We’ll use a real-world scenario throughout this tutorial.

What We’re Going To Build

In the following you can see some screenshots of the sample application we’re going to build in this tutorial:

The user interface is split up into three sections:

  • GET Request
  • GET Request with Parameters
  • POST Request

With each of these three sections the user is able to try out a specific use case for Axios. Perfoming a GET request in the first list leads to the following result:

In the second use case the user is able to send a GET request with the ID of a specific record included:

The third use case is a POST request to create a new Todo item. Therefore the user needs to enter a new todo description:

Installing Axios

Adding Axios to your project is easy. There are two options:

Option 1: Installation Axios With Node Package Manager

Installation Axios by using the Node.js package manager. This is done by using the following command:

$ npm install axios

This downloads the library and installs it in the node_modules folder.

Option 2: Using a CDN

The easiest way is to include Axios by using a Content Delivery Network, e.g. by including the following <script> tag in your index.html file:

<script src=""></script>


As we want to use the Axios library for requesting and sending data to a REST web service we need to have access to a corresponding backend. In our last tutorial you’ve learned how to easily set up a local REST server by using JSON-Server. Now you can make use of JSON-Server again

If you want to skip that step, you can use a JSON-Server instance which is running at and offers endpoints for vaious entities.

In the following, we’ll make use of the Todo entity which is available at the enpoint:

Implementing The User Interface

The first step is to create a new project directory and within that directory create a new file index.html. We’ll use some Bootstrap CSS classes to style the elements of our user interface. Insert the following HTML code into index.html:

The implementation of the HTML user interface makes use of several Bootstrap CSS classes. To be able to use Bootstrap classes we need to include Bootstrap. We do that by including corresponding script and link tags. Furthermore file main.js is included by using a <script> element at the bottom of the body section. The main.js file will be created in the project folder and will be used to include the JavaScript code which is needed for the sample application.

The user interface is split up into three main div section:

<div class="panel panel-primary">...</div>

Each div sections contains the HTML code which is needed for one Axios use case. The HTML code of each section includes a div element which is a placeholder for the result:

<div class="panel-body" id="getResult1"></div>

<div class="panel-body" id="getResult2"></div>

<div class="panel-body" id="postResult"></div>

Later when adding the JavaScript code for our application we're able to retrieve these elements by ID and insert the inner HTML code. For use case one and two the user is able to initiate the POST request by clicking on a button:

<button class="btn btn-primary" onclick="performGetRequest1()">Get Todos</button>

<button class="btn btn-primary" onclick="performGetRequest2()">Get Todos</button>

By using the onclick attribute we're connecting the click events to function performGetRequest1() and performGetRequest2(). Both methods will make use of the Axios library to initiate the GET requests and will be implemented in main.js.

The third use case makes use of a HTML form for data entry (entering a new todo description). To respond to the submit event of the form we'll connect a corresponding event handler function to this event type in the JavaScript code later.

Performing A GET Request

Now we’re able to implement the event handler methods which makes use of the Axios framework to communicate with the REST web services. We’ll start with the first use case and implement the event handler performGetRequest1 in file main.js:

First a reference of the div element wth id getResult1 is retrieved. This is the HTML element which should be used to insert the result output from the web service call.

To perform a HTTP GET request and retrieve the list of todos from the endpoint the axios.get() function is used. We need to pass in the URI of the endpoint as a parameter. The method returns a Promise, so that we can use the then and catch methods to handle the result.

If the request has been completed successfully the function is called with is passed into the call of the then method. Within that function the response object is handed over to function generateSuccessHTMLOutput. This method extracts the information of the response object and generates a corresponding HTML output. The resulting HTML string is returned and assigned to the innerHTML property of resultElement.

If the HTTP GET request has not been completed successful the catch function is activated. In this case the generateErrorHTMLOutput method is called to generate the HTML output.

The implementation of both functions — generateSuccessHTMLOutput and generateErrorHTMLOutput — is inserted into file main.js as well. The source code is available in the following listing:

Performing A GET Request with Parameter

In the second use case we’d like to perform another HTTP GET request. This time we’d like to use a specific todo ID as a request parameter. The ID can be entered by the user. The function performGetRequest2() is implemented in main.js:

Here you can see two main differences:

  • the ID which is entered by the user is retrieved from the input element with id todoId
  • a second parameter is passed to method call axios.get()

This second parameter is an object containing the params property. Another object can be assigned to params to specify a list of URL parameters. In our case we only need the id parameter here.

Performing A POST Request

The third use case of our sample application is a HTTP POST request. The post request is used to create a new todo entry. In the following listing you can see the corresponding JavaScript code which is added in file main.js:

This time a form is used to let the user enter a new todo title. So the first thing we need to do is to connect the submit event of the form with the event handler method performPostRequest(). This is done by first retrieving a reference to the form element by using the getElementById method and then calling addEventListener.

In function performPostRequest we’re first retrieving the div element with ID postResult and second the value from the input element with ID todoTitle.

The HTTP post request is performed by calling Again, two parameter are needed. First we’re passing in the URI of the service endpoint. Second, we’re passing in an object which contains the properties of the new todo item: userId, title and completed. By default the userId is set to ‘1’ and completed is set to false.

Processing the result is done in the same way as seen before when we’ve executed the HTTP GET requests. In case the POST request has been completed successfully the generateSuccessHTMLOutput() function is called and the returned HTML string is assigned to the innerHTML property of the output div element. If the request is not completed successfully the generateErrorHTMLOutput() method is used instead.

Video Tutorial

This video tutorial contains the steps described in the text above:

Also check out the great online course: The Complete Web Developer Bootcamp

The only course you need to learn web development — HTML, CSS, JS, Node, and More!

This post has been published first on Blog

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store