Sub topic 10
Implementing create, read, update, and delete with correct status codes
This chapter assumes you have the Book entity, BookRepository, DTO records, and BookService from the earlier chapters. It also assumes you know the basic HTTP methods and status code classes. Here you wire the service into a controller and choose the right status code for each outcome.
Mapping operations to methods and codes
Each CRUD operation has one HTTP method, one URL shape, and one expected success code.
| Operation | Request | Success status | Body |
|---|---|---|---|
| List | `GET /api/books` | 200 OK | Page of books |
| Read | `GET /api/books/{id}` | 200 OK | One book |
| Create | `POST /api/books` | 201 Created | New book, plus `Location` header |
| Update | `PUT /api/books/{id}` | 200 OK | Updated book |
| Delete | `DELETE /api/books/{id}` | 204 No Content | None |
Spring MVC returns 200 by default, so you only write code for the cases that differ: 201 on create and 204 on delete.
The controller
The controller stays thin. It translates HTTP into service calls and chooses the status code. It holds no business logic.
package com.example.books;
import jakarta.validation.Valid;
import java.net.URI;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public Page<BookResponse> list(Pageable pageable) {
return service.list(pageable);
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable Long id) {
return service.get(id);
}
@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody BookRequest request) {
BookResponse created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location).body(created);
}
@PutMapping("/{id}")
public BookResponse update(@PathVariable Long id, @Valid @RequestBody BookRequest request) {
return service.update(id, request);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
service.delete(id);
}
}How each endpoint behaves
Create. ResponseEntity.created(location) sets status 201 and the Location header. The header holds the URL of the new resource, such as /api/books/7. Because the builder starts from the current request URL, the header stays correct if the base path changes. Clients can follow the header without building URLs themselves.
Read. get returns the DTO directly. If the book does not exist, the service throws BookNotFoundException. The controller never checks for null, and the exception handler chapter turns the exception into a 404.
Update. PUT replaces the whole resource, so BookRequest requires both fields. The service loads the entity and calls the setters. It never calls save, because the transaction commits the change through dirty checking. A missing id gives a 404, not a new row.
Delete. The service checks existsById first. Without that check, a missing id would be silent or would fail inside the repository, and the client could not tell the two cases apart.
Common errors
- Returning 200 from POST. It works, but clients lose the
Locationheader and the signal that a resource was created. - Returning a body with 204. A 204 response must have no body. Use
voidas shown. - Using
PUTfor partial updates. Sending only a title would fail validation or erase the author. Partial updates belong toPATCH. - Returning the entity from the controller. This ties your JSON to your table. Always return
BookResponse.
Trying it
Start the application, then run:
curl -i -X POST localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Dune","author":"Frank Herbert"}'The response should start with HTTP/1.1 201 and include Location: http://localhost:8080/api/books/1. Then run curl -i -X DELETE localhost:8080/api/books/1 and expect 204.
Exercise
A client sends PUT /api/books/99 and no book with id 99 exists. With the code in this chapter, what status does the client get, and which part of the code causes it?
Show answer
It gets 404 Not Found. BookService.update calls findById, finds nothing, and throws BookNotFoundException. The exception handler in @RestControllerAdvice maps that exception to 404. No row is created, because update never calls save for a new entity.
Exercise
Why does the create method return ResponseEntity instead of just a BookResponse with @ResponseStatus(HttpStatus.CREATED)?
Show answer
The Location header needs a URL built from the new id, which is only known after the service runs. ResponseEntity lets the method set the status, the header, and the body together at runtime. A fixed @ResponseStatus cannot add a computed header.