AI Hints
Home›Spring Boot Tutorial›@PostMapping and @RequestBody, @PutMapping and @DeleteMapping
Spring Boot · Lesson 23 of 120

@PutMapping

Updating data.

⏱ 2 min read▶ Video at 30:50🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Prices change, and typos happen. PUT replaces an existing book, with new data sent by the client.

  • Prices change
  • Typos happen
  • PUT replaces

PUT in REST

PUT goes to the URL of one thing, like slash books slash one. The body holds the complete new version. The id comes from the URL, not from the body. And sending the same PUT twice gives the same result.

keyvalue
URL/books/1
Bodythe full new book
Idtaken from the URL
Repeatsame result each time

Replacing a book

This time, the map starts with one book, Dune. GET slash books slash id returns one book. At Put Mapping handles PUT, on the same path. It takes the id from the path, and the new data from the body. We build the updated book, and replace the old one. Run it. Dune costs nine ninety nine. After the PUT, it costs seven fifty, and the author is now just Herbert. And GET confirms the change.

BookController.javajava
@RestController
@RequestMapping("/books")
public class BookController {

    private final Map<Integer, Book> books = new LinkedHashMap<>(Map.of(
        1, new Book(1, "Dune", "Frank Herbert", 9.99)));

    @GetMapping("/{id}")
    public Book one(@PathVariable int id) {
        return books.get(id);
    }

    @PutMapping("/{id}")
    public Book replace(@PathVariable int id, @RequestBody Book book) {
        Book updated = new Book(id, book.title(), book.author(), book.price());
        books.put(id, updated);
        return updated;
    }
}
Output
$ curl localhost:8080/books/1
{"id":1,"title":"Dune","author":"Frank Herbert","price":9.99}
$ curl -X PUT --json '{"title":"Dune","author":"Herbert","price":7.5}'
localhost:8080/books/1
{"id":1,"title":"Dune","author":"Herbert","price":7.5}
$ curl localhost:8080/books/1
{"id":1,"title":"Dune","author":"Herbert","price":7.5}
Also uses Book.java
public record Book(Integer id, String title, String author, double price) {}
Also uses _curl.sh
curl localhost:8080/books/1
curl -X PUT --json '{"title":"Dune","author":"Herbert","price":7.5}' localhost:8080/books/1
curl localhost:8080/books/1

Summary

At Put Mapping replaces a thing, with the id from the URL, and the new data from the body. Next, deleting books.

Key takeaways
  • PUT /books/1
  • Id from the URL
  • Full new version
Next up: @DeleteMapping — removing data