React Native applications usually communicate with a backend server through REST APIs. The mobile application sends HTTP requests to the PHP/MySQL API and receives JSON responses.
A REST API allows a React Native mobile application to communicate with a server.
React Native App
↓
HTTP Request
↓
REST API
↓
PHP
↓
MySQL
↓
JSON Response
↓
React Native App
A mobile application normally should not connect directly to a production MySQL database. Instead, it communicates with a backend API.
React Native
|
| HTTP
↓
PHP REST API
|
| SQL
↓
MySQL Database
React Native is the client and PHP/MySQL acts as the backend.
The API base URL is the common starting address of your backend API.
const API_BASE_URL =
"https://example.com/api";
Individual endpoints can then be created from this base URL.
const STUDENTS_API =
`${API_BASE_URL}/students.php`;
React Native can use the JavaScript fetch() function to make HTTP requests.
const response = await fetch(
"https://example.com/api/students.php"
);
const data = await response.json();
console.log(data);
A GET request is commonly used to retrieve data from the API.
const response = await fetch(
"https://example.com/api/students.php"
);
const result = await response.json();
console.log(result.data);
const response = await fetch(
"https://example.com/api/students.php",
{
method: "GET"
}
);
const result = await response.json();
console.log(result);
GET is the default method for fetch(), but specifying it explicitly can make the code easier for beginners to understand.
The response.json() method converts a JSON response into a JavaScript object.
const response = await fetch(API_URL);
const result = await response.json();
console.log(result.success);
console.log(result.message);
console.log(result.data);
A PHP API may return a standard response such as:
{
"success": true,
"message": "Students retrieved successfully",
"data": [
{
"id": 1,
"name": "Rahul"
},
{
"id": 2,
"name": "Amit"
}
]
}
const response = await fetch(API_URL);
const result = await response.json();
if (result.success) {
console.log("API Success");
console.log(result.data);
} else {
console.log(result.message);
}
A standard response makes API handling easier.
The Fetch API provides the HTTP status through response.status.
const response = await fetch(API_URL);
console.log(response.status);
if (response.status === 200) {
console.log("Success");
}
The response.ok property is true when the HTTP status is in the successful range.
const response = await fetch(API_URL);
if (response.ok) {
const result = await response.json();
console.log(result);
}
POST is used when the React Native application needs to send data to the API.
const response = await fetch(
"https://example.com/api/students.php",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul",
email: "rahul@example.com"
})
}
);
const result = await response.json();
console.log(result);
When sending JSON, use the appropriate Content-Type header.
headers: {
"Content-Type": "application/json"
}
This tells the server that the request body contains JSON data.
JavaScript objects need to be converted into JSON before being sent as a JSON request body.
const student = {
name: "Rahul",
email: "rahul@example.com"
};
const jsonData = JSON.stringify(student);
console.log(jsonData);
The PHP API can read JSON using:
$input = json_decode(
file_get_contents("php://input"),
true
);
$name = $input['name'] ?? '';
$email = $input['email'] ?? '';
React Native and PHP can therefore exchange structured JSON data.
PUT is commonly used to update a resource.
const response = await fetch(
"https://example.com/api/students.php?id=10",
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul Kumar",
email: "rahul@example.com"
})
}
);
const result = await response.json();
console.log(result);
DELETE is used to remove a resource.
const response = await fetch(
"https://example.com/api/students.php?id=10",
{
method: "DELETE"
}
);
const result = await response.json();
console.log(result);
Mobile applications should show a loading indicator while waiting for the API response.
const [loading, setLoading] = useState(false);
async function loadStudents() {
setLoading(true);
try {
const response = await fetch(API_URL);
const result = await response.json();
console.log(result);
} finally {
setLoading(false);
}
}
try {
const response = await fetch(API_URL);
const result = await response.json();
if (!response.ok) {
throw new Error(result.message);
}
console.log(result.data);
} catch (error) {
console.log(error.message);
}
Always handle network and server errors gracefully.
API data can be stored in React state.
const [students, setStudents] = useState([]);
async function loadStudents() {
const response = await fetch(API_URL);
const result = await response.json();
if (result.success) {
setStudents(result.data);
}
}
<FlatList
data={students}
keyExtractor={(item) =>
item.id.toString()
}
renderItem={({ item }) => (
<Text>
{item.name}
</Text>
)}
/>
FlatList is useful for displaying larger lists of API records.
A common pattern is to load API data when a screen opens.
useEffect(() => {
loadStudents();
}, []);
The empty dependency array means the effect runs after the initial render.
Protected APIs usually require an authentication token.
const response = await fetch(API_URL, {
method: "GET",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json"
}
});
The PHP API can verify the JWT before returning protected data.
Query parameters can be used to search API data.
const search = "rahul";
const response = await fetch(
`${API_URL}?search=${encodeURIComponent(search)}`
);
const result = await response.json();
console.log(result.data);
Large datasets should usually be loaded page by page.
const page = 1;
const limit = 10;
const response = await fetch(
`${API_URL}?page=${page}&limit=${limit}`
);
const result = await response.json();
console.log(result.data);
Pagination reduces the amount of data transferred in one request.
Instead of writing fetch code repeatedly, create reusable API functions.
async function getStudents() {
const response = await fetch(
`${API_BASE_URL}/students.php`
);
const result = await response.json();
return result;
}
Reusable functions keep React Native screens cleaner.
API functions can be placed in a separate service directory.
src/
│
├── screens/
│ ├── LoginScreen.js
│ └── StudentScreen.js
│
├── services/
│ └── api.js
│
└── components/
└── StudentCard.js
This keeps API communication separate from UI components.
React Native Screen
↓
API Service Function
↓
fetch()
↓
PHP REST API
↓
Authentication
↓
Validation
↓
MySQL
↓
JSON Response
↓
React Native State
↓
Mobile UI
A basic React Native function can retrieve students from a PHP REST API.
const API_URL =
"https://example.com/api/students.php";
async function loadStudents() {
try {
const response = await fetch(API_URL);
const result = await response.json();
if (!response.ok) {
throw new Error(
result.message || "API request failed"
);
}
if (result.success) {
setStudents(result.data);
} else {
console.log(result.message);
}
} catch (error) {
console.log(
"API Error:",
error.message
);
}
}
This basic pattern can be extended for login, registration, student management, search, pagination, profile management, and other mobile application features.
Question: Which JavaScript function is commonly used in React Native to send HTTP requests to a REST API?