Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท REST Endpoints

REST Resources and Methods

Build REST endpoints in Quarkus: resource classes, @Path templates, HTTP method annotations, @RestPath and @RestQuery, content types and status codes.

A REST endpoint in Quarkus is a plain Java class with annotations from Jakarta REST (formerly JAX-RS). You describe what URL, which HTTP method, which content type and which return value, and Quarkus generates the glue at build time. The extension that does this work is called Quarkus REST (artifact quarkus-rest, the successor of RESTEasy Reactive). It runs on the Vert.x event loop but also lets you write ordinary blocking code, as you will see in Event Loop and Blocking.

The real Quarkus framework cannot run on this site, so the Quarkus code below is read-only. Each lesson adds a small, labelled Java stand-in that models the rule being taught, and those stand-ins do run.

A resource class

A resource class groups related endpoints under one base path:

Java
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import java.util.List;

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

    @GET
    public List<String> list() {
        return List.of("Dune", "Emma");
    }

    @GET
    @Path("/{id}")
    public String one(@PathParam("id") long id) {
        return "Book " + id;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public String create(String title) {
        return "created " + title;
    }
}

The class-level @Path is the prefix. A method-level @Path is appended to it. The method annotation (@GET, @POST, @PUT, @PATCH, @DELETE, @HEAD, @OPTIONS) selects the HTTP verb. A method without its own @Path handles the class path itself.

By default Quarkus creates one instance per application of a resource class (it behaves like @Singleton). Do not keep per-request data in fields. If you really need request state, add @RequestScoped to the class, or just pass data through method parameters.

Reading parameters

Annotated method parameters pull values out of the request:

Annotation Reads from Example
@PathParam / @RestPath a in the path /books/42
@QueryParam / @RestQuery the query string /books?limit=5
@HeaderParam / @RestHeader a request header Accept-Language
@CookieParam / @RestCookie a cookie session
@FormParam / @RestForm an HTML form field title
no annotation the request body JSON object

The @Rest... variants are Quarkus REST shortcuts: the name is optional because Quarkus reads it from the parameter name (the -parameters compiler flag is on in Quarkus projects).

Java
@GET
@Path("/{id}/reviews")
public List<Review> reviews(@RestPath long id,
                            @RestQuery @DefaultValue("10") int limit,
                            @RestQuery String sort) {
    return reviewService.find(id, limit, sort);
}

Types are converted for you: numbers, booleans, enums, UUID, LocalDate, lists (?tag=a&tag=b becomes List<String>), Optional<T>. A value that cannot be converted (/books/abc for a long) produces a 404 for path parameters and a 400 for query parameters, without any code from you.

Regular expressions in paths

A template can restrict what it matches: @Path("/{id: \\d+}"). Then /books/abc falls through to another method or becomes a 404.

Content types

@Produces lists the media types a method can return. @Consumes lists what it accepts in the request body. Quarkus matches them against the Accept and Content-Type headers:

  • A request with an unsupported Content-Type receives 415 Unsupported Media Type.
  • A request whose Accept header matches none of your @Produces types receives 406 Not Acceptable.
  • A path that exists but not for that verb receives 405 Method Not Allowed.

Put @Produces on the class to set a default for every method and override it where needed. With the quarkus-rest-jackson extension, application/json is handled automatically. Without a @Produces, Quarkus picks a type from the return value (strings become text/plain).

Choosing the response

A method can return a value, void, or a response object:

Java
import org.jboss.resteasy.reactive.RestResponse;

@POST
public RestResponse<Book> create(Book book, @Context UriInfo uri) {
    Book saved = service.save(book);
    URI location = uri.getAbsolutePathBuilder().path(String.valueOf(saved.id)).build();
    return RestResponse.created(location);   // 201 + Location header
}

@GET
@Path("/{id}")
public RestResponse<Book> find(@RestPath long id) {
    Book book = service.find(id);
    return book == null ? RestResponse.notFound() : RestResponse.ok(book);
}

RestResponse<T> is the typed version of jakarta.ws.rs.core.Response; the generic type tells OpenAPI and the serializer what the body is. For simple cases, annotate the method instead: @ResponseStatus(201) sets the success status, and a void method returns 204 No Content by default.

The convention for return values:

  • GET returns 200 with a body, or 404 if the thing does not exist.
  • POST that creates returns 201 with a Location header.
  • PUT and PATCH return 200 (with the updated body) or 204.
  • DELETE returns 204.

How a request finds its method

From request to method

Path Class path plus method path must match.
Verb GET, POST and so on pick the method.
Content type Consumes and Produces must fit the headers.
Invoke Parameters are converted and passed in.

A failed step gives 404, 405, 415 or 406.

1 / 2

The order matters, and the status code tells you which step failed. This stand-in models the dispatch rules with a tiny route table. It is plain Java, not Quarkus, but follows the same decision order: path first, then verb, then content type.

Java Stand-in: 404, 405 and 415 dispatch

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.

Content negotiation

The Accept header can list several types with quality values, like application/json;q=0.9, text/plain;q=0.5. Quarkus picks the best type that both sides support. This stand-in implements the core of that choice:

Java Stand-in: choosing a media type from Accept

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.

Common mistakes

  • Storing request data in a field. The resource is shared by all requests. Use parameters.
  • Forgetting @Consumes on POST. Without it a method accepts anything, and a wrong body fails later with a less helpful error.
  • Returning null from a method. Quarkus answers 204 for null (or 404 for Uni/Optional.empty-style cases in some setups). Be explicit with RestResponse.
  • Mixing jakarta.ws.rs and old javax.ws.rs. Quarkus 3 uses jakarta.* only.

Open /q/dev-ui while running quarkus dev: the REST card lists every endpoint, its method, path and content types, so you can check that your annotations produce the routes you intended.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A path exists but only for GET, and the client sends DELETE. What status does Quarkus return?

    The path matched but no method handles that verb, which is exactly what 405 means. 404 is for a path that matches nothing.
  2. 2. What does @RestQuery int limit do compared with @QueryParam("limit") int limit?

    @RestQuery is a Quarkus REST shortcut that infers the parameter name. Behaviour is the same.
  3. 3. Which response is conventional after a POST that creates a new resource?

    201 Created with a Location header pointing to the new resource is the standard answer.
  4. 4. Why should you avoid keeping per-request data in fields of a resource class?

    Resources behave like singletons unless you add @RequestScoped, so mutable fields are shared across threads.

Summary

  • A resource class uses @Path for the prefix and @GET, @POST, @PUT, @PATCH, @DELETE for verbs.
  • @RestPath, @RestQuery, @RestHeader, @RestForm read request data; the unannotated parameter is the body.
  • @Produces and @Consumes drive negotiation and 406 / 415 errors; a wrong verb gives 405, a wrong path 404.
  • Return a value, void (204) or a RestResponse<T> to control status and headers.
  • Resources are shared, so keep them stateless.

Next: JSON and Bean Validation