How to build a REST API with Spring Boot


Spring Boot makes it very easy to build production-ready REST APIs with minimal configuration. In this tutorial, we’ll build a simple Book Management REST API with CRUD operations. This article doesn’t cover the security aspects. This will be covered in later posts.

You will learn to build rest api with spring boot with full code samples. We will create an entity, repository, service and finally the REST Controller. Try to code in your IDE while reading this tutorial.

🧰 What You’ll Need

  • Java 17+
  • Maven or Gradle
  • IDE (IntelliJ IDEA, VS Code, Eclipse)
  • Postman or Curl for testing

1. Create a Spring Boot Project

Use Spring Initializr to generate a project:

Settings:

  • Project: Maven
  • Language: Java
  • Spring Boot: 3.x+
  • Dependencies:
    • Spring Web
    • Spring Data JPA
    • H2 Database (for in-memory testing)

Download and unzip the project, then open it in your IDE.

2. Create the Entity

package com.themstembook.demo.model;

import jakarta.persistence.*;

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String author;

    // Getters & Setters
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public String getAuthor() { return author; }
    public void setAuthor(String author) { this.author = author; }
}Code language: JavaScript (javascript)

3. Create the Repository

Repository is used to save and fetch the data from the database. For this tutorial, you can use an in-memory database like h2. For production deployment, change this to another database like a postgres, mysql or similar.

package com.thestembook.demo.repository;

import com.example.demo.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Long> {
}Code language: CSS (css)

4. Book Service Bean

The service is the class where the core business logic resides. The Service interacts with the repository and persists and fetches entities, in our case, the book entity. In this example, the service class is pretty simple and doesn’t include much logic.

package com.thestembook.demo.service;

import com.example.demo.model.Book;
import com.example.demo.repository.BookRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookService {
    private final BookRepository repository;

    public BookService(BookRepository repository) {
        this.repository = repository;
    }

    public List<Book> findAll() {
        return repository.findAll();
    }

    public Optional<Book> findById(Long id) {
        return repository.findById(id);
    }

    public Book save(Book book) {
        return repository.save(book);
    }

    public void deleteById(Long id) {
        repository.deleteById(id);
    }
}Code language: PHP (php)

5. Create the REST Controller

The REST Controller ( @RestController) is responsible for exposing the service to the outside world. A controller can interact with multiple services or a single service , single in this example. Controller can be enhanced to add security annotations ( spring oauth 2) to introduce access control. This is not shown in this example.

package com.thestembook.demo.controller;

import com.example.demo.model.Book;
import com.example.demo.service.BookService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/books")
public class BookController {
    private final BookService service;

    public BookController(BookService service) {
        this.service = service;
    }

    @GetMapping
    public List<Book> getAllBooks() {
        return service.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Book> getBookById(@PathVariable Long id) {
        return service.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public Book createBook(@RequestBody Book book) {
        return service.save(book);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Book> updateBook(@PathVariable Long id, @RequestBody Book bookDetails) {
        return service.findById(id)
                .map(book -> {
                    book.setTitle(bookDetails.getTitle());
                    book.setAuthor(bookDetails.getAuthor());
                    return ResponseEntity.ok(service.save(book));
                }).orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteBook(@PathVariable Long id) {
        service.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}Code language: PHP (php)

6. Testing Phase

You can use Postman or curl to test your API:

  • GET /api/books
  • POST /api/books
  • PUT /api/books/1
  • DELETE /api/books/1

We have now created REST API with CRUD operations using Spring Boot. This structure is scalable and ready to be extended with:

  • Security (JWT, OAuth2) – Spring OAuth2 with security annotations
  • Pagination
  • Validation – Hibernate validator framework is very handy here
  • Swagger/OpenAPI Docs – There are plugins available for this

References:

Spring Book Documentation

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *


 We break down complex topics into clear, actionable content. Built for developers, learners, and curious minds.


Socail Connect

theStemBookDev

about science, tech, engineering , programming and more