Skip to content
javahacks.dev
Quarkus

Quarkus Tutorial for Beginners From Zero to REST API

Create a Quarkus 3 project, add a REST endpoint with JSON, run it in dev mode and write a test, in about fifteen minutes and with no prior Quarkus knowledge.

6 min read
Summarize in AI
Flat illustration of startup time of a JVM compared with a native image, with the Quarkus, Spring, Spring Boot and Kubernetes logos.

Quarkus is a Java framework built for fast startup and quick feedback. This tutorial creates a project on JDK 25, adds a small REST API that returns JSON, tests it, runs it in dev mode and packages it. You need a JDK and Maven, or the Quarkus command line tool. It is a starting point; the mapping from what you may know in Spring is in Quarkus for Spring developers.

Create the project

With the Maven plugin, passing the extensions you want at creation:

Shell
mvn io.quarkus.platform:quarkus-maven-plugin:3.27.0:create \
  -DprojectGroupId=dev.javahacks -DprojectArtifactId=quarkus-demo \
  -Dextensions='rest-jackson'
cd quarkus-demo

With the CLI, quarkus create app dev.javahacks:quarkus-demo --extension=rest-jackson does the same thing. The generated project contains a pom.xml that imports the Quarkus BOM, which pins compatible versions of every extension, a Maven wrapper, a set of Dockerfiles and a sample resource. The platform version above was current when this was written; check the getting started guide for the latest number before you copy it.

Write a resource

src/main/java/dev/javahacks/ProductResource.javajava
package dev.javahacks;

import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.util.List;

@Path("/products")
@Produces(MediaType.APPLICATION_JSON)
public class ProductResource {

    public record Product(long id, String name) {}

    private final List<Product> products = List.of(
            new Product(1, "Espresso machine"),
            new Product(2, "Grinder"));

    @GET
    public List<Product> all() {
        return products;
    }

    @GET
    @Path("/{id}")
    public Product one(@PathParam("id") long id) {
        return products.stream()
                .filter(p -> p.id() == id)
                .findFirst()
                .orElseThrow(() -> new jakarta.ws.rs.NotFoundException("No product " + id));
    }
}

The annotations are Jakarta REST, formerly JAX-RS, so if you have seen them on a Jakarta EE server they are the same. A resource class is an application-scoped CDI bean by default with this extension, which means one instance serves every request. That is why the list is a final field and why you must not keep per-request state in fields. Throwing NotFoundException produces a 404 response with no extra code. The record is serialised by Jackson because the rest-jackson extension is on the classpath.

Run in dev mode

Shell
./mvnw quarkus:dev

The terminal prints the Quarkus banner, then Listening on: http://localhost:8080. Open http://localhost:8080/products and the JSON appears. Change a product name in the source, save, and reload the browser. The code recompiles on that request, with no restart and no manual build. The terminal accepts single key commands while it runs, and r runs the tests, which is explained in dev mode and continuous testing. The Dev UI is at http://localhost:8080/q/dev-ui; it lists extensions, beans, configuration and endpoints of the running application, which is the quickest way to answer the question of what is loaded.

Add a test

Add quarkus-junit5 and rest-assured to the test scope if the generator did not, then write:

src/test/java/dev/javahacks/ProductResourceTest.javajava
package dev.javahacks;

import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;

import io.quarkus.test.common.http.TestHTTPEndpoint;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;

@QuarkusTest
@TestHTTPEndpoint(ProductResource.class)
class ProductResourceTest {

    @Test
    void returnsOneProduct() {
        given().when().get("/1")
               .then().statusCode(200)
               .body("name", is("Espresso machine"));
    }

    @Test
    void unknownProductIs404() {
        given().when().get("/99").then().statusCode(404);
    }
}

@QuarkusTest starts the real application once for the test class, so these are integration tests against a real HTTP server, not mock objects. @TestHTTPEndpoint prefixes each path with the resource's @Path, which is why the test calls /1. Run it with ./mvnw test, or leave dev mode running and press r, so every save reruns the tests.

Read configuration

Properties live in src/main/resources/application.properties, and a bean reads them with an annotation:

properties
shop.currency=EUR
%dev.shop.currency=USD
java
@ConfigProperty(name = "shop.currency", defaultValue = "EUR")
String currency;

The %dev. prefix applies a value only in the dev profile, and %test. and %prod. work the same way. That single file replaces separate per-environment files for most small applications.

Package and run

Shell
./mvnw package
java -jar target/quarkus-app/quarkus-run.jar

The output is a directory, target/quarkus-app, with a fast-jar layout: your classes, the libraries, and a small launcher. Run it with java -jar as above. Copy the whole directory when deploying, not only the launcher jar. Startup is typically well under a second for an application this size, though you should time your own.

Accept input and validate it

A read-only API shows little. Add a POST that creates a product and rejects bad input. Add the quarkus-hibernate-validator extension, then annotate the request type:

java
public record NewProduct(@NotBlank String name, @Positive long priceCents) {}

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response create(@Valid NewProduct input, @Context UriInfo uri) {
    Product created = new Product(nextId.incrementAndGet(), input.name());
    products.add(created);
    return Response.created(uri.getAbsolutePathBuilder().path(String.valueOf(created.id())).build())
                   .entity(created)
                   .build();
}

@Valid triggers Bean Validation before the method runs. A blank name produces a 400 response with a body that lists the violated constraints, and your method is never called. For this to compile, the list in the resource must be a mutable one such as CopyOnWriteArrayList, and nextId an AtomicLong; a shared list written by concurrent requests needs that care, and it is the first sign that an in-memory store is not an answer for anything real. The 201 Created response with a Location header is the conventional reply to a POST that creates a resource, and the test for it checks both the status and the header.

java
@Test
void createReturns201WithLocation() {
    given().contentType("application/json")
           .body("{\"name\":\"Kettle\",\"priceCents\":2500}")
           .when().post()
           .then().statusCode(201)
           .header("Location", containsString("/products/"));
}

Add a second test with a blank name and expect 400. Tests for the failure path are the ones people skip, and they catch the validation annotation you forgot to add.

Understand what dev mode is doing

Dev mode is not a faster compile loop alone. Quarkus does most of its work at build time, and in dev mode it reruns the relevant build steps when a source file changes and swaps the result into the running JVM. That is why a change to an annotation, which would need a restart in many frameworks, takes effect on the next request. It also explains one surprise: changes to a library jar or to the pom.xml are not picked up live, and dev mode restarts itself or asks you to. If a change seems ignored, look at the terminal; it usually tells you why.

Next: a database

Add the quarkus-hibernate-orm-panache and quarkus-jdbc-postgresql extensions and, in dev mode, Quarkus starts a PostgreSQL container for you with no configuration, a feature described in Dev Services. It needs Docker running. Replace the in-memory list with a Panache entity and the same tests keep passing against a real database.

If something goes wrong

Three problems account for most first-day questions. The port is taken: another process is on 8080, and the startup log says so; change it with quarkus.http.port=8081 in application.properties. The first run is slow: Maven is downloading the platform, and later runs reuse the local repository. A change is not picked up: dev mode only watches the project, so a dependency you added to the pom.xml needs a restart, which dev mode normally offers on the next request. When the cause is not obvious, read the terminal output from the top, because Quarkus reports a configuration problem at startup with the property name, and that line is usually the whole answer.

What this tutorial leaves out

An in-memory list is not persistence, and a production service also needs health checks, metrics, security and validation extensions. Native images come after you are comfortable with the JVM mode. The Quarkus guides have one guide per extension, and the REST API design rules apply to this endpoint exactly as they do to any other.

Also inSpring MVC
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.