Video in progress

Junior 🌱 Spring

What is the difference between @PathVariable and @RequestParam?

@PathVariable takes a piece of the URL path (/users/42), while @RequestParam takes a query parameter (/users?page=2). The first points to a resource, the second is for filters or options.

📖 Answer

@GetMapping("/orders/{id}")
public OrderDto one(@PathVariable long id) { ... }        // /orders/15

@GetMapping("/orders")
public List<OrderDto> list(@RequestParam(defaultValue = "0") int page,
                           @RequestParam(required = false) String status) { ... }
// /orders?page=1&status=PAID

A simple rule: one specific resource goes in the path (/orders/15); search, sorting and paging go in parameters (?status=PAID&sort=date).

The subtle parts:

  • @RequestParam is required by default; if the parameter is missing you get a 400. To make it optional, use required = false or defaultValue.
  • If the type doesn't match (/orders/abc when a long is expected) — another 400.
  • If you compile with Java 8+ and the -parameters flag, you don't need to write the name; Spring Boot sets this up for you.