Lesson 109 of 158 – Axios GET Request
69%

Axios GET Request

The Axios GET method is used to retrieve data from a REST API. In a React Native application, Axios can send a GET request to a PHP REST API, and the API can return data from a MySQL database.

Note: GET requests are normally used to read or retrieve data. In this lesson, we will learn GET requests with React Native, Axios, PHP REST API and MySQL.

1. What is an Axios GET Request?

An Axios GET request asks a server for information.

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

2. Basic Axios GET Syntax

const response =
    await axios.get(API_URL);

console.log(
    response.data
);

The axios.get() method sends a GET request.

3. Importing Axios

import axios from "axios";

Axios must be installed and imported before using it.

npm install axios

4. Simple GET Request

import axios from "axios";

async function getStudents() {

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

    console.log(
        response.data
    );
}

5. Using try...catch

Network and server errors should be handled with try...catch.

async function getStudents() {

    try {

        const response =
            await axios.get(API_URL);

        console.log(
            response.data
        );

    } catch (error) {

        console.log(
            error.message
        );

    }
}

6. Reading response.data

Axios provides the server response through the data property.

const response =
    await axios.get(API_URL);

const result =
    response.data;

console.log(result);

Unlike Fetch, you normally do not call response.json().

7. PHP API Response

Suppose the PHP API returns:

{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "Rahul Kumar",
            "email": "rahul@example.com"
        },
        {
            "id": 2,
            "name": "Amit Kumar",
            "email": "amit@example.com"
        }
    ]
}

Axios makes this JSON available through response.data.

8. Accessing the Student Data

const response =
    await axios.get(API_URL);

const students =
    response.data.data;

console.log(students);

The first data belongs to Axios and the second data belongs to the JSON structure returned by the API.

9. Axios GET 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
        );
    }
}

10. Loading Data with useEffect

useEffect(() => {

    getStudents();

}, []);

This loads the students when the component is mounted.

11. GET Request with API Base URL

Creating an Axios instance makes API requests easier to maintain.

import axios from "axios";

const api = axios.create({

    baseURL:
        "https://example.com/api"

});

export default api;

Then use the instance:

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

12. GET Request with Query Parameters

Axios provides the params option for query parameters.

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

The request becomes similar to:

/students.php?search=rahul

13. Multiple Query Parameters

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

Axios creates the query string from the params object.

14. GET Request with Headers

Headers can be added to a GET request.

const response =
    await api.get(
        "/students.php",
        {
            headers: {
                "Accept":
                    "application/json"
            }
        }
    );

15. GET Request with JWT Token

A protected API can require a JWT token.

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

The PHP API can verify the token before returning protected data.

16. Checking HTTP Status

const response =
    await axios.get(API_URL);

console.log(
    response.status
);

For example, a successful GET request commonly returns HTTP status 200.

17. Axios Error Response

When Axios receives an HTTP error response, useful information can be accessed from error.response.

try {

    await axios.get(API_URL);

} catch (error) {

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

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

}

18. Loading State

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

async function getStudents() {

    setLoading(true);

    try {

        const response =
            await axios.get(API_URL);

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

    } catch (error) {

        console.log(
            error.message
        );

    } finally {

        setLoading(false);
    }
}

19. Displaying GET Data with FlatList

<FlatList

    data={students}

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

    renderItem={({ item }) => (

        <View>

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

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

        </View>

    )}
/>

20. GET Request with Search

Search parameters can be sent using Axios.

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

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

21. GET Request with Pagination

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

This can be combined with FlatList's onEndReached for loading additional records.

22. GET Request with Search and Pagination

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

This is useful for large student lists.

23. GET Request with Sorting

const response =
    await api.get(
        "/students.php",
        {
            params: {
                page: 1,
                limit: 10,
                sort: "name",
                order: "asc"
            }
        }
    );

The PHP API should allow only approved sorting columns and directions.

24. Reusable GET Function

async function getStudents(
    search = "",
    page = 1
) {

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

    return response.data;
}

A reusable function keeps API logic separate from the UI.

25. Complete PHP GET API

<?php

header(
    "Content-Type: application/json"
);

require_once "../db.php";

$search = trim(
    $_GET['search'] ?? ''
);

if ($search !== '') {

    $keyword =
        "%" . $search . "%";

    $stmt = $pdo->prepare(
        "SELECT id, name, email, course
         FROM students
         WHERE name LIKE ?
            OR email LIKE ?
            OR course LIKE ?
         ORDER BY id DESC"
    );

    $stmt->execute([
        $keyword,
        $keyword,
        $keyword
    ]);

} else {

    $stmt = $pdo->query(
        "SELECT id, name, email, course
         FROM students
         ORDER BY id DESC"
    );
}

$data =
    $stmt->fetchAll(
        PDO::FETCH_ASSOC
    );

echo json_encode([
    "success" => true,
    "data" => $data
]);

26. Complete React Native GET Function

async function getStudents() {

    setLoading(true);
    setError("");

    try {

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

        if (response.status === 200) {

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

        }

    } catch (error) {

        if (error.response) {

            setError(
                error.response.data?.message ||
                "Server error"
            );

        } else {

            setError(
                "Network error"
            );
        }

    } finally {

        setLoading(false);
    }
}

27. Axios GET with Empty Results

A successful request may return an empty array when no records match.

{
    "success": true,
    "data": []
}

React Native can display a friendly message:

{students.length === 0 && (
    <Text>
        No students found.
    </Text>
)}

28. Complete Axios GET Example

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

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

import axios from "axios";

const api = axios.create({

    baseURL:
        "https://example.com/api",

    timeout: 10000

});

export default function StudentList() {

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

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

    const [error, setError] =
        useState("");

    async function getStudents() {

        setLoading(true);
        setError("");

        try {

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

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

        } catch (error) {

            if (error.response) {

                setError(
                    error.response.data?.message ||
                    "Server error"
                );

            } else {

                setError(
                    "Network error"
                );
            }

        } finally {

            setLoading(false);
        }
    }

    useEffect(() => {

        getStudents();

    }, []);

    return (

        <View style={{
            flex: 1,
            padding: 20
        }}>

            {loading && (
                <ActivityIndicator
                    size="large"
                />
            )}

            {error !== "" && (
                <Text>
                    {error}
                </Text>
            )}

            <FlatList

                data={students}

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

                renderItem={({ item }) => (

                    <View style={{
                        padding: 15
                    }}>

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

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

                        <Text>
                            Course:
                            {item.course}
                        </Text>

                    </View>

                )}

                ListEmptyComponent={
                    !loading ? (
                        <Text>
                            No students found.
                        </Text>
                    ) : null
                }

            />

        </View>
    );
}

29. Common Axios GET Mistakes

  • Forgetting to install Axios.
  • Using an incorrect API URL.
  • Forgetting to import Axios.
  • Trying to use response.json() with Axios.
  • Not reading data from response.data.
  • Not handling network errors.
  • Not checking server errors.
  • Forgetting JWT headers for protected APIs.
  • Not handling loading states.
  • Not handling empty results.
  • Hard-coding the same API URL in many components.

30. Complete Axios GET Flow

React Native
      ↓
  axios.get()
      ↓
   HTTP GET
      ↓
 PHP REST API
      ↓
    MySQL
      ↓
 JSON Response
      ↓
 response.data
      ↓
 React Native State
      ↓
    FlatList
      ↓
 Display Data

Axios GET requests are the foundation for reading data from REST APIs. In the next lessons, we will use Axios for POST, PUT and DELETE requests.

📌 Key Points

  • axios.get() is used to retrieve data from an API.
  • Axios responses are accessed using response.data.
  • Axios works with async/await.
  • Use try...catch for API error handling.
  • Use params for query parameters.
  • Headers can be used for authentication.
  • JWT tokens can be sent using the Authorization header.
  • GET requests can be combined with search and pagination.
  • Axios can be configured with a common base URL.
  • React Native state can store the returned API data.
  • FlatList is useful for displaying large API result lists.

🧠 Quick Quiz

Question: Which Axios method is used to retrieve data from a REST API?