Spring: @RequestParam vs @PathVariable vs @RequestBody

Query string, URL segment and request body respectively - the three ways a controller receives data.

Code
@GetMapping("/orders/{id}")
Order byId(@PathVariable Long id) { ... }              // /orders/42

@GetMapping("/orders")
List<Order> search(@RequestParam(defaultValue = "0") int page,
                   @RequestParam(required = false) String status) { ... } // /orders?page=2

@PostMapping("/orders")
Order create(@RequestBody OrderRequest body) { ... }   // JSON body
Output
GET /orders/42          -> byId(42)
GET /orders?page=2      -> search(2, null)
POST /orders {"sku":..} -> create(request)
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11