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.
An Axios GET request asks a server for information.
React Native
↓
Axios GET
↓
PHP REST API
↓
MySQL
↓
JSON Response
↓
React Native
const response =
await axios.get(API_URL);
console.log(
response.data
);
The axios.get() method sends a GET request.
import axios from "axios";
Axios must be installed and imported before using it.
npm install axios
import axios from "axios";
async function getStudents() {
const response =
await axios.get(
"https://example.com/api/students.php"
);
console.log(
response.data
);
}
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
);
}
}
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().
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.
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.
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
);
}
}
useEffect(() => {
getStudents();
}, []);
This loads the students when the component is mounted.
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"
);
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
const response =
await api.get(
"/students.php",
{
params: {
search: "rahul",
page: 1,
limit: 10
}
}
);
Axios creates the query string from the params object.
Headers can be added to a GET request.
const response =
await api.get(
"/students.php",
{
headers: {
"Accept":
"application/json"
}
}
);
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.
const response =
await axios.get(API_URL);
console.log(
response.status
);
For example, a successful GET request commonly returns HTTP status 200.
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
);
}
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);
}
}
<FlatList
data={students}
keyExtractor={item =>
item.id.toString()
}
renderItem={({ item }) => (
<View>
<Text>
{item.name}
</Text>
<Text>
{item.email}
</Text>
</View>
)}
/>
Search parameters can be sent using Axios.
const response =
await api.get(
"/students.php",
{
params: {
search: search
}
}
);
setStudents(
response.data.data || []
);
const response =
await api.get(
"/students.php",
{
params: {
page: 2,
limit: 10
}
}
);
This can be combined with FlatList's onEndReached for loading additional records.
const response =
await api.get(
"/students.php",
{
params: {
search: "rahul",
page: 2,
limit: 10
}
}
);
This is useful for large student lists.
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.
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.
<?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
]);
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);
}
}
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>
)}
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>
);
}
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.
Question: Which Axios method is used to retrieve data from a REST API?