Lesson 55 of 158 – Get Single Record API
55%

Get Single Record API

In the previous lesson, we created a GET API to retrieve all student records. Now we will learn how to retrieve one specific student using the student's ID.

Note: A Get Single Record API is useful when we need the details of one particular record instead of downloading all records.

1. What is a Get Single API?

A Get Single API retrieves one specific record from a database.

For our project, we can retrieve a student using the student's ID.

GET /api/student.php?id=1

The API searches for student ID 1 and returns that student's information.

2. Why Get a Single Record?

Sometimes an application does not need all records. It only needs one specific record.

For example:

  • View one student's profile
  • View one student's details
  • Edit one student
  • Display one product
  • Display one user

3. Query Parameter

We can send the student ID as a query parameter.

http://localhost/rest_api/api/student.php?id=1

Here, id is the parameter name and 1 is its value.

4. Access Query Parameter in PHP

PHP provides query parameters through the $_GET array.

$id = $_GET['id'] ?? null;

If the id parameter is not provided, the value will be null.

5. Check Whether ID Exists

The API should check whether the client has supplied an ID.

if (!$id) {

    echo json_encode([
        "success" => false,
        "message" => "Student ID is required"
    ]);

    exit;
}

6. Convert ID to Integer

If the ID should be numeric, we can convert it to an integer.

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

This ensures that the value is treated as an integer by PHP.

7. Select One Student

We can use a WHERE condition to find one student.

SELECT * FROM students
WHERE id = ?

The question mark is a placeholder for the student ID.

8. Use a Prepared Statement

PDO prepared statements are useful when a value comes from the client.

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

The student ID can then be supplied separately.

9. Execute the Query

Pass the ID to the prepared statement using execute().

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

PDO places the ID into the query parameter.

10. Fetch One Record

Since we need only one student, we can use fetch().

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

The result will contain one student record if the ID exists.

11. Check if Student Exists

If no student has the requested ID, fetch() will return false.

if (!$student) {

    // Student not found

}

This allows us to return a suitable response to the client.

12. Student Not Found Response

If the student does not exist, we can return HTTP status code 404.

http_response_code(404);

echo json_encode([
    "success" => false,
    "message" => "Student not found"
]);

exit;

A 404 status indicates that the requested resource was not found.

13. Successful Response

When the student is found, return the student data.

http_response_code(200);

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

14. Example Success Response

{
    "success": true,
    "data": {
        "id": "1",
        "name": "Rahul",
        "email": "rahul@example.com",
        "mobile": "9876543210",
        "course": "PHP"
    }
}

The client receives one student object instead of an array containing all students.

15. Complete Basic API

<?php

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

require_once "../config/database.php";

$id = $_GET['id'] ?? null;

if (!$id) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Student ID is required"
    ]);

    exit;
}

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

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

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

if (!$student) {

    http_response_code(404);

    echo json_encode([
        "success" => false,
        "message" => "Student not found"
    ]);

    exit;
}

http_response_code(200);

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

?>

16. Validate Numeric ID

We can validate the ID before querying the database.

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

This is useful when the ID is expected to be an integer.

17. Invalid ID Response

If the supplied ID is invalid, return a client error.

if (!$id) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Invalid student ID"
    ]);

    exit;
}

HTTP 400 means the request contains invalid or incorrect input.

18. Select Required Columns

Instead of selecting every column, an API can select only the fields it needs.

SELECT id, name, email, mobile, course
FROM students
WHERE id = ?

This provides better control over the data returned by the API.

19. Use Try-Catch

Database operations can fail, so the API should handle PDO exceptions.

try {

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

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

} catch (PDOException $e) {

    http_response_code(500);

}

20. Return Database Error

If the database operation fails, return a JSON error response.

http_response_code(500);

echo json_encode([
    "success" => false,
    "message" => "Database error"
]);

The client can use the response to handle the failure.

21. Complete Get Single API

<?php

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

require_once "../config/database.php";

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

if (!$id) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Invalid student ID"
    ]);

    exit;
}

try {

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

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

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

    if (!$student) {

        http_response_code(404);

        echo json_encode([
            "success" => false,
            "message" => "Student not found"
        ]);

        exit;
    }

    http_response_code(200);

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

} catch (PDOException $e) {

    http_response_code(500);

    echo json_encode([
        "success" => false,
        "message" => "Database error"
    ]);

}

?>

22. Test with Postman

Open Postman and select the GET method.

GET

http://localhost/rest_api/api/student.php?id=1

Click Send to request student ID 1.

23. Test an Existing Student

If student ID 1 exists, the API should return a successful response.

200 OK

The response body can contain:

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

24. Test a Non-Existing Student

Try an ID that does not exist.

GET

http://localhost/rest_api/api/student.php?id=999

The API should return:

404 Not Found

along with a suitable JSON error message.

25. Missing ID Test

Now try the API without an ID.

GET

http://localhost/rest_api/api/student.php

The API should return an error such as:

400 Bad Request

because the required student ID was not provided.

26. Get Single API Flow

GET Request
     ↓
?id=1
     ↓
PHP reads ID
     ↓
Validate ID
     ↓
Prepared SQL Query
     ↓
SELECT student
     ↓
fetch()
     ↓
JSON Response

27. Get All vs Get Single

API Purpose Example
Get All Retrieve multiple students GET /students.php
Get Single Retrieve one student GET /student.php?id=1

28. React Native Use Case

A React Native application can use the Get Single API when the user taps a student from a list and wants to see the student's complete profile.

Student List
     ↓
Tap Student
     ↓
Student ID
     ↓
GET Single API
     ↓
Student Details Screen

29. Important Security Practice

Always validate input received from the client and use prepared statements for database queries.

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

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

Do not directly concatenate user input into SQL queries.

30. Get Single Record Summary

The Get Single API retrieves one student using an ID supplied by the client. PHP reads and validates the ID, uses a PDO prepared statement to query MySQL, fetches one record, and returns the result as JSON.

GET ?id=1
     ↓
Validate ID
     ↓
Prepared Statement
     ↓
fetch()
     ↓
Student Record
     ↓
JSON Response

📌 Key Points

  • A Get Single API retrieves one specific record.
  • The student ID can be passed as a query parameter.
  • PHP reads query parameters using $_GET.
  • The ID should be validated before using it.
  • PDO prepared statements should be used for database queries.
  • fetch(PDO::FETCH_ASSOC) retrieves one record.
  • HTTP 200 can indicate a successful response.
  • HTTP 400 can indicate invalid input.
  • HTTP 404 can indicate that the requested student was not found.
  • HTTP 500 can indicate a server or database error.
  • The API should return JSON to the client.
  • React Native can use this API to display one student's details.

🧠 Quick Quiz

Question: Which PDO method is commonly used to retrieve one record from the result?