Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: A Bookshop REST API

Build a complete Quarkus bookshop API: project setup, Panache entity, REST resource, validation, error mapping, tests, health checks and container image, with a runnable model.

This project ties the course together. You will design and build a small but realistic service, bookshop, with a PostgreSQL database, a REST API, validation, error handling, tests, health checks and a container image. The steps are the ones you would follow on a real job, and each step names the lesson that explains the details.

Quarkus and a database cannot run on this site, so the real project files are shown read-only and written to be copied into a real project created at code.quarkus.io. The two TryIts run a faithful model of the service in plain Java: first the layers and validation, then a working HTTP server with the same routes, so you can see the behavior you are building.

1. Requirements

  • GET /books lists books; supports ?author= filter and ?page=&size= paging.
  • GET /books/{id} returns one book or 404.
  • POST /books creates a book (editors only); validates input; returns 201 with a Location header.
  • DELETE /books/{id} removes a book (admins only).
  • Errors have one JSON shape. Health, metrics and OpenAPI are available. Tests cover the API.

2. Create the project

Terminal
quarkus create app org.acme:bookshop \
  --extension='rest-jackson,hibernate-orm-panache,jdbc-postgresql,hibernate-validator,smallrye-health,micrometer-registry-prometheus,smallrye-openapi,oidc'
cd bookshop
quarkus dev

Dev mode starts PostgreSQL through Dev Services, so there is nothing to install (dev mode).

PROPERTIES
# application.properties
quarkus.datasource.db-kind=postgresql
quarkus.hibernate-orm.database.generation=none
%dev.quarkus.hibernate-orm.database.generation=drop-and-create
%dev.quarkus.hibernate-orm.sql-load-script=import-dev.sql
quarkus.security.jaxrs.deny-unannotated-endpoints=true
bookshop.page.max-size=100

3. The entity

Java
@Entity
public class Book extends PanacheEntity {

    @NotBlank @Size(max = 200)
    public String title;

    @NotBlank
    public String author;

    @Min(1)
    public int pages;

    public static List<Book> byAuthor(String author, int page, int size) {
        return find("author", Sort.by("title"), author).page(page, size).list();
    }
}

Panache's active-record style keeps this short; the repository style (a separate PanacheRepository<Book>) is the better choice if you prefer testing services with fake repositories.

4. The resource

Java
@Path("/books")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class BookResource {

    @ConfigProperty(name = "bookshop.page.max-size") int maxSize;

    @GET
    @PermitAll
    public List<Book> list(@QueryParam("author") String author,
                           @QueryParam("page") @DefaultValue("0") int page,
                           @QueryParam("size") @DefaultValue("20") int size) {
        int safeSize = Math.min(size, maxSize);
        return author == null
            ? Book.findAll(Sort.by("title")).page(page, safeSize).list()
            : Book.byAuthor(author, page, safeSize);
    }

    @GET @Path("/{id}")
    @PermitAll
    public Book get(@PathParam("id") long id) {
        return (Book) Book.<Book>findByIdOptional(id)
                .orElseThrow(() -> new NotFoundException("No book " + id));
    }

    @POST
    @RolesAllowed("editor")
    @Transactional
    public Response create(@Valid Book book, @Context UriInfo uri) {
        book.persist();
        return Response.created(uri.getAbsolutePathBuilder().path(String.valueOf(book.id)).build())
                       .entity(book).build();
    }

    @DELETE @Path("/{id}")
    @RolesAllowed("admin")
    @Transactional
    public void delete(@PathParam("id") long id) {
        if (!Book.deleteById(id)) throw new NotFoundException("No book " + id);
    }
}

Pieces you built in earlier chapters: REST endpoints, Panache, validation with @Valid, and security annotations. The paging limit comes from configuration.

5. One error shape

Java
@Provider
public class ApiExceptionMapper implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable t) {
        if (t instanceof WebApplicationException w) {
            return json(w.getResponse().getStatus(), w.getMessage());
        }
        if (t instanceof ConstraintViolationException v) {
            return json(400, v.getConstraintViolations().stream()
                .map(c -> c.getPropertyPath() + " " + c.getMessage()).sorted().toList().toString());
        }
        Log.error("Unhandled", t);
        return json(500, "Internal error");     // no stack traces to clients
    }

    private Response json(int status, String message) {
        return Response.status(status).type(MediaType.APPLICATION_JSON)
                       .entity(Map.of("status", status, "message", message)).build();
    }
}

Layers of the bookshop

Resource HTTP, status codes, security.
Validation Bean Validation on input.
Panache Entity and queries.
PostgreSQL Dev Services in dev and test.

Small layers, each tested on its own.

1 / 2

6. Model it in plain Java

This model has the same layers: a validated entity, a repository, a paging rule and a resource that returns status codes. Read it as an executable spec of the behavior above.

Java Stand-in: validation, paging and the resource logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

7. Test it

Java
@QuarkusTest
class BookResourceTest {

    @Test
    void anyoneCanList() {
        given().when().get("/books").then().statusCode(200);
    }

    @Test @TestSecurity(user = "ed", roles = "editor") @TestTransaction
    void editorCreates() {
        given().contentType("application/json")
          .body("{\"title\":\"Solaris\",\"author\":\"Lem\",\"pages\":204}")
          .when().post("/books")
          .then().statusCode(201).header("Location", containsString("/books/"));
    }

    @Test @TestSecurity(user = "ed", roles = "editor")
    void invalidBookIs400() {
        given().contentType("application/json").body("{\"title\":\"\",\"pages\":0}")
          .when().post("/books").then().statusCode(400);
    }

    @Test @TestSecurity(user = "ed", roles = "editor")
    void editorCannotDelete() {
        given().when().delete("/books/1").then().statusCode(403);
    }

    @Test
    void anonymousCannotCreate() {
        given().contentType("application/json").body("{}")
          .when().post("/books").then().statusCode(401);
    }
}

These follow testing with @QuarkusTest and mocks and profiles. Add an @QuarkusIntegrationTest subclass for the packaged jar.

8. A runnable HTTP model

The second model is a real HTTP server (JDK HttpServer) with the same routes, a client that exercises it, and the status codes you expect from Quarkus. It runs on a random loopback port.

Java Stand-in: the bookshop routes over real HTTP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

9. Observe and ship

  • GET /q/health and /q/metrics already work; add a custom readiness check if you call an external service (health and metrics).
  • GET /q/openapi and /q/swagger-ui document the API (OpenAPI tutorial).
  • Add Flyway (quarkus-flyway) for versioned schema changes and set database.generation=none in production.
  • Package with Jib and generate manifests (containers and Kubernetes).

Extension challenges

  1. Add PUT /books/{id} with optimistic locking (@Version field and a 409 response).
  2. Add an Author entity and a many-to-one relationship; avoid N+1 queries with a fetch join.
  3. Publish a book-created event with an Emitter (messaging).
  4. Cache GET /books/{id} with quarkus-cache (@CacheResult).
  5. Build it native and compare startup time with the JVM jar.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use %dev.quarkus.hibernate-orm.database.generation=drop-and-create instead of the unprefixed key?

    Schema recreation is convenient in dev but dangerous in production; the profile prefix keeps it in dev only.
  2. 2. Which status should POST /books return on success, and which header?

    Creating a resource returns 201 Created with a Location header pointing to it.
  3. 3. What does @TestTransaction give in the editorCreates test?

    Changes made during the test are rolled back at the end.
  4. 4. Why cap the size parameter with a configured maximum?

    Unbounded page sizes let one request load the entire table into memory.

Summary

  • Create the project with the right extensions; Dev Services supplies PostgreSQL.
  • Panache entity + REST resource + Bean Validation + exception mapper give a clean API.
  • Security annotations and deny-unannotated-endpoints keep it closed by default.
  • Tests cover success, validation and security; health, metrics and OpenAPI come with extensions.
  • Ship as a container with generated Kubernetes manifests.

Next: Project: An Event-Driven Order Pipeline