Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
PUT and PATCH are two HTTP methods used to update resources on the server in the context of RESTful web services. The main difference between them lies in how they interact with existing resources.
PUT (Object Replacement)
The PUT request indicates that the client is sending a new representation of the resource that should completely replace the current state of the resource or create a new one if it does not exist. In other words, the entire resource must be replaced with the new one.
Ruby on Rails example:
# Controller
def update
@user = User.find(params[:id])
if @user.update(user_params)
render json: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
In this example, update is used with a PUT request, and @user.update(user_params) replaces all user attributes with new values coming from the client. It implies that user_params contains all parameters of the object (model).
PATCH (Partial Update)
The PATCH request indicates that the client is sending a partial update of the resource, meaning only the data that needs to be changed, without the need to send all the information about the resource. This is convenient when the client wants to update only certain fields of the resource. For example - only one section of the form with information about themselves on the site.
Ruby on Rails example:
# Controller
def update
@user = User.find(params[:id])
if @user.update(user_partial_params)
render json: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
Here @user.update(user_partial_params) is used for partial user update with a PATCH request, where user_partial_params contains only those fields that need to be updated.
In summary, PUT is used for complete resource updates, while PATCH is used for partial updates, allowing other parts of the resource to remain unchanged.
Ruby on Rails is quite an intelligent framework and it determines itself which request it needs to make. This allows for automation and simplifies controller logic, making the code cleaner and more understandable.
So technically, the call @user.update(user_params) (which we considered earlier as PUT) can be PATCH instead of PUT, because the form on the frontend does not have all the fields of the object.
This post doesn't have any additions from the author yet.