Sub topic 1
Where a Request Carries Data: Path, Query String, and Body
A Spring Boot controller method can only work with data that arrived in the HTTP request. This chapter shows where that data sits in the request, so the later chapters on @PathVariable, @RequestParam, and @RequestBody have something concrete to attach to.
Prerequisites
This chapter assumes you have the following:
- Basic Java, including classes and records.
- A Spring Boot web project (
spring-boot-starter-web) that starts and answers requests. - Basic HTTP knowledge: methods, status codes, and headers.
- Basic JSON syntax.
curlinstalled, to run the examples.
You do not need to know Spring's binding annotations yet. This chapter only previews them.
The anatomy of an HTTP request
An HTTP/1.1 request is plain text with three parts:
- A request line: the method, the target, and the protocol version.
- Headers: name/value pairs such as
HostandContent-Type. - An optional body, which follows a blank line.
Here is a request that creates a book. It uses all three data-carrying places at once:
POST /api/libraries/7/books?notify=true HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Content-Length: 78
{"title":"A Wizard of Earthsea","author":"Ursula K. Le Guin","pages":183}The request target, /api/libraries/7/books?notify=true, holds two of the three places:
- The part before the
?is the path. Here it is/api/libraries/7/books. - The part after the
?is the query string. Here it isnotify=true. - The text after the blank line is the body.
Headers and cookies also carry data, such as authentication tokens and content types. Spring reads them with @RequestHeader and @CookieValue. This tutorial focuses on the path, the query string, and the body, because those carry most of the business input.
The path
The path identifies which resource the request targets. In REST design, each segment names a thing or a collection:
/api/booksis the collection of books./api/books/42is the book with id 42./api/libraries/7/booksis the books that belong to library 7.
A path variable is a segment whose value changes from request to request. In a Spring mapping you write it as a placeholder, such as /api/books/{id}. Spring matches the incoming path against that template and extracts the value.
Properties of path data:
- It is required. If the segment is missing, the URL is a different URL and usually matches a different handler, or none.
- It is part of the resource's identity. Two different ids are two different URLs.
- It is text. Everything on the wire is a string, so
42arrives as the characters4and2. - It is URL-encoded. A segment containing a space or a slash must be percent-encoded (
%20,%2F). Many servers reject an encoded slash by default for security reasons, so avoid free-text values in path segments.
The query string
The query string comes after ? and is a list of name=value pairs joined with &:
/api/books?author=Le%20Guin&page=0&size=10Query parameters usually do not change which resource you address. They change how you view or process it: filtering, sorting, paging, switching a feature on or off.
Properties of query data:
- It is usually optional. A request without
pageshould still work, with a default. - Order generally does not matter, and a name can appear more than once (
?tag=fantasy&tag=classic). Spring can bind repeated names to a list. - Values are strings and are percent-encoded. In a query string, a literal space may appear as
%20or as+. A literal plus sign must be sent as%2B, or the server reads it as a space. - An absent parameter and an empty parameter differ.
?authorand?author=carry an empty value. Leaving the name out means no value at all. Spring treats these two cases differently for optional parameters. - It is visible everywhere. Query strings end up in browser history, proxy logs, and access logs.
The body
The body carries a payload: the data you want the server to store or process. It is separate from the URL, so it can hold large or nested data that would not fit in a URL.
A body is only meaningful together with a Content-Type header that says how to read it:
| Content-Type | Typical body | Common use |
|---|---|---|
| `application/json` | `{"title":"..."}` | REST APIs |
| `application/x-www-form-urlencoded` | `title=Earthsea&pages=183` | HTML form posts |
| `multipart/form-data` | Several parts, including files | File uploads |
| `text/plain` | Raw text | Simple messages |
In this tutorial the body is JSON. Spring picks a converter based on Content-Type. For JSON, that converter is Jackson. If the header is missing or the type is not one the handler accepts, Spring answers 415 Unsupported Media Type, not a binding error.
Properties of body data:
- It is typically sent with
POST,PUT, andPATCH. - It is not part of the URL, so it does not appear in access logs by default.
- It has structure: nested objects, arrays, numbers, and booleans keep their JSON types. Jackson still has to map them onto Java types.
GETandDELETErequests technically may carry a body, but the HTTP specification gives it no defined meaning. Many clients, proxies, and caches drop or ignore it. Do not design an API that depends on it.
Seeing the three places on the wire
curl -v prints the request it sends. Run these against any server, or a local one. Even a 404 shows you the request text:
curl -v http://localhost:8080/api/books/42
curl -v "http://localhost:8080/api/books?author=Le%20Guin&page=0&size=10"
curl -v -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"A Wizard of Earthsea","author":"Ursula K. Le Guin","pages":183}'Lines starting with > are what curl sent. In the first call, the data is only in the request line. In the second, the data is in the request line after ?. In the third, the data is after the blank line, and the Content-Type header is set.
Quote any URL containing ? or & in the shell. Otherwise the shell treats & as "run in the background" and cuts your URL short.
Preview: how Spring maps each place
Spring MVC reads each place with a different annotation on a method parameter. This controller is complete. You will meet each annotation in its own chapter, so treat this one as a map:
import java.util.List;
import org.springframework.http.HttpStatus;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/books")
public class BookController {
public record Book(long id, String title, String author) {}
public record CreateBookRequest(String title, String author, int pages) {}
@GetMapping("/{id}") // path
public Book getById(@PathVariable long id) {
return new Book(id, "Sample title", "Sample author");
}
@GetMapping // query string
public List<Book> search(@RequestParam(defaultValue = "") String author,
@RequestParam(defaultValue = "0") int page) {
return List.of(new Book(1, "Sample title", author));
}
@PostMapping // body
@ResponseStatus(HttpStatus.CREATED)
public Book create(@RequestBody CreateBookRequest request) {
return new Book(99, request.title(), request.author());
}
}| Place | Annotation | Source of the value | Required by default |
|---|---|---|---|
| Path | `@PathVariable` | A `{name}` placeholder in the mapping | Yes |
| Query string | `@RequestParam` | `name=value` after `?` | Yes, unless you opt out |
| Body | `@RequestBody` | The raw body, decoded by a message converter | Yes |
Notice that two of the three annotations are required by default. A missing required query parameter or a missing body produces a 400 response. How to shape those responses is covered later in this tutorial.
The mapping decides which handler runs. Spring first matches the HTTP method and the path template, then narrows by Content-Type and other conditions if present. Only after a handler is chosen does Spring read the parameters. A wrong path gives 404. A right path with a wrong method gives 405. Bad data in a matched request gives 400.
Common mistakes
- Putting a filter in the path.
/api/books/author/LeGuinforces a new path pattern for every filter and cannot combine filters. Use?author=LeGuin. - Putting an identity in the query string.
/api/books?id=42works, but/api/books/42states the resource more clearly and caches better. - Sending a body without
Content-Type.curl -ddefaults toapplication/x-www-form-urlencoded, so a JSON endpoint rejects it. Always add-H "Content-Type: application/json". - Sending secrets in the URL. Passwords and tokens in a path or query string land in logs and browser history. Put them in a header or the body.
- Forgetting to encode. A value such as
Le Guin & Comust be encoded asLe%20Guin%20%26%20Co. Unencoded&splits your value into two parameters. - Expecting a typed value on the wire. Path and query values are always strings until Spring converts them.
?page=abcfails at conversion, not at the network level.
Exercises
Exercise
A request is sent to /api/libraries/7/books?sort=title&page=2. Name the path and the query string. Which values identify a resource and which only adjust the view?
Show answer
The path is /api/libraries/7/books, and the query string is sort=title&page=2. The 7 in the path identifies the library, so it is part of the resource's identity. sort and page only change how the list is ordered and sliced, so they are options.
Exercise
A POST to a JSON endpoint with curl -d '{"title":"X"}' http://localhost:8080/api/books fails with 415 Unsupported Media Type. Why, and what is the fix?
Show answer
Without -H, curl sends Content-Type: application/x-www-form-urlencoded. The JSON converter does not accept that type, so Spring answers 415. Add -H "Content-Type: application/json" to the command.
Exercise
For each piece of input, choose path, query string, or body: (a) the id of the book to read, (b) the maximum number of results to return, (c) the title, author, and page count of a new book.
Show answer
(a) Path, because the id identifies the resource. (b) Query string, because it is an optional setting that changes the view. (c) Body, because it is a structured payload that creates a new resource.