What do @RequestBody, @ResponseBody, @PathVariable, and @RequestParam do?

8 minbeginnerrequestbodyresponsebodypathvariablerequestparam

Quick Answer

@RequestBody deserializes the incoming HTTP request body (typically JSON) into a Java object parameter, using an HttpMessageConverter. @ResponseBody serializes a handler method's return value directly into the HTTP response body (implied automatically for every method in an @RestController). @PathVariable binds a value from a URI template segment (e.g., /orders/{id}) to a method parameter. @RequestParam binds a value from a query string parameter or form field to a method parameter, optionally with a default value.

Detailed Answer

These four annotations cover how data flows into and out of a Spring MVC handler method:

@RequestBody — deserializes the HTTP request body into a Java object, using a registered HttpMessageConverter (Jackson, for JSON):

@PostMapping("/orders")
Order createOrder(@RequestBody OrderRequest request) { ... } // JSON body -> OrderRequest object

@ResponseBody — serializes the method's return value directly into the HTTP response body, bypassing view resolution (automatically implied for every method when the class is @RestController):

@GetMapping("/orders/{id}")
@ResponseBody
Order getOrder(@PathVariable Long id) { ... } // Order object -> JSON response body

@PathVariable — binds a value from a URI template variable (a placeholder segment of the mapped path) to a parameter:

@GetMapping("/orders/{id}")
Order getOrder(@PathVariable Long id) { ... } // GET /orders/42 -> id = 42

@RequestParam — binds a value from a query string parameter (or a form field in a form submission) to a parameter, optionally with a default and optionality:

@GetMapping("/orders")
List<Order> listOrders(@RequestParam(defaultValue = "10") int limit,
                        @RequestParam(required = false) String status) { ... }
// GET /orders?limit=20&status=SHIPPED

Quick way to keep them straight: @PathVariable is part of the URL's path (/orders/{id}); @RequestParam is part of the URL's query string (?limit=20) or form data; @RequestBody is the request's payload; @ResponseBody is the method's return value going out as the response payload.