Lesson 96 of 158 – React Native REST API
61%

React Native REST API

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.

Note: In this section, we will connect React Native with the REST APIs created using PHP and MySQL. You will learn how to send requests, receive JSON, display API data, handle loading and errors, and build mobile applications using real backend data.

1. What is a REST API in React Native?

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

2. Why Does a Mobile App Need an API?

A mobile application normally should not connect directly to a production MySQL database. Instead, it communicates with a backend API.

  • API handles database operations
  • API validates data
  • API handles authentication
  • API applies authorization
  • API provides JSON data
  • API protects database credentials

3. React Native and PHP API Architecture

React Native
     |
     | HTTP
     ↓
PHP REST API
     |
     | SQL
     ↓
MySQL Database

React Native is the client and PHP/MySQL acts as the backend.

4. API Base URL

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`;

5. Using fetch() in React Native

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);

6. GET Request

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);

7. GET Request with HTTP Method

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.

8. Reading JSON Response

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);

9. Standard API Response

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"
        }
    ]
}

10. Checking API Success

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.

11. Checking HTTP Status

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");
}

12. response.ok

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);

}

13. POST Request

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);

14. Content-Type Header

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.

15. JSON.stringify()

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);

16. Sending Form Data to PHP

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.

17. PUT Request

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);

18. DELETE Request

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);

19. API Loading State

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);

    }
}

20. Handling API Errors

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.

21. Displaying API Data

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);
    }
}

22. Displaying Students with FlatList

<FlatList
    data={students}
    keyExtractor={(item) =>
        item.id.toString()
    }
    renderItem={({ item }) => (
        <Text>
            {item.name}
        </Text>
    )}
/>

FlatList is useful for displaying larger lists of API records.

23. useEffect for API Loading

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.

24. API Authentication

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.

25. API Search from React Native

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);

26. API Pagination

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.

27. Reusable API Function

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.

28. API Service File

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.

29. Complete React Native API Flow

React Native Screen
        ↓
API Service Function
        ↓
fetch()
        ↓
PHP REST API
        ↓
Authentication
        ↓
Validation
        ↓
MySQL
        ↓
JSON Response
        ↓
React Native State
        ↓
Mobile UI

30. Complete Student API Example

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.

📌 Key Points

  • React Native communicates with PHP REST APIs using HTTP requests.
  • REST APIs normally exchange data using JSON.
  • Use GET to retrieve data.
  • Use POST to create or submit data.
  • Use PUT or PATCH to update data.
  • Use DELETE to remove data.
  • Use response.json() to read JSON responses.
  • Use loading and error states in mobile screens.
  • Use JWT authentication for protected APIs.
  • Use FlatList to display API lists efficiently.
  • Search and pagination can be implemented using query parameters.
  • Keep reusable API functions in a service file.
  • Never connect the React Native production app directly to MySQL.

🧠 Quick Quiz

Question: Which JavaScript function is commonly used in React Native to send HTTP requests to a REST API?