Understand Http PUT vs PATCH with Examples

In this tutorial we are going to Understand HTTP PUT vs HTTP PATCH request Methods with Spring REST Service Examples. Also covers the difference between HTTP PUT and PATCH and when to use them.

Http PUT vs PATCH

On high level, both PUT and PATCH are used to modify a resource denoted by the request URI. However, they are different from each other. Next, we will understand their differences and also learn when to use which.

The HTTP PUT request method creates a new resource or replaces the target resource with the one provided in request payload. The PUT is a idempotent request, which means even if user sends the exact same request repeatedly there is no impact on the target resource.

"PUT /students/2 HTTP/1.1"Code language: JSON / JSON with Comments (json)

The above HTTP call denotes a PUT request on the resource identifier of /students/2. If the student with Id 2 already exists, the server will replace it by the one from the request body. And, if it does not exist, the server will create a new one.

On the other hand, the HTTP PATCH request method applies partial modifications to the target resource. The body of a PATCH request can contains instructions to modify the target resource. In contrast with the PUT request which is always idempotent, the PATCH request can be idempotent. Which means it depends on the resource state and the instructions which are applied on the state of the resource.

"PATCH /students/2 HTTP/1.1"Code language: JSON / JSON with Comments (json)

Above is an example, of a PATCH request which intends to update only a few fields on the Student with Id 2.

When to Use HTTP PUT request method

A Client should use the HTTP PUT Request method when they want to replace a resource if it exists, or add new if it doesn’t. A prerequisite to the PUT request is that, client needs to send a complete representation of the resource in the request body.

A PUT request can also be used for a partial modification of a resource. However, it is clients responsibility to provide the final desired state of the resource. To understand this, a PUT request to modify first name field of a Student, must have all the fields from the Students including the first name with modified value and rest of the fields with unchanged values. If the request does not contain the unchanged fields, the server will put null values for them while modifying the resource.

When to Use HTTP PATCH request method

A Client should use HTTP PATCH request method when they want to partially modify the state of a resource. A prerequisite to the PATCH request is that, the resource must already exist on the server, as the server won’t create the resource.

For example, when a client wants to modify first name of a particular Student on the server, they must provide the field name and the modified value in the request body. It is servers responsibility to modify only the provided fields, while keeping rest of the fields unchanged.

So far, we have seen the Difference Between HTTP PUT and HTTP PATCH request methods. Next, we will see a how both of the methods can be implemented in a REST API.

In the following section, we will only concentrate on the respective handler methods of a Spring Boot REST Controller. If you are new to Spring Boot, Spring data JPA, and Hibernate please read How to Create Spring Boot REST CRUD Service with Hibernate and JPA.

REST API Example of HTTP PUT

Consider, we are working on a Students Service where the student entities are persisted in Database and we use a Spring Boot Application along with Hibernate and JPA to provide the CRUD functionality on Students.

Next, we will create an implementation of the PUT endpoint for a Student.

@PutMapping("/students/{id}")
public void putStudent(
        @PathVariable long id, 
        @RequestBody StudentDto studentDto) {

    Student student = new Student();
    student.setStudent_id(id);
    student.setFirstName(studentDto.getFirstName());
    student.setLastName(studentDto.getLastName());
    student.setYear(studentDto.getYear());
    studentRepository.save(student);
}Code language: Java (java)

We are reading the Id field from the path variable and the request body is mapped into a StudentDto. Next, we create a new entity for Student by setting the Id field from the request. Then we a set all the individual fields on the student by reading them from StudentDto instance one by one. The save Spring data JPA repository, performs update or insert based on the primary key, which is Id in our case.

REST API Example of HTTP PATCH

Although, the signature of PATCH request handler method will look similar to that of PUT, we should be aware that the request body may not contain all the fields.

@PatchMapping("/students/{id}")
public void patchResource(
        @PathVariable long id, 
        @RequestBody StudentDto studentDto) {
        
    Student student = studentRepository
            .findById(id).orElseThrow(StudentNotFoundException::new);

    boolean needUpdate = false;

    if (StringUtils.hasLength(studentDto.getFirstName())) {
        student.setFirstName(studentDto.getFirstName());
        needUpdate = true;
    }

    if (StringUtils.hasLength(studentDto.getLastName())) {
        student.setLastName(studentDto.getLastName());
        needUpdate = true;
    }

    if (studentDto.getYear() > 0) {
        student.setYear(studentDto.getYear());
        needUpdate = true;
    }

    if (needUpdate) {
        studentRepository.save(student);
    }
}Code language: Java (java)

Similar to the PUT example, we are getting Id value from the Path Variable and mapping the request body into a StudentDto instance.

Next, we retrieve the existing Student entity by using the ID. Remember, if the Student doesn’t exist in the database, we cannot modify it. Hence, we throw a StudentNotFoundException for such cases.

After that, we check each of the fields from the request body and set them on the entity object if they are present. Finally, we save the entity, if there is at least one field in the request body.

Summary

In this hands on tutorial, we understood HTTP PUT vs HTTP PATCH requests. We learned the differences between them and also covered when to use which request method. Lastly, we implemented HTTP PUT and HTTP PATCH REST API Endpoints using Spring REST Controller.

For full source code of the examples used here, please visit our Github Repository.