← All tutorials

GoCareerGo Tutorials

Spring Boot Tutorial

Auto-configuration, REST APIs, JPA, AOP, caching, microservices and Spring Cloud.

Building a CRUD REST API

A complete Create/Read/Update/Delete controller — the pattern behind almost every Spring Boot REST tutorial.

@RestController
@RequestMapping("/api/books")
public class BookController {
    private final BookRepository repo;
    public BookController(BookRepository repo) { this.repo = repo; }

    @GetMapping public List<Book> all() { return repo.findAll(); }
    @GetMapping("/{id}") public Book one(@PathVariable Long id) { return repo.findById(id).orElseThrow(); }
    @PostMapping public Book create(@RequestBody Book b) { return repo.save(b); }
    @PutMapping("/{id}") public Book update(@PathVariable Long id, @RequestBody Book b) {
        b.setId(id); return repo.save(b);
    }
    @DeleteMapping("/{id}") public void delete(@PathVariable Long id) { repo.deleteById(id); }
}