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.
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.
Sometimes an application does not need all records. It only needs one specific record.
For example:
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.
PHP provides query parameters through the $_GET array.
$id = $_GET['id'] ?? null;
If the id parameter is not provided, the value will be null.
The API should check whether the client has supplied an ID.
if (!$id) {
echo json_encode([
"success" => false,
"message" => "Student ID is required"
]);
exit;
}
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.
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.
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.
Pass the ID to the prepared statement using execute().
$stmt->execute([$id]);
PDO places the ID into the query parameter.
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.
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.
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.
When the student is found, return the student data.
http_response_code(200);
echo json_encode([
"success" => true,
"data" => $student
]);
{
"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.
<?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
]);
?>
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.
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.
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.
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);
}
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.
<?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"
]);
}
?>
Open Postman and select the GET method.
GET
http://localhost/rest_api/api/student.php?id=1
Click Send to request student ID 1.
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"
}
}
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.
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.
GET Request
↓
?id=1
↓
PHP reads ID
↓
Validate ID
↓
Prepared SQL Query
↓
SELECT student
↓
fetch()
↓
JSON Response
| API | Purpose | Example |
|---|---|---|
| Get All | Retrieve multiple students | GET /students.php |
| Get Single | Retrieve one student | GET /student.php?id=1 |
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
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.
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
Question: Which PDO method is commonly used to retrieve one record from the result?