Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download a Free Sample PDF

Difference between @GetMapping @PostMapping @PutMapping @DeleteMapping @PatchMapping

In the world of web development, the Spring Framework is widely known for its versatility and ease of use. It provides several annotations that simplify the process of handling HTTP requests and mapping them to specific methods in Spring controllers. Among these annotations, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping are some of the most commonly used ones. In this article, we will explore each of these annotations in detail, highlighting their purposes, differences, and providing examples to better understand their usage.

We will explore the most widely used annotation as mentioned above. Let’s explain each one in great depth.


To demonstrate the usage of Spring's HTTP method annotations (@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping), let's create a simple Spring Boot application that handles different types of HTTP requests.


Step 1: Set Up the Project

Create a new Spring Boot project using your preferred IDE or Spring Initializr (https://start.spring.io/).

Add the required dependencies: "Web" (to enable Spring Web MVC) and "DevTools" (optional, for hot-reloading during development).

Step 2: Create a Data Model

For this example, we'll use a simple "Data" model class:

public class Data {

    private Long id;

    private String name;

    // Add other properties and their getters and setters as needed

}


Step 3: Create a Controller


Next, create a controller class that will handle various HTTP requests. We'll define methods annotated with @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping.

Difference between @GetMapping @PostMapping @PutMapping @DeleteMapping @PatchMapping



@GetMapping

The @GetMapping annotation is used to handle HTTP GET requests. It maps an HTTP GET request to a specific handler method in a Spring controller. This means that when a client sends a GET request to a particular URL, the corresponding method annotated with @GetMapping will be invoked to handle the request. The @GetMapping annotation can also be used to define URL parameters and path variables.


Example:

@RestController

public class MyController {


    @GetMapping("/hello")

    public String getHello() {

        return "Hello, World!";

    }

}


@PostMapping

The @PostMapping annotation is used to handle HTTP POST requests. It maps an HTTP POST request to a specific handler method in a Spring controller. When a client sends a POST request to a defined URL, the method annotated with @PostMapping will be executed to process the request. Typically, @PostMapping is used when you want to create or add new resources.

Example:

@RestController

public class MyController {


    @PostMapping("/add")

    public String addData(@RequestBody Data data) {

        // Process the data and add it to the system

        return "Data added successfully!";

    }

}


@PutMapping

The @PutMapping annotation is used to handle HTTP PUT requests. It maps an HTTP PUT request to a specific handler method in a Spring controller. Unlike POST requests that typically add new resources, PUT requests are intended to update existing resources. Therefore, @PutMapping is commonly used to modify resource data on the server.


Example:

@RestController

public class MyController {


    @PutMapping("/update/{id}")

    public String updateData(@PathVariable Long id, @RequestBody Data data) {

        // Update the existing resource with the provided data

        return "Data updated successfully!";

    }

}


@DeleteMapping

The @DeleteMapping annotation is used to handle HTTP DELETE requests. It maps an HTTP DELETE request to a specific handler method in a Spring controller. As the name implies, @DeleteMapping is used to delete or remove resources from the server.

Example:

@RestController

public class MyController {


    @DeleteMapping("/delete/{id}")

    public String deleteData(@PathVariable Long id) {

        // Delete the resource with the given ID from the system

        return "Data deleted successfully!";

    }

}


@PatchMapping

The @PatchMapping annotation is used to handle HTTP PATCH requests. It maps an HTTP PATCH request to a specific handler method in a Spring controller. The PATCH method is used to apply partial modifications to a resource, unlike PUT, which applies full updates. @PatchMapping is commonly used when you want to update only specific fields of a resource.

Example:

@RestController

public class MyController {


    @PatchMapping("/update/{id}")

    public String updatePartialData(@PathVariable Long id, @RequestBody Data data) {

        // Apply partial updates to the resource with the provided data

        return "Partial data updated successfully!";

    }

}

Step 4: Configure Application Properties


Ensure that your application.properties or application.yml file includes the necessary configuration for your application, such as server port and logging settings.


application.properties:


server.port=8080


Step 5: Run the Application

Once you've completed the setup, run your Spring Boot application. You should see the embedded Tomcat server starting up. 

The application will be accessible at http://localhost:8080 by default (or the port you specified in the application.properties file).


Step 6: Test the Endpoints

Now, you can test the different endpoints using various HTTP methods and tools like cURL, Postman, or web browsers:


To test the GET request, open your web browser and navigate to 


http://localhost:8080/hello. You should see "Hello, World!" displayed on the page.


To test the POST request, use cURL or Postman to send a POST request to 


http://localhost:8080/add with JSON data representing the "Data" object.


To test the PUT request, use cURL or Postman to send a PUT request to 


http://localhost:8080/update/{id} with JSON data representing the "Data" object and replace {id} with a valid identifier.


To test the DELETE request, use cURL or Postman to send a DELETE request to 


http://localhost:8080/delete/{id} and replace {id} with a valid identifier.


To test the PATCH request, use cURL or Postman to send a PATCH request to 


http://localhost:8080/update/{id} with JSON data containing the specific fields you want to update and replace {id} with a valid identifier.


Conclusion

In conclusion, the Spring Framework provides several annotations to simplify the handling of HTTP requests in Spring controllers. We explored the differences between @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping annotations. @GetMapping is used for handling HTTP GET requests, @PostMapping for HTTP POST requests, @PutMapping for HTTP PUT requests, @DeleteMapping for HTTP DELETE requests, and @PatchMapping for HTTP PATCH requests.


Each annotation serves a specific purpose, allowing developers to create clean and concise code while effectively managing different types of HTTP requests. Understanding these annotations and their distinctions is crucial for building robust and efficient RESTful APIs using the Spring Framework. I hope this little effort helped you understand the difference between the HTTP request types. 


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.