JavascriptNodeJS
Last updated at 2023-09-03

Axios GET Request with Example

ClickUp
Note
AI Status
Full
Last Edit By
Last edited time
Sep 3, 2023 08:19 AM
Metatag
Slug
axios-get-request
Writer
Published
Published
Date
Sep 1, 2023
Category
Javascript
NodeJS
Axios is a popular JavaScript library for making HTTP requests in both browsers and Node.js environments.
It provides a simple and easy-to-use interface for performing various HTTP requests, including GET requests.
In this article, we'll walk you through the basics of making GET requests with Axios, including standard requests, requests with parameters, authentication, custom headers, checking the status code, and parsing the response body.
If you're new to Axios or HTTP requests in general, this guide is perfect for you.
💡
This article provides a quick snippet for your reading convenience. You are free to use it. Jump to each detail section when you need to know more

Prerequisites

Before you dive into Axios, make sure you have it installed on your project.
For simplicity, you can install Axios using npm or yarn:
npm install axios # or yarn add axios
You can install using other methods too. How to install axios.
Once Axios is installed, you can start using it for GET requests.

Complete Axios GET Request Example

💡
To learn specific topics around GET requests, you can see each topic below this section
This code shows you how to make the most of the Axios get method to perform a GET request.
It has path, query parameter, id, custom header, basic authentication, and so on.
const axios = require('axios'); const API_URL = 'https://api.example.com/data'; const USERNAME = 'your_username'; const PASSWORD = 'your_password'; const CUSTOM_HEADER = 'Custom-Header-Value'; const queryParams = { standard: 'value0', param_with_underscore: 'value1', 'param-with-hyphen': 'value2', array: ['element1', 'element2'], }; const headers = { 'Authorization': `Basic ${btoa(`${USERNAME}:${PASSWORD}`)}`, 'Custom-Header': CUSTOM_HEADER, }; axios.get(API_URL, { params: queryParams, headers: headers, }) .then((response) => { if (response.status === 200) { console.log('Response Data:', response.data); } else if (response.status === 401) { console.error('Unauthorized. Check your authentication credentials.'); } else if (response.status === 404) { console.error('Resource not found.'); } else { console.error('An unexpected error occurred.'); } }) .catch((error) => { console.error('Error:', error.message); });
Now that you have something that can be copied and pasted to test it out, you need to learn more in depth about Axios get features that can help you make a GET request to a REST API endpoint.

1. Standard GET Request

Let's start with the most straightforward GET request.
Axios provides a get method that you can use to make a GET request to a specified URL.
Here's a simple example:
const axios = require('axios'); axios.get('https://jsonplaceholder.typicode.com/posts/1') .then((response) => { console.log(response.data); }) .catch((error) => { console.error(error); });
In this code:
  • You import Axios.
  • You use the axios.get method and pass the URL of the resource you want to fetch.
  • You handle the response using .then and any errors using .catch.

2. Send Query Parameters

GET requests often require parameters to filter or specify the data you want.
You can include parameters as part of the URL or use Axios's params option.
Here's an example of adding parameters to a GET request:
axios.get('https://jsonplaceholder.typicode.com/posts', { params: { userId: 1, }, }) .then((response) => { console.log(response.data); }) .catch((error) => { console.error(error); });
In this example, you added the userId parameter to the URL, resulting in a request to https://jsonplaceholder.typicode.com/posts?userId=1.
A REST API parameter key usually uses underscore (_) or just a single word, but you can use hypen too.
Usually there are some API that requires you to send array of values.
Here is how you construct param if you want to send hyphen or array:
const queryParams = { standard: 'value0', param_with_underscore: 'value1', 'param-with-hyphen': 'value2', array: ['element1', 'element2'], }; axios.get('https://jsonplaceholder.typicode.com/posts', { params: queryParams, })

3. Use Basic Authentication

If you need to authenticate your GET request, you can do so by including credentials in the request configuration.
Axios supports various authentication methods, such as Basic Authentication and Bearer Token Authentication.
Here's an example using Basic Authentication:
axios.get('https://api.example.com/data', { auth: { username: 'your_username', password: 'your_password', }, }) .then((response) => { console.log(response.data); }) .catch((error) => { console.error(error); });
Replace 'your_username' and 'your_password' with your actual credentials.

4. Send Bearer Authentication and Custom Headers

You can add custom headers to your GET request by including them in the request configuration.
Custom headers are often used for things like authentication tokens or specifying the content type. Here's an example:
axios.get('https://api.example.com/data', { headers: { 'Authorization': 'Bearer YOUR_TOKEN', 'Custom-Header': 'Custom-Value', }, }) .then((response) => { console.log(response.data); }) .catch((error) => { console.error(error); });
Replace 'YOUR_TOKEN' with your actual authentication token and add any other custom headers as needed.

5. Check the response status code.

You can check the response status code using the response.status value.
.then((response) => { if (response.status === 200) { console.log('Response Data:', response.data); } else if (response.status === 401) { console.error('Unauthorized. Check your authentication credentials.'); } else if (response.status === 404) { console.error('Resource not found.'); } else { console.error('An unexpected error occurred.'); } })

6. Parse Response Body to Javascript Object

To extract the response body to a JavaScript object in an Axios request, you can use the response.data property. Axios automatically parses the response body based on the content type and provides it as a JavaScript object. Here's a section on how to extract the response body:
const axios = require('axios') const API_URL = 'https://api.example.com/data'; axios.get(API_URL) .then((response) => { const data = response.data; console.log(data) }) .catch((error) => { console.error('Error:', error.message); });
In this section:
  • After making the GET request, we check for a successful status code (status code 200).
  • To extract the response body as a JavaScript object, we simply access the response.data property. Axios automatically parses the response body into a JavaScript object based on the content type (e.g., JSON).
  • You can then use the data object as needed within your application.

7. Error If Endpoint Not Exist

To gracefully handle errors when an endpoint doesn't exist, you should implement robust error handling in your client-side code. This involves using constructs like try...catch (for synchronous code) or .catch() (for asynchronous code) to capture and handle errors.
Here's an example of handling a 404 error in Axios:
const axios = require('axios') axios.get('https://api.example.com/non-existent-endpoint') .then((response) => { // Handle successful response console.log('Response Data:', response.data); }) .catch((error) => { if (error.response && error.response.status === 404) { // Handle 404 error console.error('Endpoint not found.'); } else { // Handle other errors console.error('An unexpected error occurred:', error.message); } });
In this example, you specifically check for a 404 status code and handle it accordingly. For other errors, we provide a more generic error message.

Conclusion

In this ultimate guide, you have covered the basics of making GET requests with Axios, including standard requests, requests with parameters, authentication, custom headers, checking status codes, parsing response body, and more.
Axios is a powerful tool for handling HTTP requests in your JavaScript projects, and with this knowledge, you can confidently perform GET requests in various scenarios.
 

Discussion (0)

Related Posts