Lesson 13 of 158 – PUT Method
13%

PUT Method

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

For example, if a student changes their name, email, or course information, a React Native application can send a PUT request to the server to update the student's existing record.

Note: PUT is commonly used when the client wants to update an existing resource. In REST API design, PUT generally represents a complete replacement or update of a resource.

1. What is PUT?

PUT is an HTTP method used to update an existing resource on a server.

Example:


PUT /api/students/10

Here, 10 can represent the ID of the student that needs to be updated.

2. Purpose of PUT

The main purpose of PUT in a REST API is to update or replace an existing resource.

Examples include:

  • Updating a student
  • Updating a user profile
  • Updating product information
  • Updating course information
  • Updating an order

3. PUT and REST API

A REST API commonly uses PUT when an existing resource needs to be updated.


PUT /api/students/10

The endpoint identifies the resource, while the request body contains the new values.

4. PUT Request Body

A PUT request commonly contains the updated resource data in the request body.


{
    "name": "Rahul Kumar",
    "email": "rahul@example.com",
    "course": "React Native"
}

The server receives the data and updates the corresponding resource.

5. PUT and JSON

JSON is commonly used to send structured data in a PUT request.


{
    "name": "Amit Kumar",
    "email": "amit@example.com",
    "mobile": "9876543210"
}

The API reads the JSON data and uses it to update the resource.

6. PUT URL and Resource ID

A PUT request commonly includes the ID of the resource being updated.


PUT /api/students/25

In this example, 25 identifies the student that should be updated.

7. PUT Request Example

A complete PUT request can look like this:


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

{
    "name": "Rahul Kumar",
    "email": "rahul@example.com"
}

The server can use the ID and submitted data to update the student.

8. Content-Type Header

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


Content-Type: application/json

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

9. PUT Response

After processing a PUT request, the server sends an HTTP response.


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

The response informs the mobile application whether the update was successful.

10. HTTP Status Code 200

A successful PUT request commonly returns the HTTP status code 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. PUT and 204 No Content

An API can also return 204 No Content when an update succeeds but there is no response body to return.


HTTP/1.1 204 No Content

The exact response status depends on the API design.

12. PUT with React Native Fetch

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


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

const data = await response.json();

console.log(data);

13. PUT with Async/Await

Async/await makes PUT request code easier to understand.


const updateStudent = async () => {

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

    const data = await response.json();

    console.log(data);
};

14. PUT Error Handling

PUT requests should handle network and server errors.


try {

    const response = await fetch(
        "https://example.com/api/students/10",
        {
            method: "PUT",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                name: "Rahul Kumar"
            })
        }
    );

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

    const data = await response.json();

} catch (error) {

    console.log(error);

}

15. Updating Form Data

A React Native edit screen can collect updated information and send it to the API using PUT.

For example:

  • Student name
  • Email address
  • Mobile number
  • Course

After the user presses the update button, the application can send the new values to the server.

16. PUT with PHP REST API

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


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

The decoded values can then be validated and used in an UPDATE query.

17. Reading PUT JSON in PHP

Suppose React Native sends the following JSON:


{
    "name": "Rahul Kumar",
    "email": "rahul@example.com"
}

PHP can read the values:


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

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

18. PUT and MySQL UPDATE

After validating the submitted data, PHP can update a MySQL record.


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

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

Prepared statements should be used when working with user-supplied values.

19. Finding the Resource Before Update

Before updating a resource, the API can verify that the requested ID exists.


SELECT id
FROM students
WHERE id = ?

If the record does not exist, the API can return an appropriate error response instead of performing the update.

20. Complete PHP PUT Flow


PUT 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 updating an existing resource using PUT.

21. PUT 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"
]);

React Native can use this response to update the user interface.

22. PUT Validation

Server-side validation should be performed before updating a resource.

The API can check:

  • Whether the ID is valid
  • Whether the record exists
  • Required fields
  • Email format
  • Mobile number format
  • Valid course information
  • Whether submitted values are acceptable

The mobile application should not be the only place where validation is performed.

23. PUT with Axios

Axios provides a convenient method for sending PUT requests.


import axios from "axios";

const response = await axios.put(
    "https://example.com/api/students/10",
    {
        name: "Rahul Kumar",
        email: "rahul@example.com"
    }
);

console.log(response.data);

24. PUT and Postman

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

In Postman:

  1. Select the PUT method.
  2. Enter the API URL.
  3. Include the resource ID in the URL.
  4. Open the Body section.
  5. Select raw.
  6. Select JSON.
  7. Enter the updated data.
  8. Click Send.

25. PUT and Authentication

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

A token can be sent through the Authorization header.


fetch("https://example.com/api/students/10", {
    method: "PUT",
    headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer YOUR_TOKEN"
    },
    body: JSON.stringify({
        name: "Rahul Kumar"
    })
});

26. PUT vs POST

POST PUT
Commonly creates a resource Commonly updates a resource
Example: POST /students Example: PUT /students/10
Usually does not require an existing resource ID for creation Usually identifies an existing resource
Used for submitting new data Used for updating existing data

27. PUT vs PATCH

PUT and PATCH are both used for updating resources, but they can represent different update semantics.

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

28. PUT in a Student Management App

A React Native student management application can use PUT for updating student information.

Example:


PUT /api/students/15

{
    "name": "Amit Kumar",
    "email": "amit@example.com",
    "mobile": "9876543210",
    "course": "React Native"
}

After the server updates the record, the mobile application can refresh the student information.

29. Common PUT Mistakes

  • Using the wrong resource ID.
  • Forgetting to specify the PUT method.
  • Forgetting the Content-Type header.
  • Sending invalid JSON.
  • Forgetting JSON.stringify() when using Fetch.
  • Not checking whether the resource exists.
  • Not validating submitted data.
  • Using unsafe SQL queries.
  • Ignoring the server response.
  • Not handling network errors.

30. Complete PUT Concept

PUT is an important HTTP method for updating existing resources in a REST API.


React Native
      ↓
PUT /api/students/10
      ↓
PHP REST API
      ↓
Read JSON
      ↓
Validate Data
      ↓
Check Student
      ↓
MySQL UPDATE
      ↓
JSON Response
      ↓
React Native

The mobile application sends the resource ID and updated data. The PHP REST API validates the request, updates the MySQL record, and returns a JSON response.

📌 Key Points

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

🧠 Quick Quiz

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