Backend Development

What Is the Difference Between PUT and PATCH? A Beginner-Friendly Guide

When building REST APIs with Node.js and Express.js, you will frequently work with HTTP methods such as GET, POST, PUT, PATCH, and DELETE.Most developers…

D
DevByteTechnical Author
Published
10 min read0 views
What Is the Difference Between PUT and PATCH? A Beginner-Friendly Guide

When building REST APIs with Node.js and Express.js, you will frequently work with HTTP methods such as GET, POST, PUT, PATCH, and DELETE.

Most developers understand that GET retrieves data and POST creates new resources. But when it comes to PUT and PATCH, things can become confusing.

Both methods are commonly used to update existing resources. So, what is the actual difference between them? When should you use PUT, and when is PATCH the better choice?

In this guide, we will explore the differences between PUT and PATCH, understand how they work, and implement both methods using practical Node.js and Express.js examples.

1. What Is PUT in REST APIs?

The HTTP PUT method is used to create or replace the state of a resource at a specific URL.

When updating an existing resource, PUT generally represents replacing the resource with the new representation provided in the request body.

For example, imagine you have a user resource in your database:

{
  "id": 101,
  "name": "Manjeet",
  "email": "manjeet@example.com",
  "age": 25
}

Now, suppose you want to update this user's information using PUT.

Your request might look like this:

PUT /api/users/101
Content-Type: application/json

Request body:

{
  "name": "Manjeet Kumar",
  "email": "manjeet@example.com",
  "age": 26
}

The server uses the submitted representation to replace the existing user resource.

How Does PUT Work?

The typical process looks like this:

  1. The client sends a PUT request to the resource URL.

  2. The request contains the new representation of the resource.

  3. The server validates the submitted data.

  4. The server replaces or updates the resource according to the API's defined semantics.

  5. The server returns an appropriate HTTP response.

Important: Under the HTTP standard, PUT requests are intended to replace the target resource's state. However, the exact fields required and how the server handles omitted properties depend on the API's resource model and implementation.

For a conventional full-replacement API, you should send all fields required to represent the resource rather than assuming omitted fields will remain unchanged.

2. What Is PATCH in REST APIs?

The HTTP PATCH method is used to apply partial modifications to an existing resource.

Unlike a typical full-replacement PUT request, PATCH allows you to submit only the fields you want to change.

Let's use the same user example:

{
  "id": 101,
  "name": "Manjeet",
  "email": "manjeet@example.com",
  "age": 25
}

Suppose the user wants to update only their age.

You can send a PATCH request:

PATCH /api/users/101
Content-Type: application/json

Request body:

{
  "age": 26
}

The server applies the requested modification while preserving the other fields.

The updated resource becomes:

{
  "id": 101,
  "name": "Manjeet",
  "email": "manjeet@example.com",
  "age": 26
}

Notice that you did not need to send the user's name or email again.

How Does PATCH Work?

The typical process is:

  1. The client sends a PATCH request.

  2. The request contains the intended changes.

  3. The server validates the requested modifications.

  4. The server applies those changes to the resource.

  5. The server returns an appropriate response.

One important detail is that PATCH does not automatically mean "merge every JSON field." The server must define how the patch document is interpreted. For example, it might accept a simple JSON object of fields to update or use a standard format such as JSON Merge Patch or JSON Patch.

3. PUT vs PATCH: Key Differences

Although both methods can update resources, their intended semantics differ.

Feature

PUT

PATCH

Main purpose

Replace a resource's state

Apply partial modifications

Request body

Usually contains the complete resource representation

Contains the changes to apply

Partial updates

Possible, but generally not the intended use for replacement-style APIs

Primary use case

Omitted fields

May be removed or reset in a replacement-style API

Usually remain unchanged when using a simple partial-update object

Idempotent

Yes, according to HTTP semantics

Not guaranteed; depends on the patch operation

Typical use case

Replace a user's profile

Update only a user's email or age

HTTP method safety

Not safe

Not safe

Let's understand the two most important differences in more detail.

Difference 1: Full Replacement vs Partial Update

The primary difference is how the request modifies the resource.

With PUT, the client generally sends a complete representation of the resource it wants the server to store.

With PATCH, the client sends only the modifications it wants to apply.

For example, if you want to update only a user's email address, a typical PATCH request would be:

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

With a full-replacement PUT endpoint, you would normally send the other required fields as well.

Difference 2: Idempotency

Idempotency is another important concept when working with HTTP methods.

An operation is idempotent if repeating the same request produces the same intended result as sending it once.

For example, consider this PUT request:

PUT /api/users/101
{
  "name": "Manjeet Kumar",
  "email": "manjeet@example.com",
  "age": 26
}

Sending the same request multiple times leaves the resource in the same intended state, assuming the same request is processed successfully and the endpoint follows normal PUT semantics.

Therefore, PUT is defined as idempotent by HTTP.

What about PATCH?

A PATCH request can also be idempotent, but it is not guaranteed to be.

For example, setting a user's age to a specific value is naturally idempotent:

{
  "age": 26
}

Repeating this operation leaves the age at 26.

However, a patch operation that increments an account balance by 100 could produce a different result every time it is repeated.

Remember: PUT is idempotent by definition. PATCH may be idempotent or non-idempotent depending on the patch instructions and implementation.

4. Implementing PUT and PATCH in Express.js

Now let's see how these methods work in a real Node.js application.

For simplicity, we will store user data in an array. In a production application, you would normally use a database such as MongoDB or PostgreSQL.

Step 1: Set Up Express.js

First, install Express:

npm init -y
npm install express

Create an index.js file:

const express = require("express");

const app = express();

app.use(express.json());

const users = [
  {
    id: 1,
    name: "Manjeet",
    email: "manjeet@example.com",
    age: 25,
  },
];

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

Here, express.json() parses incoming JSON request bodies.

Step 2: Create a PUT Endpoint

Let's implement a PUT endpoint that replaces the editable fields of an existing user.

app.put("/api/users/:id", (req, res) => {
  const userId = Number(req.params.id);

  const userIndex = users.findIndex(
    (user) => user.id === userId
  );

  if (userIndex === -1) {
    return res.status(404).json({
      message: "User not found",
    });
  }

  const { name, email, age } = req.body;

  if (
    typeof name !== "string" ||
    typeof email !== "string" ||
    typeof age !== "number"
  ) {
    return res.status(400).json({
      message: "Name, email, and age are required",
    });
  }

  users[userIndex] = {
    id: userId,
    name,
    email,
    age,
  };

  return res.status(200).json({
    message: "User replaced successfully",
    user: users[userIndex],
  });
});

In this example:

  • req.params.id identifies the user.

  • findIndex() locates the existing user.

  • The request body must contain all three editable fields.

  • The existing editable fields are replaced with the submitted values.

  • The server returns the updated user.

This example intentionally implements a full-replacement style endpoint for the editable fields. The id remains controlled by the URL rather than being replaced by a value from the request body.

If the user does not exist, the API returns a 404 Not Found response.

If required fields are missing or have the wrong types, it returns a 400 Bad Request response.

Step 3: Create a PATCH Endpoint

Now let's create a PATCH endpoint that updates only the supplied fields.

app.patch("/api/users/:id", (req, res) => {
  const userId = Number(req.params.id);

  const user = users.find(
    (user) => user.id === userId
  );

  if (!user) {
    return res.status(404).json({
      message: "User not found",
    });
  }

  const allowedFields = ["name", "email", "age"];
  const updates = req.body;

  if (
    !updates ||
    typeof updates !== "object" ||
    Array.isArray(updates) ||
    Object.keys(updates).length === 0
  ) {
    return res.status(400).json({
      message: "Provide at least one field to update",
    });
  }

  const invalidFields = Object.keys(updates).filter(
    (field) => !allowedFields.includes(field)
  );

  if (invalidFields.length > 0) {
    return res.status(400).json({
      message: "Invalid fields provided",
      invalidFields,
    });
  }

  if (
    "name" in updates &&
    typeof updates.name !== "string"
  ) {
    return res.status(400).json({
      message: "Name must be a string",
    });
  }

  if (
    "email" in updates &&
    typeof updates.email !== "string"
  ) {
    return res.status(400).json({
      message: "Email must be a string",
    });
  }

  if (
    "age" in updates &&
    typeof updates.age !== "number"
  ) {
    return res.status(400).json({
      message: "Age must be a number",
    });
  }

  Object.assign(user, updates);

  return res.status(200).json({
    message: "User updated successfully",
    user,
  });
});

This endpoint checks that the request contains at least one allowed field, validates the supplied values, and applies the changes to the existing user.

For example, send this request:

PATCH /api/users/1
Content-Type: application/json
{
  "age": 26
}

The server changes the user's age without modifying the name or email.

Production tip: In a real application, use a validation library such as Joi or Zod, validate route parameters, and update only explicitly permitted fields. With MongoDB and Mongoose, construct an update object from validated fields rather than passing untrusted request data directly to a database update operation.

5. When Should You Use PUT or PATCH?

Choosing between PUT and PATCH depends on the operation your API needs to perform.

Use PUT When:

  • You want to replace the resource's current representation.

  • The client can provide the complete resource representation.

  • You want repeated requests to set the same intended resource state.

  • Your API defines a full-replacement update operation.

Example:

PUT /api/products/10

You are replacing the product's editable details with the submitted representation.

Use PATCH When:

  • You want to update only selected fields.

  • Sending the entire resource would be unnecessary.

  • Your application has forms that modify individual fields.

  • You want to update a user's status, email, or profile picture independently.

Example:

PATCH /api/users/1
{
  "email": "updated@example.com"
}

Only the email address needs to change.

What About Updating Data in MongoDB?

In a MERN stack application, you will often use PATCH for partial updates.

For example, with Mongoose:

const updatedUser = await User.findByIdAndUpdate(
  req.params.id,
  { $set: req.body },
  {
    new: true,
    runValidators: true,
  }
);

This demonstrates the basic MongoDB update operation, but you should not pass req.body directly in production. First validate the input and build an object containing only the fields your API permits users to modify.

For example:

const updates = {};

if (typeof req.body.name === "string") {
  updates.name = req.body.name;
}

if (typeof req.body.email === "string") {
  updates.email = req.body.email;
}

if (typeof req.body.age === "number") {
  updates.age = req.body.age;
}

const updatedUser = await User.findByIdAndUpdate(
  req.params.id,
  { $set: updates },
  {
    new: true,
    runValidators: true,
  }
);

This is still a simplified example. A production implementation should reject invalid input, handle empty updates, validate the ID, and return 404 when the user does not exist.

Also, note that findByIdAndUpdate() updates the database directly. It does not automatically make the endpoint a PUT or PATCH endpoint; that depends on the HTTP route and the semantics you implement.

6. Common Mistakes to Avoid

When working with PUT and PATCH, keep these mistakes in mind.

1. Treating both methods as identical

Both can change resource data, but their intended semantics are different. Use the method that accurately describes the operation.

2. Assuming PATCH automatically preserves every omitted field

A simple partial-update API usually preserves omitted fields, but the server must implement that behavior. The patch format determines how modifications are applied.

3. Forgetting validation

Never assume that data received from the client is valid. Validate field types, allowed fields, required fields, and business rules before updating the database.

4. Allowing users to update protected fields

Fields such as role, isAdmin, and internal account identifiers should not be freely modifiable just because the client includes them in a request.

5. Confusing idempotency with success

Idempotency describes the intended effect of repeating a request. It does not guarantee that every request succeeds, nor does it mean that every response must be identical.

Conclusion

Both PUT and PATCH are important HTTP methods for updating resources in REST APIs, but they serve different purposes.

Use PUT when you want to replace a resource's state, and use PATCH when you want to apply partial modifications.

In a Node.js and Express.js application, choosing the correct method makes your API easier to understand, maintain, and use. Regardless of which method you choose, validate incoming data, restrict updates to allowed fields, and handle errors consistently.

Once you understand the difference between these methods, designing clean and predictable REST APIs becomes much easier.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘