Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How To Use JavaScript Fetch API To Get Data?
Next article icon

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

Last Updated : 17 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Table of Content

  • Using Axios in Html head
  • Using npm install

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.



Next Article
How To Use JavaScript Fetch API To Get Data?
author
chitrankmishra
Improve
Article Tags :
  • HTML
  • JavaScript
  • Node.js
  • Web Technologies
  • Write From Home
  • JavaScript-Questions

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 o
    2 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
    7 min read
  • How to connect to an API in JavaScript ?
    An API or Application Programming Interface is an intermediary which carries request/response data between the endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms th
    5 min read
  • How To Use JavaScript Fetch API To Get Data?
    An API is a set of rules, protocols, and tools that allows different software applications to communicate with each other. One of the popular ways to perform API requests in JavaScript is by using Fetch API. What is the Fetch API?The Fetch API is a built-in JavaScript feature that allows you to make
    4 min read
  • How to use JavaScript Fetch API to Get Data ?
    The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests.  Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity, and a few more. H
    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
    4 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
    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 reque
    3 min read
  • How to Hide API Key in JavaScript?
    The Process of Hiding API keys in JavaScript is crucial for securing our application and preventing unauthorized access. API Keys should not be exposed in client-side code because anyone can view the source code and misuse the keys. The primary goal is not accessible to end users. PrerequisitesJavaS
    2 min read
  • How to Fetch XML with Fetch API in JavaScript ?
    The JavaScript fetch() method retrieves resources from a server and produces a Promise. We will see how to fetch XML data with JavaScript's Fetch API, parse responses into XML documents, and utilize DOM manipulation for streamlined data extraction with different methods. These are the following meth
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences