Sub topic 12
Choosing between path, query, and body
This chapter assumes you can already read @PathVariable, @RequestParam, and @RequestBody parameters, and that you know HTTP methods and status codes. It is about design. Given a piece of input, which of the three channels should carry it? Spring will bind any of them, so the framework does not decide for you. The choice affects caching, logging, URL length, error codes, and how stable your API stays as it grows.
The three channels have different meanings
Each channel says something different to clients, proxies, caches, and logs.
- The path names the resource.
/api/books/42is the address of one book. Changing the path points at a different resource. - The query string adjusts how a resource, or a collection of resources, is viewed.
/api/books?author=Le%20Guin&page=2is the same collection, filtered and paged. - The body carries a representation of data you are sending. It is meant for creating or replacing something, or for input too large or structured for a URL.
A useful test is to ask what a different value would mean. A different path value means a different thing. A different query value means a different view of the same thing. A different body means different content for the operation.
Decision rules
Work through these questions in order for each input.
- Does it identify the resource the request acts on? Use a path variable. Examples are a book ID, an order number, or a username.
- Is it optional, or does it filter, sort, page, or shape the response? Use a query parameter. A missing value should have a sensible default.
- Is it the data being created or changed, or is it nested, long, or sensitive? Use the request body.
- Is it metadata about the request itself? Use a header. Authentication tokens, content type, and correlation IDs are examples. Headers are outside this chapter's scope.
Side-by-side comparison
| Property | Path variable | Query parameter | Request body |
|---|---|---|---|
| Typical role | Identity | Filter, sort, page | Data to create or change |
| Optional? | Not really. The route needs it. | Yes, with `required = false` or a default | Optional only if you set `required = false` |
| Works with GET | Yes | Yes | Not reliably. Avoid it. |
| Appears in logs and history | Yes | Yes | Usually not |
| Part of the cache key | Yes | Yes | No |
| Practical size | Short values | Short values, limited by URL length | Large |
| Structure | One flat value | Flat, repeated values allowed | Nested objects and arrays |
| Missing value gives | 404 (no route matches) | 400 for a required parameter | 400 for a missing body |
| Bad content type gives | Not applicable | Not applicable | 415 |
The error row matters for API design. A missing path variable never reaches your controller, because no mapping matches the URL. A missing required query parameter does reach Spring's binding stage and fails there with a MissingServletRequestParameterException. You can turn that into a 400 with the same @RestControllerAdvice approach used for other binding errors.
A worked example
This controller puts each input in the channel the rules suggest. It assumes a BookService bean and a Book record like the ones from earlier chapters, shown here in a minimal form so the code is complete.
package com.example.books;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import java.net.URI;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
record Book(Long id, String title, String author, int pages) {}
record BookRequest(
@NotBlank String title,
@NotBlank String author,
@Positive int pages) {}
record BookSearch(String titleContains, Integer minPages, Integer maxPages) {}
interface BookService {
Book get(Long id);
List<Book> search(String author, int page, int size);
List<Book> advancedSearch(BookSearch criteria);
Book create(BookRequest request);
Book replace(Long id, BookRequest request);
void delete(Long id);
}
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
// Identity in the path
@GetMapping("/{id}")
public Book getById(@PathVariable Long id) {
return service.get(id);
}
// Filter and paging in the query string
@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);
}
// Data in the body
@PostMapping
public ResponseEntity<Book> create(@Valid @RequestBody BookRequest request) {
Book saved = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(saved.id())
.toUri();
return ResponseEntity.created(location).body(saved);
}
// Identity in the path, new content in the body
@PutMapping("/{id}")
public Book replace(@PathVariable Long id,
@Valid @RequestBody BookRequest request) {
return service.replace(id, request);
}
// Identity only. No body is needed.
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
service.delete(id);
return ResponseEntity.noContent().build();
}
// Structured criteria that outgrow a query string
@PostMapping("/search")
public List<Book> advancedSearch(@RequestBody BookSearch criteria) {
return service.advancedSearch(criteria);
}
}Notice that PUT /{id} uses two channels together. The path says which book to replace, and the body says what it becomes. Treat the path as authoritative. If you also put an id field in the body, you create a conflict to resolve, so leave it out of the request record.
Edge cases and gotchas
Sensitive values do not belong in the URL
Web servers, proxies, and browsers record URLs. Query strings and path segments end up in access logs, browser history, and Referer headers. Do not put passwords, tokens, or personal data there. Send them in the body or in a header over HTTPS.
Filters are not identity
A common mistake is /api/books/author/Le%20Guin for a search. The author is not the identity of any one book. Each new filter then needs a new route shape, and combinations such as author plus minimum pages become awkward. Use /api/books?author=Le%20Guin&minPages=100, where filters combine freely and each is optional.
The opposite mistake is GET /api/books?id=42. This works technically, but it hides identity in a place that reads as optional. It also makes the missing-ID case a 400 instead of a clean 404 for an unknown route.
Hierarchy belongs in the path
When a resource only exists inside a parent, the path expresses that well. /api/authors/7/books reads as "the books of author 7". Stop at about two levels. Deeper nesting makes URLs long and ties clients to your internal model. Once a child has its own unique ID, you can usually address it directly as /api/books/42.
Special characters in path variables
Values containing / are a problem in a path segment. Servers often reject the encoded form %2F by default. If the value can contain arbitrary text, such as a title or a file path, carry it in a query parameter or the body instead.
GET with a body
The HTTP specification does not give a body on GET any defined meaning. Many clients, proxies, and tools drop it or refuse to send it. Do not design endpoints that depend on it. When filter criteria are too large or too nested for a query string, as with advancedSearch above, use POST on a search sub-resource.
A POST search gives up some properties of GET. Intermediaries do not cache it by default, and it is not safe to retry blindly in every client. If those properties matter and the criteria fit in a URL, stay with GET and a query string.
URL length limits
Servers and proxies cap request-line and header size. Embedded Tomcat, for example, defaults to about 8 KB for the header section. Passing hundreds of IDs as ?ids=1,2,3,... can hit that limit. A POST with a JSON array avoids it.
Form submissions
A browser form posted as application/x-www-form-urlencoded is neither JSON nor a query string. Spring binds those fields with @RequestParam or a model object, not @RequestBody. A JSON endpoint should declare what it consumes, for example @PostMapping(consumes = "application/json"). A client that sends the wrong Content-Type then receives 415 instead of a confusing binding failure.
Be consistent across the API
Pick one convention and apply it everywhere. Page parameters named page and size on one endpoint and pageNumber and limit on another force clients to special-case each call. Decide once whether collections use sort=title,asc or something else, and keep it.
Quick reference for common operations
| Operation | Path | Query | Body |
|---|---|---|---|
| Fetch one book | `/books/{id}` | none | none |
| List with filters | `/books` | author, page, size, sort | none |
| Create a book | `/books` | none | book fields |
| Replace a book | `/books/{id}` | none | book fields |
| Delete a book | `/books/{id}` | none | none |
| Complex search | `/books/search` | none | criteria object |
Exercise
You are adding an endpoint that returns the reviews of one book, with optional filtering by minimum star rating and paging. Which input goes in the path, which in the query string, and what would the URL look like?
Show answer
The book ID identifies the parent resource, so it goes in the path. The minimum rating and the paging values only filter and page the result, so they go in the query string, each optional with a default. For example: GET /api/books/42/reviews?minRating=4&page=0&size=20. No body is needed, because the request only reads data.
Exercise
A teammate proposes GET /api/users/login/{username}/{password} so clients can sign in. Give two reasons this design is wrong and say where each input should go instead.
Show answer
First, the password in the path is recorded in access logs, browser history, and proxies. Second, GET responses can be cached and the request is meant to be safe, but a login creates a session or token, so it is not a read. Use POST /api/sessions (or /api/login) with a JSON body containing username and password, sent over HTTPS. The body is not part of the URL and is not logged by default.
Exercise
A client calls PUT /api/books/42 with a JSON body whose id field is 99. Why is this a design problem, and how do you avoid it?
Show answer
The request names two different identities, and the server must decide which wins. Avoid it by treating the path as the only source of identity and leaving id out of the request record (BookRequest above has no id field). Jackson then ignores or rejects the extra field depending on configuration, and the handler always uses the path value.