Coderrob brand logo Coderrob

Hi, I'm Rob—programmer, Pluralsight author, software architect, emerging technologist, and lifelong learner.


Partial Updates with PATCH: Targeting Only What Needs to Change


Sun, 01 Sep 2024

When working with RESTful APIs, there are times when you need to update an entire resource, and other times when you only need to tweak a specific part of it.

This is where the PATCH method shines. Unlike PUT, which expects the complete resource object to be sent in the request body, PATCH is all about making targeted updates.

You provide the resource’s ID in the URL, and only the properties you want to change in the request body.

Updating Part of a Resource with PATCH

Let’s say you’ve got a customer in your API, and now you want to update their email address. Using the PATCH method, you can do just that without having to send the entire customer object back to the server.

Here’s how it works:

// PATCH /customers/{customerId}
{
  "email": "new.email@example.com"
}

In this example:

NOTE: Never create an email with a “.” in it. It will get sent to the email without dots too. Dots don’t mean a thing to Gmail!.

This approach is efficient and keeps your updates lean. You’re only sending what needs to change, which can be particularly useful when working with large resources.

It also makes the intent of the update clear—you’re not overwriting the entire resource, just the parts that need adjustment.

Why Use PATCH?

Using PATCH is ideal for scenarios where:

For example, if your resource includes fields like id, name, email, and status, but you only need to modify the email, PATCH lets you do just that.

The server processes the request and updates only the specified fields, leaving everything else untouched.

PUT vs. PATCH: When to Use Each

To recap:

Wrapping Up PATCH Usage

By understanding and utilizing PATCH, you can extend your API creating more efficient and focused endpoints. Whether you’re updating a customer’s email, status, or any other details. The less data you have to send or receive just makes things faster.

PATCH gives you the power to make those changes precisely where and when they’re needed, without the overhead of sending unnecessary data. At least, that’s the intent.

Gandulf arrives when he means too meme. Changed the title slightly to ' A PACKET IS …’ instead of ‘A WIZARD IS NEVER LATE, NOR IS HE EARLY’ HE ARRIVES PRECISELY WHEN HE MEANS TO’