✨ Strapi MCP is now Generally Available - let your agents manage your Strapi content ✨

Ecosystem13 min read

What Are Axios GET Requests? A Beginner's Guide to Making API Calls

May 29, 2025Updated on June 14, 2026
What Are Axios GET Requests

GET requests are the primary method for retrieving data from servers and are used for read-only operations. These requests are perfect for data retrieval without altering server resources, a key pattern in modern web applications.

This guide will show you how to make Axios GET Requests. Axios is a versatile JavaScript HTTP client that simplifies the process and works consistently in browser and Node.js environments. It is especially useful in Node.js for tasks like web scraping.

In brief:

  • Axios has a simpler syntax than the Fetch API, with automatic JSON transformation and improved error handling.
  • Setting up Axios is easy, whether using npm/yarn or a CDN.
  • Enhance GET requests with query parameters and custom headers for more accurate data retrieval.
  • Async/await syntax makes Axios requests more readable and maintainable.

Why Choose Axios for Making GET Requests?

Axios is a powerful and developer-friendly alternative to the native Fetch API for making HTTP requests in JavaScript. It simplifies GET requests by automatically parsing JSON, offering better error handling, and a more concise syntax. It also automatically rejects promises on HTTP errors, which makes it easier to manage issues.

Axios offers several key advantages over Fetch:

  1. Automatic JSON Transformation: Axios automatically parses JSON responses, so you don’t need to manually call .json() as you would with Fetch. The parsed data is available directly in response.data.
  2. Better Error Handling: To facilitate better error handling, Axios rejects promises on HTTP error status codes (4xx and 5xx). Fetch only rejects promises for network errors, requiring additional checks for HTTP error statuses.
  3. Simpler Syntax: Axios has a more concise syntax, especially when handling tasks like setting headers or managing query parameters.
  4. Request and Response Interceptors: Axios lets you intercept requests and responses, offering global configuration and data manipulation capabilities.

Let's compare a simple GET request using both Axios and Fetch:

// Axios
axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

// Fetch
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

As shown, Axios requires less boilerplate and is more straightforward.

Axios is widely used in React, Vue, and Angular projects due to its simplicity and ease of integration. Axios is also popular for working with headless CMS platforms like Strapi. For example, you can check out our real estate app guide to see how Axios integrates with Strapi in a practical project.

Setting Up Axios GET Requests

To get started with Axios GET requests, follow this simple setup guide.

Installing Axios

You can install Axios using npm and yarn, or include it via CDN.

  1. Using npm:
npm install axios
  1. Using yarn:
yarn add axios
  1. Using CDN, add the following script tag to your HTML file:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Importing Axios

Once installed, you need to import Axios into your JavaScript file:

  1. For ES6 modules:
import axios from 'axios';
  1. For CommonJS:
const axios = require('axios');

Verifying the Installation

To confirm Axios is set up correctly, try a simple test request:

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    console.log('Axios is working:', response.data);
  })
  .catch(error => {
    console.error('Error using Axios:', error);
  });

If you see the data logged in the console, Axios is successfully installed and ready to use.

Making Your First Axios GET Request

Now that Axios is set up, let’s create your first GET request. We’ll start with the simplest example and then explore how to access and display the response data.

  1. Start with the simplest form:
axios.get('https://api.example.com/data')

This line sends a GET request to the specified URL.

  1. To access the response data, we use the .then() method:
axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  });

The response object contains several properties:

  • data: The payload returned from the server
  • status: The HTTP status code
  • statusText: The HTTP status message
  • headers: The headers sent by the server
  • config: The original request configuration
  1. Let's create a complete, working example that fetches data from JSONPlaceholder (a free fake API for testing) and displays it on a web page:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Axios GET Request Example</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <h1>User Data</h1>
    <div id="user-data"></div>

    <script>
        // Function to fetch and display user data
        function fetchUserData() {
            axios.get('https://jsonplaceholder.typicode.com/users/1')
                .then(response => {
                    const userData = response.data;
                    const userDiv = document.getElementById('user-data');
                    userDiv.innerHTML = `
                        <h2>${userData.name}</h2>
                        <p>Email: ${userData.email}</p>
                        <p>Phone: ${userData.phone}</p>
                        <p>Website: ${userData.website}</p>
                    `;
                })
                .catch(error => {
                    console.error('Error fetching user data:', error);
                    const userDiv = document.getElementById('user-data');
                    userDiv.innerHTML = '<p>Error fetching user data. Please try again later.</p>';
                });
        }

        // Call the function when the page loads
        fetchUserData();
    </script>
</body>
</html>

In this example:

  • We include the Axios library using a CDN.
  • We define a function fetchUserData() that makes a GET request to the JSONPlaceholder API.
  • Inside the .then() block, we access the response data and update the HTML to display the user information.
  • We use a .catch() block to handle any errors that might occur during the request.
  • The fetchUserData() function is called when the page loads, triggering the API request.

This basic example demonstrates how to make a GET request with Axios, handle the response, and update the DOM with the fetched data. It also includes simple error handling to improve the user experience in case of network issues or API errors. You could also use this same approach to fetch content from a headless CMS like Strapi 5, which provides a robust REST API for content delivery.

Advanced Axios Features for GET Requests

You can use query parameters and custom headers to create more efficient, secure, and flexible API interactions. Query parameters reduce unnecessary data transfer, while custom headers help implement robust authentication, versioning, and other custom behaviors in your application.

Query Parameters

Query parameters allow you to filter, sort, and paginate data directly from the API, reducing the amount of data transferred and processed by your application. There are two primary methods to add query parameters to your Axios GET requests:

  1. Directly in the URL:
axios.get('https://api.example.com/data?id=123&sort=desc')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));
  1. Using the params object:
axios.get('https://api.example.com/data', {
  params: {
    id: 123,
    sort: 'desc'
  }
})
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

The params object approach is generally preferred as it offers cleaner code and automatic URL encoding. This is particularly useful when dealing with complex parameters or values that may contain special characters.

Real-world use case: In an e-commerce application, you might use query parameters to fetch products based on category, price range, or search terms:

axios.get('https://api.example.com/products', {
  params: {
    category: 'electronics',
    minPrice: 100,
    maxPrice: 500,
    search: 'smartphone'
  }
})
  .then(response => {
    // Handle filtered product list
  })
  .catch(error => console.error('Error fetching products:', error));

When working with a headless CMS like Strapi v5, query parameters are beneficial for filtering content collections. For example:

axios.get('https://your-strapi-v5-api.com/api/articles', {
  params: {
    'filters[category][$eq]': 'technology',
    'sort[0]': 'publishedAt:desc',
    'pagination[page]': 1,
    'pagination[pageSize]': 10
  }
})
  .then(response => {
    // Handle filtered articles
  })
  .catch(error => console.error('Error fetching articles:', error));

Custom Headers

Custom headers allow you to send additional information with your requests, such as authentication tokens, content types, or client-specific data. Here's how to add custom headers to your Axios GET requests:

axios.get('/api/data', {
  headers: {
    'Authorization': 'Bearer token123',
    'Accept': 'application/json',
    'X-Custom-Header': 'SomeValue'
  }
})
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

Real-world use cases for custom headers include:

  1. Authentication: Send JWT tokens or API keys.
  2. Content Negotiation: Specify accepted response formats.
  3. API Versioning: Request specific API versions.
  4. Tracking: Add client or request identifiers.

For example, in a SaaS application that uses JWT for authentication:

const authToken = getAuthTokenFromStorage();

axios.get('https://api.example.com/user/profile', {
  headers: {
    'Authorization': `Bearer ${authToken}`,
    'Accept': 'application/json',
    'X-Client-Version': '2.1.0'
  }
})
  .then(response => {
    // Handle user profile data
  })
  .catch(error => {
    if (error.response && error.response.status === 401) {
      // Handle unauthorized access
    } else {
      console.error('Error fetching user profile:', error);
    }
  });

Error Handling When Making Axios GET Requests

Effective error handling is essential when making GET requests with Axios. It ensures your application remains resilient in the face of errors. Axios provides a detailed error object to help you manage different types of errors. There are three main types of errors you may encounter:

  • Response errors: The server returns an error status code (4xx or 5xx).
  • Request errors: No response is received (network issues).
  • Setup errors: Issues with the request configuration.

Here’s an example of how to handle these errors using a try/catch block with async/await syntax:

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    console.log(response.data);
  } catch (error) {
    if (error.response) {
      // Server responded with an error status
      switch (error.response.status) {
        case 400:
          console.log('Bad Request');
          break;
        case 401:
          console.log('Unauthorized');
          break;
        case 404:
          console.log('Not Found');
          break;
        default:
          console.log('Server Error:', error.response.status);
      }
    } else if (error.request) {
      // Request was made but no response received
      console.log('No response received:', error.request);
    } else {
      // Error in setting up the request
      console.log('Request error:', error.message);
    }
  }
}

This approach allows you to handle specific HTTP status codes, provide appropriate feedback to users, and perform necessary actions (like redirecting to a login page for 401 errors).

For more fine-grained control over which status codes trigger errors, you can use the validateStatus option:

axios.get('https://api.example.com/data', {
  validateStatus: function (status) {
    return status < 500; // Only treat 500+ status codes as errors
  }
});

To implement centralized error handling, you can use Axios interceptors:

axios.interceptors.response.use(
  response => response,
  error => {
    // Global error handling logic
    if (error.response && error.response.status === 401) {
      // Redirect to login page or refresh token
    }
    return Promise.reject(error);
  }
);

When working with content APIs like those provided by Strapi v5, proper error handling becomes even more critical. For instance, you might need to handle permission errors differently from validation errors:

try {
  const response = await axios.get('https://your-strapi-v5-api.com/api/restricted-content');
  displayContent(response.data);
} catch (error) {
  if (error.response) {
    if (error.response.status === 403) {
      showPermissionError("You don't have access to this content");
    } else if (error.response.status === 404) {
      showNotFoundError("The content you requested doesn't exist");
    } else {
      showGenericError("Something went wrong when fetching content");
    }
  } else {
    showConnectionError("Could not connect to the content server");
  }
}

Using Async/Await with Axios GET Requests

The async/await syntax simplifies handling asynchronous HTTP requests in JavaScript. It makes working with Axios GET requests much cleaner and more readable.

Here's how to use async/await with Axios GET requests:

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    console.log(response.data);
    return response.data;
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error;
  }
}

The await keyword pauses the function's execution until the promise is resolved, making the code read more like synchronous code while maintaining its asynchronous behavior. This approach eliminates the need for promise chains with .then() and .catch(), resulting in more readable and maintainable code.

Error handling with async/await is also more intuitive. You can use familiar try/catch blocks to handle errors, making your code easier to understand and debug.

Async/await really shines when handling multiple sequential requests. Instead of dealing with nested promise chains, you can write code that's easier to follow:

async function getUserWithPosts(userId) {
  try {
    const userResponse = await axios.get(`https://api.example.com/users/${userId}`);
    const user = userResponse.data;

    const postsResponse = await axios.get(`https://api.example.com/users/${userId}/posts`);
    const posts = postsResponse.data;

    return {
      user,
      posts
    };
  } catch (error) {
    console.error('Error fetching user data:', error);
    throw error;
  }
}

When fetching content from a headless CMS like Strapi v5, async/await makes complex data fetching operations more manageable:

async function fetchBlogWithRelatedContent() {
  try {
    // Fetch the main blog post
    const blogResponse = await axios.get('https://your-strapi-v5-api.com/api/blogs/1?populate=author,category');
    const blog = blogResponse.data;

    // Use information from the blog to fetch related content
    const categoryId = blog.data.attributes.category.data.id;

    // Fetch related posts in the same category
    const relatedResponse = await axios.get(`https://your-strapi-v5-api.com/api/blogs`, {
      params: {
        'filters[category][id][$eq]': categoryId,
        'filters[id][$ne]': blog.data.id, // Exclude current blog
        'pagination[limit]': 3
      }
    });

    return {
      currentBlog: blog.data,
      relatedBlogs: relatedResponse.data.data
    };
  } catch (error) {
    console.error('Error fetching blog content:', error);
    throw error;
  }
}

Remember that async functions always return a promise, so you can still use .then() and .catch() when calling them:

getUserWithPosts(123)
  .then(data => {
    console.log(data.user);
    console.log(data.posts);
  })
  .catch(error => {
    console.error('Failed to get user with posts:', error);
  });

Simultaneous GET Requests with Axios

In modern web development, you often need to fetch data from multiple endpoints simultaneously. Axios provides powerful tools to handle concurrent GET requests efficiently.

Using axios.all()

The axios.all() method allows you to execute multiple GET requests concurrently. It takes an array of promises and returns a single promise that resolves when all requests are complete:

import axios from 'axios';

const endpoints = [
  'https://api.github.com/users/username',
  'https://api.github.com/users/username/repos',
  'https://api.github.com/users/username/followers'
];

axios.all(endpoints.map(endpoint => axios.get(endpoint)))
  .then(responses => {
    console.log(responses); // Array of response objects
  })
  .catch(error => {
    console.error(error);
  });

This approach is useful when you need to fetch related data from different endpoints.

Handling Responses with axios.spread()

To make response handling more readable, especially when dealing with multiple requests, you can use axios.spread():

const getUserInfo = () => {
  const userRequest = axios.get('https://api.github.com/users/username');
  const reposRequest = axios.get('https://api.github.com/users/username/repos');
  const followersRequest = axios.get('https://api.github.com/users/username/followers');

  axios.all([userRequest, reposRequest, followersRequest])
    .then(axios.spread((userResponse, reposResponse, followersResponse) => {
      console.log('User data:', userResponse.data);
      console.log('Repos data:', reposResponse.data);
      console.log('Followers data:', followersResponse.data);
    }))
    .catch(error => {
      console.error(error);
    });
};

This method simplifies response handling and improves readability.

Using Async/Await for Cleaner Code

You can use async/await with Promise for even more readable asynchronous code.all():

async function fetchData() {
  try {
    const endpoints = [
      'https://api.example.com/users',
      'https://api.example.com/products',
      'https://api.example.com/orders'
    ];

    const requests = endpoints.map(endpoint => axios.get(endpoint));
    const responses = await Promise.all(requests);

    const [users, products, orders] = responses.map(response => response.data);

    return { users, products, orders };
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error;
  }
}

This approach allows you to manage multiple concurrent requests with cleaner, more readable code.

When working with content management systems like Strapi v5, you might need to fetch different content types simultaneously:

async function fetchHomepageContent() {
  try {
    const strapiBaseUrl = 'https://your-strapi-v5-api.com/api';

    // Define all the requests we need for our homepage
    const requests = [
      axios.get(`${strapiBaseUrl}/hero-section?populate=*`),
      axios.get(`${strapiBaseUrl}/featured-products?populate=images`),
      axios.get(`${strapiBaseUrl}/testimonials?pagination[limit]=3`),
      axios.get(`${strapiBaseUrl}/blog-posts?pagination[limit]=4&sort=publishedAt:desc`)
    ];

    // Execute all requests in parallel
    const [heroData, productsData, testimonialsData, blogData] = await Promise.all(requests);

    // Transform and return the data
    return {
      hero: heroData.data.data.attributes,
      featuredProducts: productsData.data.data,
      testimonials: testimonialsData.data.data,
      latestBlogPosts: blogData.data.data
    };
  } catch (error) {
    console.error('Failed to fetch homepage content:', error);
    throw error;
  }
}

Best Practices for Managing Multiple Requests

You can follow these practices and adopt Axios's features for concurrent GET requests to build robust and efficient data fetching logic in your web applications.

  1. Use descriptive variable names to clearly indicate what each request is fetching.
  2. Handle errors appropriately, either globally or individually for each request.
  3. Consider request cancellation in single-page applications to prevent memory leaks when components unmount.
  4. Be mindful of performance implications, such as browser limits on concurrent connections and response sizes.
  5. Implement caching strategies to avoid redundant requests and improve application performance.

Whether you're building a dashboard that needs to display various types of content from Strapi v5 or a complex form that requires information from multiple endpoints, mastering simultaneous GET requests with Axios will significantly enhance your development workflow.

Streamlining Your API Workflow with Axios

Mastering GET requests with Axios offers a world of possibilities for building robust, data-driven applications. In this guide, you’ve learned how to set up Axios, make basic and advanced requests, handle errors effectively, and use modern JavaScript patterns like async/await for cleaner code. You’ve also seen how Axios works seamlessly with headless CMS platforms like Strapi 5 to fetch and manage content efficiently.

By implementing the techniques in this guide, you’ll create more maintainable and error-resistant code that communicates with backend services. Good API integration goes beyond just making requests—it’s about handling responses smoothly, managing errors intelligently, and structuring your code for readability and maintainability.

Whether building a marketing site with Strapi or a food ordering app with Strapi, mastering Axios will streamline your development process and enhance your app’s performance.

Paul BratslavskyDeveloper Advocate

Related Posts

Authentication Methods in Strapi
APIs·11 min read

Guide on Authenticating Requests With the REST API in Strapi

This article was updated to Strapi v5.

·March 27, 2024
Request Strapi's REST API behind a CDN.jpg
TutorialsAdvanced·15 min read

Request Strapi's REST API behind a Content Delivery Network (CDN)

This tutorial will focus on the problem of network latency when requesting large numbers of media assets from a REST...

·July 18, 2024
TutorialsIntermediate·10 min read

How to Build an API Request Throttling with Strapi and Redis

Learn how to implement API request throttling using Strapi and Redis by implementing a blog to show how to limit client requests to specific endpoints.

·May 11, 2023