Skip to main content
PreparationZone Logo
PrepZone

Build a CRUD API Step by Step

Complete BookStore CRUD — entity, repository, service and controller wired together.

Pass checkpoint below

Why this matters

  • Building CRUD from scratch cements the layered pattern before adding validation, error handling, and security.
  • This is the reference implementation every later BookStore article extends.
  • Interviewers often ask candidates to sketch a CRUD API — having built one makes the answer concrete.

CRUD flow

L1 · Fresher

Entity → repository → service → controller forms the BookStore vertical slice interviewers ask you to whiteboard.

Spring Data repository

L2 · Intermediate

JpaRepository gives save, findById, and derived query methods without boilerplate SQL for simple access.

HTTP semantics

L3 · Advanced

Use POST for create, PUT/PATCH for update, DELETE for remove, and correct status codes (201, 204, 404).

Idempotent PUT

L4 · Expert

Design PUT with client-supplied IDs or natural keys so retries do not duplicate resources — ties to production REST patterns later.

Injection styles
ConstructorRecommended — final fields
SetterOptional dependencies
FieldAvoid — hard to test
Constructor injection is preferred — dependencies are explicit, immutable, and easy to test.

Step 1: Entity

Java
// learn:fragment
@Entity
@Table(name = "books")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String title;

    @Column(nullable = false, unique = true)
    private String isbn;

    @Column(nullable = false)
    private BigDecimal price;

    protected Book() {}  // JPA requires no-arg constructor

    public Book(String title, String isbn, BigDecimal price) {
        this.title = title;
        this.isbn = isbn;
        this.price = price;
    }

    // getters and setters
}

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 6 sections

  • Step 2: Repository
  • Step 3: Service
  • Step 4: Controller
  • Step 5: Configuration
  • Test the API
  • Request flow summary

Test yourself

Answer these before moving on — recall is what makes it stick.