Lesson 60 of 158 – PHP PATCH API
60%

PHP PATCH API

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.

Note: PUT is commonly used when replacing or updating a resource, while PATCH is commonly used for a partial update where only the fields that need to change are sent.

1. What is the PATCH Method?

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

2. PATCH vs PUT

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.

3. Example of Partial Update

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.

4. PATCH API Endpoint

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.

5. Check the Request Method

PHP provides the HTTP method through $_SERVER['REQUEST_METHOD'].

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'PATCH') {

    // Partial update

}

6. Set JSON Response Header

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

The API uses JSON for both request and response data.

7. Include PDO Connection

The PATCH API needs a PDO connection to update the MySQL database.

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

8. Read PATCH Request Body

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.

9. Decode PATCH JSON

$data = json_decode(
    file_get_contents("php://input"),
    true
);

The JSON is converted into a PHP associative array.

10. Get Student ID

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.

11. Validate Student ID

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.

12. Optional Fields in PATCH

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.

13. Detect Supplied Fields

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.

14. Check Whether Fields Were Supplied

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

15. Validate Optional Name

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

16. Validate Optional Email

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

17. Build the UPDATE Query

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.

18. Add the Student ID

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.

19. Prepare the PATCH Query

$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.

20. Execute the PATCH Query

$stmt->execute($values);

The supplied field values and student ID are passed to the prepared statement.

21. Complete Basic PATCH API

<?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"
]);

?>

22. Handle Database Errors

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

23. Test PATCH in Postman

Open Postman and select the PATCH method.

PATCH

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

Go to:

Body → raw → JSON

24. Send One Field

To update only the mobile number, send:

{
    "id": 1,
    "mobile": "9999999999"
}

Only the mobile column needs to be updated.

25. Send Multiple Fields

PATCH can also update multiple selected fields.

{
    "id": 1,
    "name": "Rahul Kumar",
    "course": "React Native"
}

Only the name and course fields are changed.

26. Verify the PATCH Update

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.

27. PATCH API Flow

React Native / Postman
        ↓
PATCH Request
        ↓
JSON Body
        ↓
Read ID
        ↓
Detect Supplied Fields
        ↓
Validate Data
        ↓
Build UPDATE Query
        ↓
PDO
        ↓
MySQL
        ↓
JSON Response

28. PATCH with React Native

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.

29. Important Security Practice

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.

30. PHP PATCH API Summary

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

📌 Key Points

  • PATCH is commonly used for partial updates.
  • PUT and PATCH can both modify existing resources, but PATCH is useful when only selected fields need to change.
  • PATCH data can be sent as JSON.
  • php://input reads the raw request body.
  • json_decode() converts JSON into PHP data.
  • The student ID identifies the record to update.
  • PATCH can update only the fields supplied by the client.
  • Dynamic UPDATE queries should use a controlled allow-list of columns.
  • PDO prepared statements should be used for database values.
  • HTTP 200 can indicate a successful update.
  • HTTP 400 can be used for invalid input.
  • HTTP 500 can be used for database or server errors.
  • React Native can send PATCH requests using Fetch or Axios.

🧠 Quick Quiz

Question: Which HTTP method is commonly used for a partial update of an existing resource?