Lesson 11 of 158 – GET Method
11%

GET Method

The GET method is one of the most commonly used HTTP methods in REST API development. It is mainly used to retrieve data from a server.

In a React Native application, GET requests are used when the mobile app needs to read information from a PHP REST API, such as students, users, products, courses, or orders.

Note: GET is generally used for reading data. In a well-designed API, a GET request should not be used to create, update, or delete database records.

1. What is GET?

GET is an HTTP method used to request information from a server.

Example:


GET /api/students

The server receives the request and can return student information.

2. Purpose of GET

The main purpose of GET is to retrieve resources.

For example, a mobile application can use GET to retrieve:

  • Student records
  • User profiles
  • Product lists
  • Course lists
  • Orders
  • Notifications

3. GET and REST API

REST APIs commonly use GET to read resources.


GET /api/students

Here, /api/students represents the student resource.

4. GET All Records

A GET endpoint can return multiple records.


GET /api/students

The server might return:


{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "Rahul"
        },
        {
            "id": 2,
            "name": "Amit"
        }
    ]
}

5. GET a Single Record

GET can also retrieve a specific resource.


GET /api/students/10

Here, 10 can represent the ID of a particular student.

6. GET Request URL

A GET request is sent to an API URL.


https://example.com/api/students

The URL tells the client where the API resource is located.

7. GET with Path Parameter

A path parameter can be used to identify a specific resource.


GET /api/students/25

In this example, 25 can identify the student whose data is required.

8. GET with Query Parameters

Query parameters can be used to filter or customize a GET request.


GET /api/students?course=ReactNative

The server can read the query parameter and return matching records.

9. Multiple Query Parameters

A GET request can contain multiple query parameters.


GET /api/students?course=ReactNative&status=active

The API can use both values when processing the request.

10. GET and Request Body

GET requests are generally designed to retrieve information.

When data needs to be submitted to create or update a resource, POST, PUT, or PATCH is normally used instead.


GET /api/students

Filtering and other request information can commonly be provided through the URL and query parameters.

11. GET Response

After receiving a GET request, the server sends an HTTP response.


HTTP/1.1 200 OK
Content-Type: application/json

{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "Rahul"
        }
    ]
}

12. GET and JSON

REST APIs commonly return JSON data in response to GET requests.


{
    "id": 10,
    "name": "Rahul",
    "course": "React Native"
}

React Native can convert the JSON response into JavaScript or TypeScript data.

13. GET with Fetch API

React Native can use the Fetch API to send a GET request.


fetch("https://example.com/api/students")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    });

14. GET with Async/Await

The Fetch API can also be used with async/await.


const response = await fetch(
    "https://example.com/api/students"
);

const data = await response.json();

console.log(data);

Async/await can make asynchronous API code easier to read.

15. Checking GET Response

The response should be checked before processing the returned data.


const response = await fetch(
    "https://example.com/api/students"
);

if (!response.ok) {
    throw new Error("Request failed");
}

const data = await response.json();

The ok property indicates whether the response status is in the successful range.

16. GET with Loading State

A mobile application often displays a loading indicator while a GET request is being processed.


const [loading, setLoading] = useState(true);

const loadStudents = async () => {

    setLoading(true);

    const response = await fetch(
        "https://example.com/api/students"
    );

    const data = await response.json();

    setLoading(false);
};

17. GET Error Handling

Network problems or server errors can occur during a GET request. Use try/catch to handle errors.


try {

    const response = await fetch(
        "https://example.com/api/students"
    );

    const data = await response.json();

} catch (error) {

    console.log("Network error");

}

18. GET with PHP REST API

A PHP REST API can receive a GET request and read records from MySQL.


GET
   ↓
PHP REST API
   ↓
MySQL SELECT
   ↓
JSON Response

The mobile application receives the JSON response.

19. PHP $_GET

PHP provides $_GET for reading query-string parameters.

Example URL:


/api/students.php?course=ReactNative

PHP can read the parameter:


$course = $_GET['course'] ?? '';

For JSON APIs, the response should then be returned in a suitable JSON structure.

20. GET and MySQL

A PHP GET API can use a SQL SELECT query to retrieve database records.


SELECT id, name, email
FROM students;

The PHP application can convert the database result into JSON and send it to the React Native application.

21. GET All Students Example

A simple PHP API can retrieve all students using PDO.


$stmt = $pdo->query(
    "SELECT id, name, email FROM students"
);

$students = $stmt->fetchAll(
    PDO::FETCH_ASSOC
);

header("Content-Type: application/json");

echo json_encode([
    "success" => true,
    "data" => $students
]);

This JSON response can be consumed by React Native.

22. GET One Student Example

An API can retrieve one student using an ID.


GET /api/students.php?id=10

PHP can read the ID and use a prepared SQL statement.


$id = (int)($_GET['id'] ?? 0);

$stmt = $pdo->prepare(
    "SELECT id, name, email
     FROM students
     WHERE id = ?"
);

$stmt->execute([$id]);

$student = $stmt->fetch(
    PDO::FETCH_ASSOC
);

23. GET and FlatList

React Native commonly uses FlatList to display a list returned by a GET API.


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

The API response can be stored in state and passed to FlatList.

24. GET with Axios

Axios is another popular way to make GET requests.


import axios from "axios";

const response = await axios.get(
    "https://example.com/api/students"
);

console.log(response.data);

Axios can simplify many common HTTP operations.

25. GET with Authentication

Some GET endpoints are public, while others require authentication.

A protected GET request can include an authorization token in the request headers.


fetch("https://example.com/api/profile", {
    headers: {
        "Authorization": "Bearer YOUR_TOKEN"
    }
});

26. GET and Pagination

When an API contains many records, pagination can be used to return a smaller set of results at a time.

Example:


GET /api/students?page=1&limit=10

This allows the mobile application to request a particular page of data.

27. GET and Search

Query parameters can also be used for searching.


GET /api/students?search=Rahul

The PHP API can use the search value to retrieve matching records from MySQL.

28. GET Request Flow


React Native
      ↓
GET Request
      ↓
PHP REST API
      ↓
Validate Request
      ↓
MySQL SELECT
      ↓
PHP
      ↓
JSON Response
      ↓
React Native
      ↓
Display Data

This is the basic flow that will be used in our mobile application projects.

29. Common GET Mistakes

  • Using the wrong API URL.
  • Using POST when only data retrieval is required.
  • Ignoring HTTP response status.
  • Not handling network errors.
  • Forgetting to parse JSON.
  • Not showing a loading state in the mobile app.
  • Returning inconsistent JSON structures.
  • Building SQL queries directly from untrusted input.

Use prepared statements and validate input on the server.

30. Complete GET Concept

A GET request allows a React Native application to request data from a REST API.


React Native
      ↓
GET /api/students
      ↓
PHP REST API
      ↓
MySQL SELECT
      ↓
JSON Response
      ↓
React Native
      ↓
FlatList
      ↓
Student List

GET is one of the most important methods for building mobile applications because mobile apps frequently need to retrieve data from backend servers.

📌 Key Points

  • GET is used to retrieve resources.
  • GET is commonly used for reading data.
  • A GET request contains an API URL.
  • Path parameters can identify a specific resource.
  • Query parameters can filter or customize a request.
  • GET responses commonly contain JSON data.
  • React Native can send GET requests using Fetch or Axios.
  • PHP can process GET requests and retrieve data from MySQL.
  • HTTP status codes should be checked by the mobile application.
  • Loading and error states should be handled in React Native.
  • GET can be used for search and pagination.
  • Protected GET endpoints can require authentication.
  • Prepared statements should be used when querying MySQL.

🧠 Quick Quiz

Question: Which HTTP method is primarily used to retrieve data from a REST API?