Skip to main content
React Native Introduction
CHAPTER 19 Beginner

Axios and API Integration

Updated: May 16, 2026
5 min read

# CHAPTER 19

Axios and API Integration

1. Introduction

In the previous chapter, we used the built-in fetch API. It works perfectly, but it is highly repetitive. For every single request, you have to manually write response.json(), manually check !response.ok to throw errors, and manually attach your authentication tokens to the headers. If your app makes 50 different API calls, this is an architectural nightmare. In this chapter, we will master Axios and API Integration. Axios is the undisputed industry-standard HTTP client for React and React Native. We will learn how to configure a global instance, set base URLs, and utilize interceptors to automate error handling and authentication.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain why Axios is preferred over the native fetch API.
  • Install the axios package via npm.
  • Execute clean GET and POST requests using Axios.
  • Create an Axios Instance with a global baseURL.
  • Understand the concept of Axios Interceptors for authentication.

3. Axios vs Fetch (The Advantages)

Why do professionals install a third-party library when fetch is built-in?
  1. 1. Automatic JSON Parsing: You never have to write await response.json() again. Axios does it automatically.
  1. 2. Automatic Error Throwing: fetch does not trigger the catch block if a server returns a 404 Not Found error (it only catches total network failures). Axios automatically throws an error for *any* status code outside the 200 range!
  1. 3. Timeouts: You can tell Axios to abort the request automatically if the server takes longer than 5 seconds.
  1. 4. Global Configuration: You can set a Base URL and default headers once, and never type them again.

4. Installation and Basic Usage

Install the package:
bash
1
npm install axios

Let's refactor the GET and POST requests from the previous chapter to use Axios. Notice how much cleaner the code is!

javascript
1234567891011121314151617181920212223242526272829303132
import axios from 'axios';

// --- GET REQUEST ---
const fetchUsers = async () => {
  try {
    // 1. One line of code! No response.json() needed!
    const response = await axios.get('https://jsonplaceholder.typicode.com/users');
    
    // 2. The parsed data is automatically attached to the '.data' property!
    console.log(response.data); 
  } catch (error) {
    // Automatically catches 404, 500, and network failures!
    console.error("Error:", error.message);
  }
};

// --- POST REQUEST ---
const createPost = async () => {
  try {
    // 1. Pass the exact JavaScript object! No JSON.stringify() needed!
    // 2. Headers are handled automatically!
    const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'Axios is awesome',
      body: 'It saves so much time',
      userId: 1
    });

    console.log("Success! ID:", response.data.id);
  } catch (error) {
    console.error("Error:", error.message);
  }
};

5. Creating an Axios Instance (Best Practice)

In a real app, you don't want to type https://api.mycompany.com/v1/ on every single request. You create a specialized Axios "Instance" in an api.js file, configure it once, and import *that instance* everywhere else in your app.
javascript
123456789101112131415
// services/api.js
import axios from 'axios';

// Create a custom instance
const apiClient = axios.create({
  baseURL: 'https://api.mycompany.com/v1',
  timeout: 10000, // Abort if it takes longer than 10 seconds!
  headers: {
    'Accept': 'application/json',
    // You can attach API Keys here globally!
    'X-Api-Key': 'SECRET_12345' 
  }
});

export default apiClient;

Now, in your UI components, you use the instance for incredibly clean code:

HomeScreen.js
12345678
import apiClient from '../services/api';

const fetchProducts = async () => {
  // It automatically prepends the baseURL!
  // It actually calls: https://api.mycompany.com/v1/products
  const response = await apiClient.get('/products'); 
  setProducts(response.data);
};

6. Axios Interceptors (Advanced but Crucial)

What if every API request requires a User Login Token? You don't want to manually attach the token 50 times. An Interceptor is a tollbooth. It catches EVERY request right before it leaves your phone, allowing you to automatically inject the token!
javascript
123456789101112131415161718
// services/api.js

// Request Interceptor: Runs right before the request is sent
apiClient.interceptors.request.use(
  async (config) => {
    // Fetch the token from Local Storage (We learn this next chapter!)
    const token = await AsyncStorage.getItem('userToken');
    
    // If a token exists, inject it securely into the Headers!
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

7. Visual Learning: The Interceptor Flow

txt
12345678910111213
[ UI Component: apiClient.get('/profile') ]
                 |
                 v
   [ Axios Request Interceptor ] <-- (Secretly attaches Authorization Token)
                 |
                 v
           [ The Internet ]
                 |
                 v
   [ Axios Response Interceptor ] <-- (Secretly checks if Token is expired)
                 |
                 v
     [ UI Component receives Data ]

8. Common Mistakes

  • Forgetting .data: The most common mistake for developers moving from fetch to axios is treating the response as the data. fetch returns the data directly after .json(). Axios returns an object containing headers, status codes, and configuration. The actual server payload is ALWAYS nested inside response.data.
BAD: setUsers(response); (UI crashes). GOOD: setUsers(response.data);

9. Best Practices

  • Centralized API Services: Do not write Axios calls directly inside your React Components. Create an apiServices.js file holding all your functions (export const getUserProfile = () => apiClient.get('/profile')). Your components should simply call the function. This makes your UI code much cleaner and easier to unit test.

10. Practice Exercises

  1. 1. What property of the Axios configuration object is used to set a default root URL, preventing you from typing the domain name on every request?
  1. 2. What feature of Axios allows you to intercept and modify an HTTP request (e.g., attaching an auth token) right before it leaves the mobile device?

11. MCQs with Answers

Question 1

A developer switches their code from the native fetch API to axios. Which manual step from the fetch workflow is no longer required because Axios handles it automatically?

Question 2

In Axios, if the server responds with a 404 Not Found or a 500 Internal Server Error, how does Axios behave differently than the native fetch API?

12. Interview Questions

  • Q: Detail three specific architectural advantages of using Axios over the native fetch API in a large-scale React Native project.
  • Q: Explain the purpose and implementation of an Axios Request Interceptor. Provide a specific, real-world example of when it is absolutely required.
  • Q: Describe how an Axios Response Interceptor can be utilized to handle global error scenarios, such as detecting a 401 Unauthorized status code to automatically log the user out of the application.

13. FAQs

Q: Does Axios increase the size of my app significantly? A: No, Axios is incredibly lightweight (less than 15kb). The architectural benefits and massive reduction in boilerplate code far outweigh the minuscule addition to the app bundle size.

14. Summary

In Chapter 19, we upgraded our networking architecture to enterprise standards by implementing Axios. We eliminated repetitive boilerplate code by taking advantage of Axios's automatic JSON parsing, automated stringification, and superior error throwing mechanics. We established a scalable foundation by configuring a global Axios Instance with a baseURL and Timeouts. Finally, we explored the immense power of Interceptors, paving the way for automated, secure authentication pipelines.

15. Next Chapter Recommendation

Our API is fully functional, and we can fetch a user token from the server. But when the user closes the app, the token is lost in RAM! We need to save it permanently to the phone's hard drive. Proceed to Chapter 20: AsyncStorage and Local Data Storage.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·