The Wayback Machine - https://web.archive.org/web/20240906141008/https://www.geeksforgeeks.org/how-to-make-get-call-to-an-api-using-axios-in-javascript/
Open In App

How to Make GET call to an API using Axios in JavaScript?

Last Updated : 17 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain JavaScript or with any library accordingly. There are two methods to use the AXIOS which are as follows:

Using Axios in Html head

The following script-src will include axios.js in the head section of your HTML code 

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

When we send a request to the API using Axios, it returns a response. The response object consists of: 

  • data: the data returned from the server.
  • status: the HTTP code returned from the server.
  • statusText: the HTTP status returned by the server.
  • headers: headers obtained from the server.
  • config: the original request configuration.
  • request: the request object.


For the purpose of demonstration, we will be hosting an API on the localhost: 

http://127.0.0.1:5000

Include axios.js and the corresponding JS file in the HTML file. In the JS file, write the following code which makes a GET request using Axios to the API. A GET request to the API requires the path to the API method. 
Example: To demonstrate making a GET request using Axios to the API in JavaScript.

JavaScript
function makeGetRequest(path) {
    axios.get(path).then(
        (response) => {
            var result = response.data;
            console.log(result);
        },
        (error) => {
            console.log(error);
        }
    );
}
makeGetRequest('http://127.0.0.1:5000/test');

Output: It will call the API with a GET request. The response will be obtained on the console window. 

Using npm install

Axios is a popular JavaScript library used for making HTTP requests in both Node.js and browser environments. It simplifies the process of sending asynchronous HTTP requests to REST APIs, allowing developers to perform various operations like fetching data, sending data, updating data, and deleting data

Step-by-step Explanation:

Step 1. Install Axios

First, install Axios in your project using npm (Node Package Manager). Open your terminal or command prompt and run the following command:

   npm install axios

Step 2. Import Axios

In your JavaScript file where you want to make API calls, import Axios using either `require` or `import` syntax, depending on your project setup.

Using CommonJS (Node.js):

   const axios = require('axios');

Using ES6 Modules:

   import axios from 'axios';

Step 3. Make a GET Request

To make a GET request to an API endpoint using Axios, you need to specify the URL of the endpoint you want to fetch data from. Use the `axios.get()` method and pass the URL as an argument.

Syntax:

   axios.get(url[, config]) 
.then(response => {
// Handle successful response
console.log(response.data); // Access response data
})
.catch(error => {
// Handle error
console.error(error);
});

Example: To demonstrate making the get call to an API using Axios in JavaScript.

JavaScript
const axios = require('axios');
axios.get('https://api.example.com/data')
    .then(response => {
        console.log(response.data);
         // Display fetched data
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });

Output: The output will include the data that is fetched after hitting the end point of the API.



Similar Reads

How to make POST call to an API using Axios.js in JavaScript ?
Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain Javascript or with any library accordingly. The following scri
2 min read
Axios npm - How to Install Axios npm in Terminal?
Axios is a popular JavaScript library for making HTTP requests in web applications. It simplifies the process of sending asynchronous requests and handling responses. It is commonly used with Node.js and in browser-based projects and can be installed via NPM (Node Package Manager). In this article, we will explore the step-by-step process of instal
2 min read
How to send one or more files to an API using axios in ReactJS?
Assuming that you want to send multiple files from the front-end, i.e., the React app, to the server using Axios. For that, there are two approaches as shown below: Send multiple requests while attaching a single file in each request.Send a single request while attaching multiple files in that request itself.We are going to follow the second approa
3 min read
Consuming a Rest API with Axios in Vue.js
Many times when building an application for the web that you may want to consume and display data from an API in VueJS using JavaScript fetch API, Vue resource, jquery ajax API, but a very popular and most recommended approach is to use Axios, a promise-based HTTP client. Axios is a great HTTP client library. Similar to JavaScript fetch API, it use
2 min read
How To Get And Process A Stream Response With Axios in NextJS ?
When building web applications with Next.js, you often encounter scenarios where you need to fetch and process streaming data. Whether it's downloading large files, real-time data feeds, or multimedia content, efficiently handling stream responses is crucial for performance and user experience. We'll explore how to utilize Axios, a popular HTTP cli
5 min read
How to make axios send cookies in its requests automatically?
Cookies are small pieces of data stored on the client's computer for various tasks. If we want to make Axios send cookies in its request automatically, then we can use the 'withCrendentials' options. We need to set it to true in our Axios configuration. This makes sure that cookies are included in both requests and responses. In this article, we wi
3 min read
4 Ways to Make an API Call in JavaScript
API(Application Programming Interface) is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data, and interact with each other. API is a service created for user applications that request data or some functionality from servers. To give specific access to our system to other appli
7 min read
Call by Value Vs Call by Reference in JavaScript
Call by Value: In this method, values of actual parameters are copied to the function’s formal parameters, and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in the actual parameters of the caller. Suppose there is a variable named “a”. Now, we store a primitive value(boo
3 min read
How to correctly use axios params with arrays in JavaScript ?
In this article, we will be going to learn about how to correctly use Axios params with arrays in Javascript. While making HTTP requests in Axios with arrays as parameters in JavaScript, one needs to serialize the array in such a way that the server can understand it easily. These are the following ways to use Axios params with arrays: Table of Con
2 min read
Program to swap two integer parameters using call by value & call by address in PHP ?
Call by value: In call by value, we will send the value from the calling function to the called function. The values of the calling function arguments are directly copied to the corresponding arguments of the called function. If any modification is done on the arguments of the called function, it will not be effected on the arguments of the calling
3 min read
REST API Call to Get Location Details in Vue.js
In this article, we will know the REST API call to get the location details in VueJS, along with understanding its implementation through the examples. VueJS is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to design the user interface layer, it is easy to pick up for any developer. It is compatible with other libraries
7 min read
How to post a file from a form with Axios?
In this article, we are going to discuss making POST requests with form data using the Axios library. Axios is a Promise based HTTP client that can be used for the web as well as for Node.JS development. However, in this article, we are going to strictly refer to client-side use of Axios. To start off, we need to add axios to our development by usi
3 min read
Axios in React Native
Axios is a widely used HTTP client for making REST API calls. You can use this in React Native to get data from any REST API. Features of Axios: It can make both XMLHttpRequests and HTTP requests.It can understand all the requests and responses from an API.Axios is promise-based.It can transform the response in JSON format. How to install Axios in
4 min read
How to remove the console errors in axios ?
In this article, we will see the “Remove the console errors in Axios“. The console errors method outputs an error message to the Web console. Axios is a JavaScript library that implements the Promise API that is native to JS ES6 and is used to make HTTP requests using node.js or XMLHttpRequests from the browser. It allows client-side XSRF protectio
2 min read
Difference between Fetch and Axios for making http requests
For web applications to communicate with servers using the HTTP protocol, developers commonly use Fetch or Axios. Both are similar, but some prefer Axios for their simplicity. However, Fetch, a built-in API, is also powerful and can do what Axios does. Table of Content What is Fetch?What is Axios?Difference between Axios and FetchWhat is Fetch?The
3 min read
How To Use Axios NPM to Generate HTTP Requests ?
In this article, we are going to learn about Axios and HTTP requests and using Axios to generate HTTP requests. Axios is a promise-based HTTP library that is used by developers to make requests to their APIs or third-party API endpoints to fetch data. It is a popular JavaScript library used for making HTTP requests from web browsers and NodeJS appl
8 min read
How to send Basic Auth with Axios in React & Node ?
Basic Auth is a simple authentication scheme. It involves sending a username and password with each request to the server through HTTP. Axios is a popular HTTP client for making requests in JavaScript. In this article, we will create a React App to demonstrate sending basic Auth with Axios and discuss the following approaches: Table of Content Basi
5 min read
Getting error handler data from post request in AXIOS
Axios is a JavaScript library that creates HTTP requests using either XMLHttpRequests in the browser or HTTP in the Node.js runtime by using the Promise API. These requests can use async/await syntax and can also use the .then() utilities for promise chaining, and the .catch() mechanism for error handling because these requests are promises.  In th
5 min read
Axios in React: A Guide for Beginners
In React, backend communication is typically achieved using the HTTP protocol. While many developers are familiar with the XML HTTP request interface and Fetch API for making HTTP requests, there's another powerful library called Axios that simplifies the process further. Table of Content PrerequisitesIntroduction to AxiosSteps to Create React Appl
7 min read
What Is Axios?
Axios is a popular open-source JavaScript library used to make HTTP requests from web browsers or Node.js environments. It simplifies the process of sending asynchronous HTTP requests to REST endpoints, handling responses, and performing various network-related tasks. Built on top of JavaScript’s native XMLHttpRequest and the fetch API, Axios offer
5 min read
How to send API call before page reload or close using ReactJS ?
To send an API call before the page reloads or closes using React JS we have to link or define a function when the page unloads. The page unloading happens just before the page is closed or tries to reload. PrerequisitesReact JSHTML DOM onbeforeinload eventApproachWe will use some listeners like "beforeupload" and "upload", which trigger a function
2 min read
How to make ajax call from JavaScript ?
Making an Ajax call from JavaScript means sending an asynchronous request to a server to fetch or send data without reloading the web page. This allows dynamic content updates, enhancing user experience by making the web application more interactive and responsive. In this article, we'll learn about three ways to make Ajax calls in JavaScript: Tabl
4 min read
How to Delay a JavaScript Function Call using JavaScript ?
Delaying a JavaScript function call involves postponing its execution for a specified time using methods like setTimeout(). This technique is useful for timed actions, animations, or asynchronous tasks, enabling smoother user experiences and better control over when certain operations run. There are several ways to delay the execution of a function
3 min read
How to Call an API Continuously from Server Side Itself in Node.js/Express.js ?
To call an API continuously from the server side in a Node.js/Express.js environment, you can implement a periodic task that executes at regular intervals. This is typically done using functions such as setInterval, which is built into Node.js for scheduling repeated operations. There are multiple ways to make API calls from a Node.js server, depen
3 min read
What is an API call?
The full form of the API is Application programming interface Basically an API call is request by a software application to access data or any other service from another application or any other server. API calls are essential for enabling communication and data exchange between different software systems often over the internet. The APIs define a
6 min read
How to make a JSON call using jQuery ?
Use the getJSON() function in jQuery to load JSON data. The getJSON() function uses a GET HTTP request to retrieve JSON-encoded data from the server. In this article, we will learn about the jQuery getJSON() function and its implementation through examples. Syntax: $(selector).getJSON(url, data, success(data, status, xhr)) Parameters: This method a
3 min read
How to make a call-able link using HTML ?
With the rise of mobile web surfing the benefits of calling directly from a web page have become more realistic. Making a call-able link is easy with the use of HTML. HTML provides browsers with protocols such as tel which are used to add clickable phone numbers. Every browser responds differently to these protocols. Some launch the phone app with
2 min read
How to Promisify geolocation API to get current position using JavaScript ?
In this article, we are going to use Promisify geolocation API into Promise-based API. Prerequisite: JavaScript Promise Approach: As we know the navigator.geolocation.getCurrentPosition is a callback-based API, so we can easily convert it into a Promise-based API. To promisify the geolocation API, we will get the user's current position from the br
3 min read
Create a chart from JSON data using Fetch GET request (Fetch API) in JavaScript
In this article, we are going to create a simple chart by fetching JSON Data using Fetch() method of Fetch API. The Fetch API allows us to conduct HTTP requests in a simpler way. The fetch() method: The fetch method fetches a resource thereby returning a promise which is fulfilled once the response is available. Syntax: const response = fetch(resou
3 min read
How to make a video call app in node.js ?
For making a video call app, It is required that each and every client send their video and audio stream to all the other clients. So for this purpose we are using Peer.js and for the communication between the clients and the server we are using WebSocket i.e. Socket.io. Prerequisite: 1. Node.js: It is an open-source JavaScript Back-End technology.
5 min read