Lesson 14 of 158 – PATCH Method
14%

PATCH Method

The PATCH method is an HTTP method commonly used to partially update an existing resource in a REST API.

For example, if a student wants to change only their email address, the mobile application can send a PATCH request containing only the email field instead of sending the complete student record.

Note: PATCH is commonly used when only specific fields of an existing resource need to be changed.

1. What is PATCH?

PATCH is an HTTP method used to partially update an existing resource.


PATCH /api/students/10

Here, 10 can identify the student whose information needs to be partially updated.

2. Purpose of PATCH

The main purpose of PATCH is to modify one or more specific parts of an existing resource.

For example, you may update only:

  • Email address
  • Mobile number
  • Student name
  • Course
  • Status

3. PATCH and REST API

A REST API can use PATCH when the client wants to modify only part of a resource.


PATCH /api/students/10

The request body contains only the fields that need to be changed, depending on the API design.

4. PATCH Request Body

Suppose a student wants to change only their email address.


{
    "email": "newemail@example.com"
}

The API can update only the email field while leaving other student information unchanged.

5. PATCH with Multiple Fields

PATCH can also update more than one field.


{
    "email": "rahul@example.com",
    "mobile": "9876543210"
}

In this example, only the email and mobile values are being changed.

6. PATCH URL and Resource ID

A PATCH endpoint commonly identifies the resource using an ID.


PATCH /api/students/25

The number 25 identifies the resource that needs to be modified.

7. PATCH Request Example

A complete PATCH request can look like this:


PATCH /api/students/25 HTTP/1.1
Content-Type: application/json

{
    "email": "rahul@example.com"
}

Only the email field is being changed in this example.

8. Content-Type Header

When JSON data is sent in a PATCH request, the client commonly sends the following header:


Content-Type: application/json

This tells the server that the request body contains JSON data.

9. PATCH Response

After processing a PATCH request, the server sends a response to the client.


{
    "success": true,
    "message": "Student updated successfully"
}

The response can inform React Native whether the update was successful.

10. HTTP Status Code 200

A successful PATCH request can return 200 OK when the server returns a response body.


HTTP/1.1 200 OK

The response can contain the updated resource or a success message.

11. PATCH and 204 No Content

A server can also return 204 No Content when the update is successful and there is no response body.


HTTP/1.1 204 No Content

The response status used depends on the API design.

12. PATCH with React Native Fetch

React Native can send a PATCH request using the Fetch API.


const response = await fetch(
    "https://example.com/api/students/10",
    {
        method: "PATCH",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            email: "newemail@example.com"
        })
    }
);

const data = await response.json();

console.log(data);

13. PATCH with Async/Await

Async/await makes PATCH request code easier to read.


const updateEmail = async () => {

    const response = await fetch(
        "https://example.com/api/students/10",
        {
            method: "PATCH",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                email: "newemail@example.com"
            })
        }
    );

    const data = await response.json();

    console.log(data);
};

14. PATCH Error Handling

PATCH requests should handle network and server errors.


try {

    const response = await fetch(
        "https://example.com/api/students/10",
        {
            method: "PATCH",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                email: "newemail@example.com"
            })
        }
    );

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

    const data = await response.json();

} catch (error) {

    console.log(error);

}

15. PATCH and Form Editing

PATCH is useful when a mobile application has an edit screen where the user changes only a few fields.

For example:

  • Change email
  • Change mobile number
  • Change profile name
  • Change account status

The application can send only the fields that need to be changed.

16. PATCH with PHP REST API

PHP can receive a PATCH request and read JSON data from the request body.


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

The decoded data can then be validated before updating the database.

17. Reading PATCH JSON in PHP

Suppose React Native sends this JSON:


{
    "email": "newemail@example.com"
}

PHP can read the submitted value:


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

$email = $input['email'] ?? '';

18. PATCH and MySQL UPDATE

After validating the data, PHP can update the selected database field.


$stmt = $pdo->prepare(
    "UPDATE students
     SET email = ?
     WHERE id = ?"
);

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

This example changes only the email column.

19. Checking the Resource

Before updating a resource, the API can check whether the requested record exists.


SELECT id
FROM students
WHERE id = ?

If the record does not exist, the API can return an appropriate error response.

20. Complete PHP PATCH Flow


PATCH Request
      ↓
PHP REST API
      ↓
Read JSON
      ↓
Get Resource ID
      ↓
Validate Data
      ↓
Check Resource
      ↓
MySQL UPDATE
      ↓
JSON Response
      ↓
React Native

This is the basic flow for partially updating a resource.

21. PATCH Response in PHP

After successfully updating a record, PHP can return a JSON response.


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

echo json_encode([
    "success" => true,
    "message" => "Student updated successfully"
]);

The React Native application can use this response to refresh the screen or display a success message.

22. PATCH Validation

The API should validate each field that is included in the PATCH request.

For example:

  • Check whether email is valid.
  • Check whether mobile number is valid.
  • Check whether the resource ID is valid.
  • Check whether the resource exists.
  • Check whether submitted values are acceptable.

Only the submitted fields need to be processed.

23. PATCH with Axios

Axios provides a convenient method for sending PATCH requests.


import axios from "axios";

const response = await axios.patch(
    "https://example.com/api/students/10",
    {
        email: "newemail@example.com"
    }
);

console.log(response.data);

24. PATCH and Postman

Postman can be used to test a PATCH API before connecting it to a React Native application.

In Postman:

  1. Select the PATCH method.
  2. Enter the API URL.
  3. Include the resource ID.
  4. Open the Body section.
  5. Select raw.
  6. Select JSON.
  7. Enter the fields to update.
  8. Click Send.

25. PATCH and Authentication

PATCH endpoints are often protected so that only authorized users can modify resources.

An authentication token can be sent in the Authorization header.


fetch("https://example.com/api/students/10", {
    method: "PATCH",
    headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer YOUR_TOKEN"
    },
    body: JSON.stringify({
        email: "newemail@example.com"
    })
});

26. PATCH vs PUT

PUT PATCH
Commonly represents a complete update or replacement Commonly represents a partial update
Can send the complete resource representation Can send only the fields that need changing
Example: update complete student Example: update only student email
PUT /students/10 PATCH /students/10

27. PATCH vs POST

POST PATCH
Commonly creates a new resource Commonly modifies an existing resource
Example: POST /students Example: PATCH /students/10
Usually submits new resource data Usually submits changes to an existing resource

28. PATCH in a Student Management App

A React Native student management application can use PATCH for small changes to student information.

Example:


PATCH /api/students/15

{
    "mobile": "9876543210"
}

Only the mobile number needs to be changed in this example.

29. Common PATCH Mistakes

  • Using the wrong resource ID.
  • Forgetting to specify PATCH as the method.
  • Forgetting the Content-Type header.
  • Sending invalid JSON.
  • Forgetting JSON.stringify() when using Fetch.
  • Not checking whether the resource exists.
  • Not validating submitted fields.
  • Using unsafe SQL queries.
  • Updating fields that were not intended to change.
  • Ignoring the server response.

30. Complete PATCH Concept

PATCH is an important HTTP method for making partial changes to existing resources in a REST API.


React Native
      ↓
PATCH /api/students/10
      ↓
PHP REST API
      ↓
Read JSON
      ↓
Validate Submitted Fields
      ↓
Check Student
      ↓
MySQL UPDATE
      ↓
JSON Response
      ↓
React Native

The mobile application sends the resource ID and only the fields that need to be changed. The PHP REST API validates the request, updates the required database fields, and returns a JSON response.

📌 Key Points

  • PATCH is commonly used for partial updates.
  • A resource ID is commonly included in the PATCH URL.
  • Only the fields that need changing can be sent.
  • JSON is commonly used for PATCH request data.
  • Content-Type should be set correctly for JSON requests.
  • React Native can send PATCH requests using Fetch or Axios.
  • PHP can read JSON using php://input.
  • PHP can update selected MySQL columns using UPDATE queries.
  • Prepared statements should be used for database operations.
  • The API should validate every submitted field.
  • The API should check whether the requested resource exists.
  • PATCH and PUT can have different update semantics.
  • Postman can be used to test PATCH APIs.
  • Protected PATCH endpoints can require authentication.

🧠 Quick Quiz

Question: Which HTTP method is commonly used to partially update an existing resource?