Sub topic 1
Where a Request Carries Data in Spring Boot
Prerequisites.
Assume you know basic Java classes and records, HTTP methods and status codes, and JSON syntax. You also have a Spring Boot project using spring-boot-starter-web.
Three Places for Request Data
An HTTP request can carry input in three common places:
| Location | Typical purpose | Example |
|---|---|---|
| Path | Identifies one resource | `/api/books/42` |
| Query string | Filters, searches, or paginates | `/api/books?author=Le%20Guin` |
| Body | Sends structured data, often for creation | `{"title":"Dune"}` |
Choose the path when the value identifies the resource itself. Use query parameters when the request modifies a collection lookup. Use the body for larger or structured input.
Controllers and Request Mappings
A controller handles HTTP requests. @RestController tells Spring that its methods return response data. @RequestMapping supplies a shared URL prefix. An HTTP method annotation, such as @GetMapping, selects the remaining path and method.
@RestController
@RequestMapping("/api/books")
class BookController {
@GetMapping("/{id}")
Book getById(@PathVariable Long id) {
return service.get(id);
}
@GetMapping
List<Book> search(
@RequestParam(required = false) String author,
@RequestParam(defaultValue = "0") int page) {
return service.search(author, page);
}
}Reading Path Variables with `@PathVariable`
The {id} placeholder in the mapping captures that URL segment. @PathVariable binds it to the method parameter. Spring converts the incoming text, such as "42", to Long.
Path variables are usually required. A request for /api/books/42 can identify one book, while /api/books cannot provide an id.
Reading Query Parameters with `@RequestParam`
Query parameters follow ? in the URL. Separate multiple parameters with &. Spring binds them by name:
curl "http://localhost:8080/api/books?author=Le%20Guin&page=1"author is optional in the example. If it is absent, its value is null. page defaults to 0 when absent. Spring also converts numeric values to int. A value that cannot be converted produces a client error, normally HTTP 400.
Exercise
Which input style fits a request for books by a specific author on page 2?
Show answer
Use a query string, such as /api/books?author=Le%20Guin&page=2.