Sub topic 12
Choosing between path, query, and body
This chapter helps you decide where each piece of input belongs in an endpoint. It assumes you can already write a Spring Boot controller and have seen @PathVariable, @RequestParam, and @RequestBody used on their own.
The working model
A request can carry data in three places. Each place has a different job.
- Path: identifies which resource the request is about.
- Query string: refines how you read a collection, for example by filtering, sorting, or paging.
- Body: carries the content you create or change.
Ask what the value means, then place it. Do not start from what is convenient to bind.
Decision criteria
| Question | Path | Query | Body |
|---|---|---|---|
| Is it required? | Yes, always | Usually optional | Depends on the DTO |
| Is it part of the resource's identity? | Yes | No | No |
| Can it be bookmarked or cached by URL? | Yes | Yes | No |
| Does it suit a structured or large value? | No | No | Yes |
| Allowed on GET? | Yes | Yes | Avoid |
Two rules explain most of this table.
- A missing path variable changes the URL.
/api/books/is a different route from/api/books/42. The path therefore suits values that must always be present. - GET requests should not rely on a body. Many clients, proxies, and caches ignore or drop it. Put read inputs in the query string.
One resource, three inputs
Here is the same BookController using each place for the right reason.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
// Path: which book
@GetMapping("/{id}")
public Book getById(@PathVariable Long id) {
return service.get(id);
}
// Query: how to list books
@GetMapping
public List<Book> search(@RequestParam(required = false) String author,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return service.search(author, page, size);
}
// Body: the content of the new book
@PostMapping
public ResponseEntity<Book> create(@Valid @RequestBody CreateBookRequest request) {
Book saved = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(saved.id())
.toUri();
return ResponseEntity.created(location).body(saved);
}
}The id appears in the path because /api/books/42 names one book. The author, page, and size values only narrow a list, so they are optional and have defaults. The title, author, and page count describe a new book, so they travel in a JSON body that validation can check as a unit.
Common mistakes
- Filters in the path.
/api/books/author/Le Guinties a route to one filter. Adding a second filter forces another route. Use/api/books?author=Le%20Guin. - Identifiers in the query string.
/api/books?id=42makes a required identity look optional. Use/api/books/42. - Sensitive data in the URL. Paths and query strings end up in access logs, browser history, and proxy logs. Send passwords or tokens in a header or a body.
- Long or nested data in the query string. Lists of objects and deeply nested values are hard to express and hit URL length limits. Use a body.
- A body on GET. Avoid it, as described above. If a search is too complex for a query string, a
POSTto a search endpoint is an accepted compromise.
Mixing inputs in one request
Updates commonly use two places at once. The path says which book, and the body says what to change.
@PutMapping("/{id}")
public Book update(@PathVariable Long id,
@Valid @RequestBody CreateBookRequest request) {
return service.update(id, request);
}Do not repeat the identifier in the body. If it appears in both places, you must decide what happens when they disagree. Taking it from the path only avoids that question.
Effect on error handling
The placement also decides which error you get when input is wrong. A path variable or query value that cannot be converted raises MethodArgumentTypeMismatchException. A body that fails validation raises MethodArgumentNotValidException. The handlers from the earlier chapter already map both to 400 responses, so a consistent placement gives consistent errors.
Exercise
You are designing an endpoint to list a user's orders from the last 30 days, sorted by total, and another to cancel one order. Which inputs go in the path, query, or body for each?
Show answer
Listing: the user id is in the path (/api/users/{userId}/orders). The 30-day window and the sort order are query parameters (for example ?days=30&sort=total), because they only refine a read. Cancelling: the order id is in the path (POST /api/orders/{orderId}/cancel, or DELETE /api/orders/{orderId}). Add a body only if the client must send extra content, such as a cancellation reason.
Exercise
A teammate writes GET /api/books?id=42 to fetch one book. Give two reasons to change it, and name the new form.
Show answer
The id identifies a resource, so it belongs in the path, and a query parameter makes a required value look optional. The path form also gives each book its own URL for caching and bookmarks. The new form is GET /api/books/42.