Sub topic 10
Implementing create, read, update, and delete with correct status codes
This chapter assumes you have the Book entity, BookRepository, BookRequest/BookResponse records, and BookService from the earlier chapters. You should also know the basic HTTP methods and the status code classes (2xx success, 4xx client error, 5xx server error). Here you will wire the service into a controller and choose the right status code for each outcome.
The contract for each operation
An HTTP status code tells the client what happened without making it parse the body. A CRUD API should choose these codes on purpose, because clients, proxies, and caches all react to them.
| Operation | Method and path | Success status | Body | Typical failure |
|---|---|---|---|---|
| List | `GET /api/books` | 200 OK | page of `BookResponse` | 400 for bad paging parameters |
| Read one | `GET /api/books/{id}` | 200 OK | `BookResponse` | 404 Not Found |
| Create | `POST /api/books` | 201 Created | created `BookResponse`, plus a `Location` header | 400 for invalid input |
| Update | `PUT /api/books/{id}` | 200 OK | updated `BookResponse` | 400 invalid, 404 unknown id |
| Delete | `DELETE /api/books/{id}` | 204 No Content | none | 404 unknown id |
Two properties affect how you implement these. A method is safe if it does not change server state. GET is safe, and the others are not. A method is idempotent if repeating the same request leaves the server in the same state as sending it once. GET, PUT, and DELETE are idempotent. POST is not, so sending the same create request twice makes two books.
The controller
The controller does only HTTP work. It reads the path, query, and body, calls the service, and chooses the status and headers. The business rules stay in the service.
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.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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
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);
}
}@RestController combines @Controller and @ResponseBody. Return values are written straight to the response through Jackson, so you never return a view name.
How a request travels
The diagram follows a create request. Each layer handles one concern, and the status code is decided in the controller.
Create: 201 and the Location header
A successful POST that creates a resource should return 201 Created. It should also send a Location header with the URL of the new resource, so the client can fetch it without guessing the id.
ServletUriComponentsBuilder.fromCurrentRequest() starts from the URL of the current request, http://localhost:8080/api/books. It appends /{id} and fills in the generated id. This keeps the host, port, and context path correct behind any deployment, and you never hard-code them.
Try it with the application running:
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Notes on Computing","author":"Ada"}'The response looks like this:
HTTP/1.1 201
Location: http://localhost:8080/api/books/1
Content-Type: application/json
{"id":1,"title":"Notes on Computing","author":"Ada"}The id comes from the database because the entity uses GenerationType.IDENTITY. The response has an id only after save has run the INSERT.
Read: 200 or 404
GET /api/books/{id} returns 200 when the book exists. When it does not, the service throws BookNotFoundException. The controller never checks for a missing book, so it never returns null, which Spring would turn into an empty 200 response.
The list endpoint always returns 200, even when no books exist. An empty collection is a valid result, so a client should receive an empty page rather than a 404. The Pageable parameter is filled from the page, size, and sort query parameters, and a later chapter covers it in detail.
Update: PUT replaces the resource
PUT means "replace the resource at this URL with the body I send". The BookRequest holds all the editable fields, so the client sends the full representation. The service copies both fields onto the entity and returns it:
@Transactional
public BookResponse update(Long id, BookRequest request) {
Book book = repository.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));
book.setTitle(request.title());
book.setAuthor(request.author());
return BookResponse.from(book);
}There is no call to repository.save. Inside the transaction, the entity returned by findById is managed, and Hibernate compares it with its loaded state when the transaction commits. If a field changed, it issues an UPDATE. This is called dirty checking. The method returns 200 OK with the updated resource, and 204 No Content is also acceptable if you prefer to send no body.
If you need partial updates, where the client sends only the fields that changed, PATCH is the correct method. PATCH is not idempotent by definition, and it needs a request type with optional fields. This chapter keeps the API to PUT.
Delete: 204 and what a second DELETE returns
@ResponseStatus(HttpStatus.NO_CONTENT) sets the status for a void method that completes normally. No body is written, which matches what 204 means.
The service checks existsById first and throws if the book is missing. That makes a repeated DELETE return 404. Some APIs return 204 every time, because the end state is the same: the resource is gone. Both choices are defensible. The 404 version tells the client its id was wrong. The always-204 version is simpler for retrying clients. Pick one, document it, and apply it to every resource.
Errors before the advice class exists
At this point, BookNotFoundException extends RuntimeException and nothing handles it. Spring Boot's default error handling turns it into a 500 Internal Server Error. That is wrong, because the client made the mistake and the server did not fail. The @RestControllerAdvice class from the exception handling chapter maps the exception to 404 with a ProblemDetail body. Until you add it, expect 500 for unknown ids.
Invalid bodies already produce 400. When @Valid fails, Spring throws MethodArgumentNotValidException, and its default handling returns 400 Bad Request.
Common errors
- Returning 200 from POST. Clients that follow REST conventions look for
201andLocation. If you return the body with a plain200, they must guess where the resource lives. - Forgetting
@Valid. Without it, the validation annotations onBookRequestare never checked, and blank titles reach the database. - Returning the entity from the controller. The JSON contract then follows the table structure. Use
BookResponseso you can change the database without breaking clients. - Using
Optional.get()or returningnullfor missing data. This produces500errors or empty200responses. Throw a specific exception and map it to404. - Updating without a transaction. If
updatelacked@Transactional,findByIdwould return a detached entity, the setters would change nothing in the database, and the endpoint would return the new values while the database kept the old ones. Dirty checking only works inside a transaction. - Putting the id in the body and the path. A client could send
PUT /api/books/1with a body that names book 2.BookRequesthas no id field, so the path is the only source of truth.
Checking the full cycle
Run these in order against a fresh database:
curl -i http://localhost:8080/api/books/1
curl -i -X PUT http://localhost:8080/api/books/1 \
-H "Content-Type: application/json" \
-d '{"title":"Notes on Computing, 2nd ed.","author":"Ada"}'
curl -i -X DELETE http://localhost:8080/api/books/1
curl -i http://localhost:8080/api/books/1After the book from the create step exists, you should see 200, 200, 204, and then 404 once the advice class is in place. If the last call returns 500, the exception handler is missing.
Exercise
A client sends the same POST /api/books request twice because of a network timeout. What does your API do, which status codes does the client see, and why can't the server rely on HTTP semantics to prevent the duplicate?
Show answer
Each request creates a separate book, so the client sees 201 Created twice with two different ids and two different Location headers. POST is not idempotent, so HTTP gives no guarantee that a repeat has no extra effect. Preventing duplicates needs an application rule, such as a unique constraint on title and author, or an idempotency key sent by the client.
Exercise
You change delete so that it calls repository.deleteById(id) directly, with no existsById check. Depending on the Spring Data version, what happens when the id does not exist, and which status does the client see?
Show answer
In current Spring Data JPA versions, deleteById does nothing when the id is missing, so the method completes and the client sees 204. Older versions threw EmptyResultDataAccessException, which would have produced 500 without a handler. Because behavior differed between versions, the explicit existsById check makes the 404-or-204 decision visible in your own code.