Difficulty: Intermediate
Explain @PathVariable, @RequestParam, and @RequestBody. When would you use each in a REST API design?
Whenever a client calls your API, data can arrive in three places: inside the URL path, in the query string, or in the request body. Spring gives one annotation for each, and picking the right one is more about REST design sense than syntax. Let's use a placement portal as the running example.
@PathVariable extracts a value from the URL path itself. In /api/students/42, the 42 identifies a specific resource. You write @GetMapping("/students/{id}") and a parameter annotated @PathVariable Long id. Use it for resource identity: fetch, update, or delete this particular thing. It is normally mandatory, and a missing segment simply means a different URL. Type conversion is automatic, so a non-numeric value for a Long produces a 400 Bad Request through a MethodArgumentTypeMismatchException.
@RequestParam reads from the query string or form data: /api/students?branch=CSE&page=2&size=20. Use it for optional filters, sorting, and pagination, things that refine a collection rather than identify one item. By default a request param is required, and a missing one gives a 400. You can set required = false or provide defaultValue, for example @RequestParam(defaultValue = "0") int page. It also handles lists like ids=1,2,3 and can bind to Optional.
@RequestBody takes the whole HTTP body, usually JSON, and deserialises it into a Java object through Jackson. Use it for POST, PUT, and PATCH where a client sends a resource representation. Malformed JSON causes HttpMessageNotReadableException, giving 400. Combine it with @Valid to validate the fields. Only one @RequestBody is allowed per method because the body stream can be read once. And a GET with a body is technically allowed but discouraged, since many proxies and clients drop it.
Design rules of thumb worth stating out loud: identity goes in the path, filters go in query params, payload goes in the body. Do not put sensitive data such as passwords or tokens in the URL or query, because URLs land in server logs, browser history, and proxies. Prefer nouns in the path, plural collection names, and HTTP verbs for action: GET reads, POST creates, PUT replaces, PATCH partially updates, DELETE removes.
Related annotations round out the answer. @RequestHeader reads a header, @CookieValue reads a cookie, and @ModelAttribute binds form fields into an object. For pagination, Spring Data offers a Pageable argument that resolves page, size, and sort query parameters automatically, which saves you from writing three @RequestParams by hand. Also remember that you can name the path variable explicitly, @PathVariable("id"), if you compile without the -parameters flag, though Spring Boot's Maven and Gradle plugins enable it by default.
@RestController
@RequestMapping("/api/students")
class StudentController {
private final StudentService service;
StudentController(StudentService service) { this.service = service; }
// path variable: identity
@GetMapping("/{id}")
public StudentDto byId(@PathVariable Long id) { return service.find(id); }
// request params: optional filters and paging
@GetMapping
public Page<StudentDto> search(@RequestParam(required = false) String branch,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return service.search(branch, PageRequest.of(page, size));
}
// request body: payload
@PostMapping
public ResponseEntity<StudentDto> create(@Valid @RequestBody CreateStudentRequest req) {
StudentDto created = service.create(req);
return ResponseEntity.created(URI.create("/api/students/" + created.id())).body(created);
}
}
Each annotation matches where the data lives in the HTTP request.
PathVariable, RequestParam, RequestBody, REST Design