A GET request is used to retrieve data from a REST API. In React Native, the Fetch API can be used to send a GET request to a PHP/MySQL backend and receive JSON data.
GET is an HTTP method used to retrieve information from a server.
React Native
↓
GET Request
↓
PHP REST API
↓
MySQL
↓
JSON Response
GET requests normally do not modify the server's data.
The simplest GET request uses fetch() with the API URL.
const response = await fetch(
"https://example.com/api/students.php"
);
Since GET is the default fetch method, the method does not have to be specified.
const response = await fetch(
"https://example.com/api/students.php",
{
method: "GET"
}
);
Writing the method explicitly can make the code easier to understand.
After receiving the response, use response.json() to read the JSON data.
const response = await fetch(API_URL);
const result = await response.json();
console.log(result);
Suppose the PHP API returns:
{
"success": true,
"message": "Students retrieved successfully",
"data": [
{
"id": 1,
"name": "Rahul",
"email": "rahul@example.com"
},
{
"id": 2,
"name": "Amit",
"email": "amit@example.com"
}
]
}
const response = await fetch(API_URL);
const result = await response.json();
console.log(result.data);
The data property contains the records returned by the API.
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);
}
}
useEffect() can be used to load data when the screen is opened.
useEffect(() => {
loadStudents();
}, []);
The empty dependency array means the effect runs after the initial render.
async function loadStudents() {
const response = await fetch(
"https://example.com/api/students.php"
);
const result = await response.json();
if (result.success) {
setStudents(result.data);
}
}
response.ok can be used to determine whether the HTTP status represents a successful response.
const response = await fetch(API_URL);
if (!response.ok) {
throw new Error(
`HTTP Error: ${response.status}`
);
}
const result = await response.json();
const response = await fetch(API_URL);
if (response.status === 200) {
const result = await response.json();
console.log(result);
}
HTTP 200 commonly indicates that the GET request was successful.
async function loadStudents() {
try {
const response = await fetch(API_URL);
const result = await response.json();
if (result.success) {
setStudents(result.data);
}
} catch (error) {
console.log(
"Error:",
error.message
);
}
}
A standard API can return an error message.
{
"success": false,
"message": "Unable to retrieve students",
"data": null
}
React Native can read the message:
if (!result.success) {
console.log(result.message);
}
const response = await fetch(
API_URL,
{
method: "GET",
headers: {
"Accept": "application/json"
}
}
);
The Accept header tells the server which response format the client expects.
Protected APIs can require a JWT token.
const response = await fetch(
API_URL,
{
method: "GET",
headers: {
"Accept": "application/json",
"Authorization": `Bearer ${token}`
}
}
);
The PHP API should verify the token before returning protected data.
Query parameters can be added to the URL.
const response = await fetch(
`${API_URL}?course=React%20Native`
);
const result = await response.json();
Query parameters are useful for filtering API results.
const search = "Rahul";
const response = await fetch(
`${API_URL}?search=${encodeURIComponent(search)}`
);
const result = await response.json();
if (result.success) {
setStudents(result.data);
}
encodeURIComponent() helps safely encode user-entered search text.
const page = 1;
const limit = 10;
const search = "Rahul";
const url =
`${API_URL}?page=${page}` +
`&limit=${limit}` +
`&search=${encodeURIComponent(search)}`;
const response = await fetch(url);
const result = await response.json();
URLSearchParams can make query parameter construction easier.
const params = new URLSearchParams({
page: "1",
limit: "10",
search: "Rahul"
});
const response = await fetch(
`${API_URL}?${params.toString()}`
);
const result = await response.json();
const page = 2;
const limit = 10;
const response = await fetch(
`${API_URL}?page=${page}&limit=${limit}`
);
const result = await response.json();
console.log(result.data);
Pagination allows the mobile application to retrieve only a portion of a large dataset.
const response = await fetch(
`${API_URL}?sort=name&order=asc`
);
const result = await response.json();
if (result.success) {
setStudents(result.data);
}
The PHP API should validate allowed sorting columns and directions.
const response = await fetch(
`${API_URL}?status=active`
);
const result = await response.json();
console.log(result.data);
Filtering lets the API return only records matching a condition.
<FlatList
data={students}
keyExtractor={(item) =>
item.id.toString()
}
renderItem={({ item }) => (
<View>
<Text>
{item.name}
</Text>
<Text>
{item.email}
</Text>
</View>
)}
/>
Show an ActivityIndicator while the GET request is running.
{loading ? (
<ActivityIndicator
size="large"
/>
) : (
<FlatList
data={students}
renderItem={renderStudent}
/>
)}
The API may return an empty array when no records are found.
{
"success": true,
"message": "No students found",
"data": []
}
React Native can display a friendly message when the array is empty.
if (students.length === 0) {
console.log("No students found");
}
async function getStudents() {
try {
const response = await fetch(
API_URL
);
const result = await response.json();
if (!response.ok) {
throw new Error(
result.message ||
"Unable to load students"
);
}
return result;
} catch (error) {
throw error;
}
}
Reusable functions keep API code separate from screen components.
async function loadStudents() {
try {
const result =
await getStudents();
if (result.success) {
setStudents(result.data);
}
} catch (error) {
setError(error.message);
}
}
const API_URL =
"https://example.com/api/students.php";
const [students, setStudents] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
async function loadStudents() {
setLoading(true);
setError("");
try {
const response = await fetch(
API_URL,
{
method: "GET",
headers: {
"Accept": "application/json"
}
}
);
const result = await response.json();
if (!response.ok) {
throw new Error(
result.message ||
"Request failed"
);
}
if (result.success) {
setStudents(result.data);
} else {
setError(result.message);
}
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
}
useEffect(() => {
loadStudents();
}, []);
React Native Screen
↓
loadStudents()
↓
fetch()
↓
GET /students.php
↓
PHP REST API
↓
MySQL
↓
JSON Response
↓
response.json()
↓
setStudents()
↓
FlatList
↓
Mobile Screen
GET requests are the foundation for retrieving data from REST APIs. The same pattern can later be extended with authentication, searching, filtering, sorting, pagination, and other API features.
Question: Which HTTP method is normally used to retrieve data from a REST API?