# @PathVariable vs @RequestParam vs @RequestBody

> Explain @PathVariable, @RequestParam, and @RequestBody. When would you use each in a REST API design?

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-request-mapping-pathvariable-requestparam-requestbody
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

Explain @PathVariable, @RequestParam, and @RequestBody. When would you use each in a REST API design?

## Answer

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.

## Code examples

### All three in one controller

```
@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.

## Key points

- Path variable = identity, request param = filter, request body = payload.
- Request params are required by default; use required=false or defaultValue.
- Only one @RequestBody per handler method.
- Never place secrets in the URL or query string.

## Common follow-up questions

- How do you bind pagination parameters automatically?
- What happens when a required request parameter is missing?
- Difference between PUT and PATCH?

## Interview tips

- Justify each choice with REST design, not only syntax.
- Mention the security concern about URLs being logged.

## Concepts covered

PathVariable, RequestParam, RequestBody, REST Design

Previous: [@RestController vs @Controller](https://www.internhack.in/learn/interview/spring-boot-interview/spring-restcontroller-vs-controller) · Next: [Bean Validation with @Valid and @Validated](https://www.internhack.in/learn/interview/spring-boot-interview/spring-validation-valid) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [Global Exception Handling with @ControllerAdvice](https://www.internhack.in/learn/interview/spring-boot-interview/spring-controlleradvice-global-exception-handling)
- [ResponseEntity and Correct HTTP Status Codes](https://www.internhack.in/learn/interview/spring-boot-interview/spring-responseentity)
- [Spring Data JPA: Repositories, Derived Queries and @Query](https://www.internhack.in/learn/interview/spring-boot-interview/spring-data-jpa-repositories-queries)
- [JPA Relationships and the N+1 Query Problem](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-relationships-n-plus-one)
- [Lazy vs Eager Fetching and LazyInitializationException](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-lazy-vs-eager-fetching)
- [@Transactional: Propagation, Rollback Rules and Self-Invocation](https://www.internhack.in/learn/interview/spring-boot-interview/spring-transactional-pitfalls)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
