Updating Resources by ID
Learn how to update resources in a NestJS application.
We'll cover the following
Now that we know how to find books by their unique identifier, imagine the scenario where one of our books needs an update. Perhaps the author released a new edition, or there’s a change in its publication details. In this section, we’ll explore the process of updating the information for a specific book using its unique identifier.
The PUT
or PATCH
method
To make an update operation for a resource, such as a book, we often face a decision between two HTTP verbs: PUT
or PATCH
. Let’s provide a brief explanation of these verbs in the context of our use case:
The
PUT
method replaces a resource complete with a new version. When usingPUT
, we send the entire resource representation in the request, effectively replacing the existing resource with the provided data.The
PATCH
method is designed for making partial updates to an existing resource. It allows us to modify specific fields or properties of the resource without requiring the entire representation to be sent. With thePATCH
we can focus on updating only the necessary attributes of thebook
while leaving the remaining fields unchanged.
Considering our goal of updating book information without replacing the entire resource, the PATCH
method aligns more closely with our use case. It enables us to make targeted modifications to specific properties of the book.
Updating BooksController
With this understanding of the difference between PUT
and PATCH
, let’s see how to implement PATCH
in our virtual library application for book updates by following these steps:
Import the
Patch
decorator to specify the HTTP verb for the update route:
Get hands-on with 1400+ tech skills courses.