In the previous lesson, we learned how to use the PUT method to update an existing student. Now we will learn about the HTTP PATCH method and create a PHP PATCH API for updating selected fields of a student.
The HTTP PATCH method is commonly used to partially update an existing resource.
For example, if a student only changes their mobile number, there is no need to send every student field.
PATCH Request
↓
PHP REST API
↓
Update Selected Fields
↓
MySQL
| Method | Common Use |
|---|---|
| PUT | Update or replace the resource representation |
| PATCH | Partially update the resource |
PATCH is especially useful when only one or a few fields need to be changed.
Suppose the existing student record is:
{
"id": 1,
"name": "Rahul Kumar",
"email": "rahul@example.com",
"mobile": "9876543210",
"course": "PHP"
}
The student only wants to change the mobile number.
{
"id": 1,
"mobile": "9999999999"
}
This is a good use case for PATCH.
We can use the student API endpoint for the PATCH request.
http://localhost/rest_api/api/students.php
The JSON body contains the ID and only the fields that need to be updated.
PHP provides the HTTP method through $_SERVER['REQUEST_METHOD'].
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'PATCH') {
// Partial update
}
header("Content-Type: application/json");
The API uses JSON for both request and response data.
The PATCH API needs a PDO connection to update the MySQL database.
require_once "../config/database.php";
The request body can be read using php://input.
$input = file_get_contents("php://input");
The result contains the raw JSON sent by the client.
$data = json_decode(
file_get_contents("php://input"),
true
);
The JSON is converted into a PHP associative array.
The ID identifies which student should be updated.
$id = filter_var(
$data['id'] ?? null,
FILTER_VALIDATE_INT
);
The ID should be validated before performing the database operation.
if (!$id || $id <= 0) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Valid student ID is required"
]);
exit;
}
The API cannot update a student if it does not know which student to modify.
Unlike a complete update, PATCH fields can be optional.
For example, the client may send only:
{
"id": 1,
"mobile": "9999999999"
}
The name, email, and course do not need to be sent.
We can check which fields are present in the request.
$fields = [];
if (array_key_exists('name', $data)) {
$fields['name'] = trim($data['name']);
}
if (array_key_exists('email', $data)) {
$fields['email'] = trim($data['email']);
}
if (array_key_exists('mobile', $data)) {
$fields['mobile'] = trim($data['mobile']);
}
if (array_key_exists('course', $data)) {
$fields['course'] = trim($data['course']);
}
This allows the API to update only the fields supplied by the client.
The API should reject a PATCH request if no updateable field was supplied.
if (empty($fields)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "No fields provided for update"
]);
exit;
}
If the name was supplied, it should not be empty.
if (
array_key_exists('name', $fields) &&
$fields['name'] === ''
) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name cannot be empty"
]);
exit;
}
If the email field is supplied, validate its format.
if (
array_key_exists('email', $fields) &&
!filter_var(
$fields['email'],
FILTER_VALIDATE_EMAIL
)
) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid email address"
]);
exit;
}
Because PATCH allows different fields to be updated, the SQL UPDATE query can be built from the fields that were supplied.
$setParts = [];
$values = [];
foreach ($fields as $column => $value) {
$setParts[] = "$column = ?";
$values[] = $value;
}
The query can then be created using these update fields.
The student ID is required for the WHERE condition.
$values[] = $id;
$sql = "UPDATE students SET "
. implode(", ", $setParts)
. " WHERE id = ?";
The last placeholder receives the student ID.
$stmt = $pdo->prepare($sql);
The query is prepared before the values are supplied.
Prepared statements help keep client-provided values separate from the SQL command.
$stmt->execute($values);
The supplied field values and student ID are passed to the prepared statement.
<?php
header("Content-Type: application/json");
require_once "../config/database.php";
$data = json_decode(
file_get_contents("php://input"),
true
);
if (!is_array($data)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid JSON data"
]);
exit;
}
$id = filter_var(
$data['id'] ?? null,
FILTER_VALIDATE_INT
);
if (!$id || $id <= 0) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Valid student ID is required"
]);
exit;
}
$fields = [];
if (array_key_exists('name', $data)) {
$fields['name'] = trim($data['name']);
}
if (array_key_exists('email', $data)) {
$fields['email'] = trim($data['email']);
}
if (array_key_exists('mobile', $data)) {
$fields['mobile'] = trim($data['mobile']);
}
if (array_key_exists('course', $data)) {
$fields['course'] = trim($data['course']);
}
if (empty($fields)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "No fields provided for update"
]);
exit;
}
if (
array_key_exists('email', $fields) &&
!filter_var(
$fields['email'],
FILTER_VALIDATE_EMAIL
)
) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid email address"
]);
exit;
}
$setParts = [];
$values = [];
foreach ($fields as $column => $value) {
$setParts[] = "$column = ?";
$values[] = $value;
}
$values[] = $id;
$sql = "UPDATE students SET "
. implode(", ", $setParts)
. " WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute($values);
http_response_code(200);
echo json_encode([
"success" => true,
"message" => "Student updated successfully"
]);
?>
The database operation should be placed inside a try-catch block.
try {
$stmt = $pdo->prepare($sql);
$stmt->execute($values);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode([
"success" => false,
"message" => "Database error"
]);
exit;
}
Open Postman and select the PATCH method.
PATCH
http://localhost/rest_api/api/students.php
Go to:
Body → raw → JSON
To update only the mobile number, send:
{
"id": 1,
"mobile": "9999999999"
}
Only the mobile column needs to be updated.
PATCH can also update multiple selected fields.
{
"id": 1,
"name": "Rahul Kumar",
"course": "React Native"
}
Only the name and course fields are changed.
After the PATCH request, use the Get Single API to verify the updated record.
GET
http://localhost/rest_api/api/student.php?id=1
The response should contain the updated values.
React Native / Postman
↓
PATCH Request
↓
JSON Body
↓
Read ID
↓
Detect Supplied Fields
↓
Validate Data
↓
Build UPDATE Query
↓
PDO
↓
MySQL
↓
JSON Response
React Native can use PATCH when only part of a student profile needs to be updated.
fetch("http://localhost/rest_api/api/students.php", {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
id: 1,
mobile: "9999999999"
})
});
The API receives only the field that needs to change.
Only allow known database columns to be updated. Never use arbitrary keys from the client directly as SQL column names.
$allowedFields = [
'name',
'email',
'mobile',
'course'
];
Using an allow-list ensures that clients can update only fields that the API has explicitly permitted.
The PATCH API is useful when only selected fields of an existing student need to be updated. PHP reads the JSON body, validates the student ID and supplied fields, builds an UPDATE query for the permitted fields, executes it using PDO, and returns a JSON response.
PATCH
↓
JSON Body
↓
Validate ID
↓
Find Supplied Fields
↓
UPDATE Selected Columns
↓
MySQL
↓
JSON Response
Question: Which HTTP method is commonly used for a partial update of an existing resource?