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.
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
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
| 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 |
Install Axios inside your React Native project using npm.
npm install axios
If you use Yarn:
yarn add axios
After installation, import Axios into your component or API service file.
import axios from "axios";
import axios from "axios";
axios.get(
"https://example.com/api/students.php"
)
.then(response => {
console.log(
response.data
);
})
.catch(error => {
console.log(
error.message
);
});
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
);
}
}
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.
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.
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.
const response =
await axios.get(
"https://example.com/api/students.php"
);
const students =
response.data.data;
console.log(students);
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
);
const response =
await axios.put(
`${API_URL}?id=10`,
{
name: "Rahul Kumar",
course: "React Native"
}
);
console.log(
response.data
);
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
);
const response =
await axios.delete(
`${API_URL}?id=10`
);
console.log(
response.data
);
Axios requests can contain a configuration object.
const response =
await axios.get(
API_URL,
{
headers: {
"Accept":
"application/json"
},
timeout: 10000
}
);
Headers can be used to send information such as authentication tokens.
const response =
await axios.get(
API_URL,
{
headers: {
"Authorization":
`Bearer ${token}`
}
}
);
const response =
await axios.post(
API_URL,
{
name: "Rahul",
email: "rahul@example.com"
},
{
headers: {
"Content-Type":
"application/json"
}
}
);
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.
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
);
}
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 can be used to load API data when a React Native component is mounted.
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;
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.
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.
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.
// 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>
);
}
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.
Question: Which property is commonly used to access the data returned by an Axios request?