Lesson 108 of 158 – Axios Introduction
68%

Axios Introduction

Axios is a popular JavaScript HTTP client used to communicate with REST APIs. In React Native applications, Axios makes it easier to send GET, POST, PUT, PATCH and DELETE requests to a PHP/MySQL backend.

Note: Axios is an alternative to the built-in Fetch API. It provides a convenient API for sending HTTP requests and handling responses.

1. What is Axios?

Axios is a promise-based HTTP client for JavaScript applications. It can be used in React Native to communicate with REST APIs.

React Native
      ↓
    Axios
      ↓
   REST API
      ↓
PHP + MySQL
      ↓
    JSON

2. Why Use Axios?

  • Simple HTTP request syntax.
  • Works with promises.
  • Supports async/await.
  • Makes JSON request and response handling convenient.
  • Supports request and response interceptors.
  • Supports custom headers.
  • Provides useful error information.
  • Works well with authentication tokens.

3. Axios and React Native

React Native can use Axios to communicate with a PHP REST API.

React Native App
       ↓
      Axios
       ↓
PHP REST API
       ↓
     MySQL
       ↓
   JSON Response
       ↓
React Native App

4. Axios vs Fetch

Feature Fetch Axios
Built-in Yes No
JSON handling Manual response.json() Response data is convenient to access
Interceptors Not built-in Yes
Request configuration Object-based Object-based
HTTP methods Supported Supported

5. Installing Axios

Install Axios inside your React Native project using npm.

npm install axios

If you use Yarn:

yarn add axios

6. Importing Axios

After installation, import Axios into your component or API service file.

import axios from "axios";

7. First Axios Request

import axios from "axios";

axios.get(
    "https://example.com/api/students.php"
)
.then(response => {

    console.log(
        response.data
    );

})
.catch(error => {

    console.log(
        error.message
    );

});

8. Axios with async/await

Axios works very well with async/await.

async function getStudents() {

    try {

        const response =
            await axios.get(
                "https://example.com/api/students.php"
            );

        console.log(
            response.data
        );

    } catch (error) {

        console.log(
            error.message
        );

    }
}

9. Axios Response Object

Axios provides a response object containing information about the API response.

const response =
    await axios.get(API_URL);

console.log(response.data);
console.log(response.status);
console.log(response.headers);

The most commonly used property is response.data.

10. Reading JSON Data

Suppose the PHP API returns:

{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "Rahul"
        }
    ]
}

Axios makes the response data available through:

response.data

You do not normally need to call response.json() like you do with Fetch.

11. Accessing API Data

const response =
    await axios.get(API_URL);

const result =
    response.data;

console.log(
    result.data
);

Here, the first data is the Axios response property and the second data belongs to the JSON response returned by your API.

12. Axios GET Request

const response =
    await axios.get(
        "https://example.com/api/students.php"
    );

const students =
    response.data.data;

console.log(students);

13. Axios POST Request

Axios can send JSON data using POST.

const response =
    await axios.post(
        API_URL,
        {
            name: "Rahul",
            email: "rahul@example.com",
            course: "React Native"
        }
    );

console.log(
    response.data
);

14. Axios PUT Request

const response =
    await axios.put(
        `${API_URL}?id=10`,
        {
            name: "Rahul Kumar",
            course: "React Native"
        }
    );

console.log(
    response.data
);

15. Axios PATCH Request

PATCH is commonly used when only some fields need to be updated.

const response =
    await axios.patch(
        `${API_URL}?id=10`,
        {
            course: "TypeScript"
        }
    );

console.log(
    response.data
);

16. Axios DELETE Request

const response =
    await axios.delete(
        `${API_URL}?id=10`
    );

console.log(
    response.data
);

17. Axios Request Configuration

Axios requests can contain a configuration object.

const response =
    await axios.get(
        API_URL,
        {
            headers: {
                "Accept":
                    "application/json"
            },

            timeout: 10000
        }
    );

18. Axios Headers

Headers can be used to send information such as authentication tokens.

const response =
    await axios.get(
        API_URL,
        {
            headers: {
                "Authorization":
                    `Bearer ${token}`
            }
        }
    );

19. Axios POST Headers

const response =
    await axios.post(
        API_URL,

        {
            name: "Rahul",
            email: "rahul@example.com"
        },

        {
            headers: {
                "Content-Type":
                    "application/json"
            }
        }
    );

20. Axios Error Handling

try {

    const response =
        await axios.get(API_URL);

    console.log(
        response.data
    );

} catch (error) {

    console.log(
        error.message
    );

}

Always handle API errors in a real mobile application.

21. Axios HTTP Error Response

When the server returns an HTTP error status such as 404 or 500, Axios provides useful information through the error object.

try {

    await axios.get(API_URL);

} catch (error) {

    console.log(
        error.response?.status
    );

    console.log(
        error.response?.data
    );

}

22. Axios with React Native State

const [students, setStudents] =
    useState([]);

async function getStudents() {

    try {

        const response =
            await axios.get(API_URL);

        setStudents(
            response.data.data || []
        );

    } catch (error) {

        console.log(
            error.message
        );

    }
}

23. Axios with useEffect

useEffect(() => {

    getStudents();

}, []);

This can be used to load API data when a React Native component is mounted.

24. Axios Base URL

Instead of repeating the complete API URL in every request, you can create an Axios instance with a base URL.

import axios from "axios";

const api =
    axios.create({
        baseURL:
            "https://example.com/api"
    });

export default api;

25. Using the Axios Instance

import api from "./api";

async function getStudents() {

    const response =
        await api.get(
            "/students.php"
        );

    console.log(
        response.data
    );
}

This makes API calls cleaner and easier to maintain.

26. Axios Query Parameters

Axios can send query parameters using the params option.

const response =
    await api.get(
        "/students.php",
        {
            params: {
                search: "rahul",
                page: 1,
                limit: 10
            }
        }
    );

Axios creates the query string for the request.

27. Axios with JWT Authentication

Axios can send a JWT token in the Authorization header.

const response =
    await api.get(
        "/profile.php",
        {
            headers: {
                Authorization:
                    `Bearer ${token}`
            }
        }
    );

This is commonly used for protected REST APIs.

28. Axios API Service Example

// api.js

import axios from "axios";

const api =
    axios.create({
        baseURL:
            "https://example.com/api",
        timeout: 10000,
        headers: {
            "Accept":
                "application/json"
        }
    });

export default api;


// StudentScreen.js

import React, {
    useEffect,
    useState
} from "react";

import {
    View,
    Text,
    FlatList
} from "react-native";

import api from "./api";

export default function StudentScreen() {

    const [students, setStudents] =
        useState([]);

    const [loading, setLoading] =
        useState(false);

    async function getStudents() {

        setLoading(true);

        try {

            const response =
                await api.get(
                    "/students.php"
                );

            setStudents(
                response.data.data || []
            );

        } catch (error) {

            console.log(
                error.message
            );

        } finally {

            setLoading(false);

        }
    }

    useEffect(() => {

        getStudents();

    }, []);

    return (

        <View>

            <FlatList

                data={students}

                keyExtractor={item =>
                    item.id.toString()
                }

                renderItem={({ item }) => (

                    <View>

                        <Text>
                            {item.name}
                        </Text>

                        <Text>
                            {item.email}
                        </Text>

                    </View>

                )}

            />

        </View>
    );
}

29. Common Axios Mistakes

  • Forgetting to install Axios.
  • Forgetting to import Axios.
  • Using the wrong API URL.
  • Not handling errors.
  • Reading the response incorrectly.
  • Forgetting authentication headers for protected APIs.
  • Not handling loading states.
  • Sending incorrect request data.
  • Not configuring the correct base URL.
  • Hard-coding API URLs in many files.

30. Complete Axios Flow

React Native
      ↓
    Axios
      ↓
HTTP Request
      ↓
 PHP REST API
      ↓
   MySQL
      ↓
 JSON Response
      ↓
 Axios Response
      ↓
response.data
      ↓
React Native State
      ↓
     UI

Axios will be used in the upcoming lessons to build GET, POST, PUT and DELETE API requests and later to handle authentication tokens.

📌 Key Points

  • Axios is a promise-based HTTP client.
  • Axios can be used with React Native REST APIs.
  • Install Axios using npm install axios.
  • Import it using import axios from "axios".
  • Axios supports GET, POST, PUT, PATCH and DELETE.
  • API response data is available through response.data.
  • Axios works with async/await.
  • Request headers can contain JWT authentication tokens.
  • The params option can send query parameters.
  • Axios instances can be created with a common base URL.
  • Always handle loading and API errors.

🧠 Quick Quiz

Question: Which property is commonly used to access the data returned by an Axios request?