Jakarta REST RESTful Web Services Explained With Examples
Learn Jakarta REST (JAX-RS): resource classes, path and parameter annotations, content negotiation, providers, exception mappers, filters and the client API.

Jakarta REST, formerly JAX-RS, is the standard Java API for building HTTP services. You write plain classes, annotate them, and the runtime handles routing, content negotiation and serialisation. It is the API behind RESTEasy, Jersey and Quarkus REST, and the one an application server such as WildFly or Payara provides. This post covers resource classes, parameter binding, return types, content negotiation, exception mappers, filters and the client, using Jakarta EE 11 (Jakarta REST 4.0) and JDK 25.
An application and a resource
An application class sets the base path. In a servlet container it activates the runtime with no web.xml:
@ApplicationPath("/api")
public class ApiApplication extends Application { }A resource is any class with @Path on the class or a method:
@Path("/books")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApplicationScoped
public class BookResource {
@Inject BookService books;
@GET
public List<Book> list(@QueryParam("author") String author,
@QueryParam("page") @DefaultValue("0") int page) {
return books.find(author, page);
}
@GET @Path("/{id}")
public Book get(@PathParam("id") long id) {
return books.find(id).orElseThrow(() -> new NotFoundException("book " + id));
}
@POST
public Response create(@Valid BookInput input, @Context UriInfo uri) {
Book saved = books.add(input);
return Response.created(uri.getAbsolutePathBuilder().path(String.valueOf(saved.id())).build())
.entity(saved).build();
}
}The URL for get is /api/books/{id}: application path, class path, method path. @GET, @POST, @PUT, @DELETE, @PATCH, @HEAD and @OPTIONS select the HTTP method. Parameters come from @PathParam, @QueryParam, @HeaderParam, @CookieParam and @FormParam, and Jakarta REST converts them to int, long, UUID, enums or any type with a valueOf(String) or a single-string constructor. A parameter without an annotation is the request body, and there can be only one. @DefaultValue supplies a fallback for a missing query parameter.
Resource classes are request-scoped by default in the specification. Add a CDI scope such as @ApplicationScoped for a stateless resource, which avoids creating an instance per request, and inject services with @Inject. Bean validation applies with @Valid on the body, as described in Bean Validation.
Return types decide how much control you have
A method can return a plain object, and the runtime serialises it with status 200, or 204 if it returns void or null. That covers most reads. When you need a status code, headers or a body-less answer, return Response:
return Response.status(Response.Status.CONFLICT)
.entity(new ApiError("duplicate isbn"))
.header("X-Reason", "isbn")
.build();Response.created(uri) returns 201 with a Location header, and Response.noContent() returns 204. The mapping of results to status codes follows the same reasoning as in Spring MVC status codes. If you only want the type to document itself, Response hides the entity type from tooling; use Response where you need control and the entity type elsewhere. Returning a CompletionStage<T> or Uni<T> (with Mutiny on Quarkus) frees the request thread for asynchronous work, and a StreamingOutput or Multi streams a large body.
Content negotiation
@Produces lists the media types a method can return, and the runtime matches them against the request's Accept header. @Consumes does the same for Content-Type. When nothing matches, the answer is 406 for a bad Accept and 415 for an unsupported body. Two methods with the same path and different @Produces coexist, and the runtime picks by the client's preference and the q values.
@GET @Produces(MediaType.APPLICATION_JSON)
public Book json(...) { /* ... */ }
@GET @Produces("text/csv")
public String csv(...) { /* ... */ }Serialisation is done by MessageBodyWriter and MessageBodyReader providers. On a full application server, JSON-B is the default, and Jackson is a common substitute through a provider or, on Quarkus, the extension described in Quarkus REST with Jackson. Declare the JSON provider you use explicitly, because the default differs between runtimes and a different one changes how dates and nulls render.
Exception mappers
Throw a WebApplicationException subclass such as NotFoundException and the runtime converts it to the right status. For your own exceptions, register a mapper once:
@Provider
public class DuplicateMapper implements ExceptionMapper<DuplicateBookException> {
@Override
public Response toResponse(DuplicateBookException e) {
return Response.status(Response.Status.CONFLICT)
.entity(new ApiError(e.getMessage()))
.type(MediaType.APPLICATION_JSON)
.build();
}
}The mapper with the closest exception type wins, the same rule as in other frameworks. A mapper for Throwable is the net for unexpected failures; log inside it, and return a body that reveals nothing about internals. Keep the error body one shape across the API, as argued in REST design rules.
Filters and interceptors
Filters run around the request and response. A ContainerRequestFilter can reject a call before it reaches the method, which is where authentication checks and request ids belong:
@Provider
@Priority(Priorities.AUTHENTICATION)
public class ApiKeyFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext ctx) {
String key = ctx.getHeaderString("X-Api-Key");
if (!ApiKeys.valid(key)) {
ctx.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
}
}By default a filter applies to every resource. Add @PreMatching to run before the resource is chosen, or use a @NameBinding annotation to apply the filter only to resources you mark. ReaderInterceptor and WriterInterceptor wrap the entity streams, and are the place for compression or signing, not for business rules.
The client
Jakarta REST includes a client with the same media type machinery:
try (Client client = ClientBuilder.newClient()) {
Book book = client.target("https://catalog.example.com/api")
.path("books/{id}").resolveTemplate("id", 42)
.request(MediaType.APPLICATION_JSON)
.get(Book.class);
}Close the client, because it holds a connection pool, and share one instance per target rather than building one per call. Set timeouts through the implementation's properties; the spec's connectTimeout and readTimeout builder methods exist for this. For a typed client with interfaces, MicroProfile Rest Client is more convenient.
Sub-resources, asynchronous responses and testing
A method can return another resource object instead of data, which lets a path be delegated. A method annotated only with @Path("{id}/items") and no HTTP method returns an ItemsResource, and the runtime continues matching against the returned object. It keeps large resources readable, at the cost of hiding the full URL map in several classes. Document the final paths in the OpenAPI output so that readers do not have to reconstruct them.
For long-running work, inject @Suspended AsyncResponse and resume it from another thread, or return a CompletionStage. Set a timeout with setTimeout, because a response that is never resumed holds a connection until the container gives up. The pattern suits calls that wait on a slow dependency, and it combines with a managed executor so that the work uses a container-managed thread.
Test resources at two levels. A plain unit test calls the resource method with a mocked service, which checks the logic and not the annotations. An integration test starts the runtime (Quarkus test, Arquillian, or an embedded server) and sends real HTTP requests, which checks routing, content negotiation, validation and exception mappers together. The second level is what catches a wrong @Produces or a missing @Provider, which no unit test can see. Check the status line, the Content-Type, and one error response per mapper.
Mistakes that cost time
A resource method that declares two unannotated parameters fails at deployment, because only one entity parameter is allowed. A mapper that is not discovered is nearly always missing @Provider or sits in a package that a Quarkus or Spring-based runtime does not scan. A @Path template such as {id: [0-9]+} accepts a regular expression, which turns a non-numeric id into a 404 before your code runs. And a resource returning a JPA entity directly will either fail with a lazy-loading error or expose columns you did not intend; return a DTO.
Choosing it
Jakarta REST fits services that run in a Jakarta EE server or on Quarkus, and teams that want a standard instead of a framework. Its model is annotation-heavy and close to Spring MVC's, so concepts transfer: compare with the Spring MVC REST controller. If the work needs managed threads for background tasks, see managed executors. The specification is at jakarta.ee, and the Jakarta EE tutorial has runnable examples.


