Sub topic 1
REST and HTTP in brief: resources, methods, status codes
Prerequisites
Assume Java fundamentals, records, basic HTTP, Maven or Gradle, and dependency injection. A REST API is an HTTP interface that exposes resources, such as books. URLs identify resources, HTTP methods describe actions, and status codes describe results.
| HTTP method | Typical use | Successful response |
|---|---|---|
| `GET` | Read a resource | `200 OK` |
| `POST` | Create a resource | `201 Created` |
| `PUT` | Replace a resource | `200 OK` or `204 No Content` |
| `DELETE` | Remove a resource | `204 No Content` |
Setting up a Spring Boot web project
Create a project with Spring Initializr or your build tool. Add the spring-boot-starter-web dependency. This starter includes Spring MVC, an embedded server, and Jackson, which converts Java objects to JSON.
Run the application with your usual Maven or Gradle command. By default, it listens on port 8080.
Your first `@RestController`
@RestController marks a class whose methods handle HTTP requests. Returned objects become response bodies, usually as JSON. @RequestMapping gives the controller a shared URL prefix.
Mapping HTTP methods
Use an annotation that matches the HTTP method. Keep the controller focused on HTTP details. Delegate business rules and data access to a service.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public List<BookResponse> list(@RequestParam(defaultValue = "") String title) {
return service.search(title);
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}
@PostMapping
public BookResponse create(@RequestBody CreateBookRequest request) {
return service.create(request);
}
}@GetMapping handles reads, while @PostMapping handles creation. @PutMapping and @DeleteMapping handle replacement and deletion. @PatchMapping commonly handles partial updates.
Path variables and query parameters
A path variable identifies one resource, such as /api/books/7. A query parameter filters or modifies a collection request, such as /api/books?title=dune. Spring converts these values to the declared Java types.
Exercise
Which mapping should handle GET /api/books/42, and where does 42 go?
Show answer
Use @GetMapping("/{id}"); Spring binds 42 to a parameter annotated with @PathVariable.