Java EE / Jakarta EE

Jakarta REST (JAX-RS 3.1): Building and Consuming HTTP APIs

Intermediate8 min readUpdated

Jakarta RESTful Web Services (JAX-RS) is the platform's annotation-driven API for HTTP services and the model that Jersey, RESTEasy and Apache CXF implement. This guide shows how requests are routed to resource methods, how parameters and JSON bodies are bound, how to return the right status codes and error bodies, how filters, interceptors and exception mappers add cross-cutting behaviour, and how to call other services with the client API — with the design and security mistakes that show up in real APIs.

What you will learn

  • Declare an application and resource classes and understand how requests are matched
  • Bind path, query, header and body parameters and return Response objects with correct status codes
  • Map exceptions to error responses and apply Bean Validation to inputs
  • Add filters, interceptors and providers for authentication, logging and content handling
  • Consume services with the Jakarta REST client API and use asynchronous responses and Server-Sent Events

Jakarta RESTful Web Services — JAX-RS in every conversation, and in the package name until the jakarta.ws.rs rename — maps HTTP onto plain Java methods. You annotate a class with a path and its methods with HTTP verbs, declare where each parameter comes from, and return an object; the runtime handles routing, content negotiation, serialisation and error responses. Where the servlet API exposes HTTP as it is, Jakarta REST exposes it the way an API designer thinks about it: resources, representations, status codes and media types. The design principles of good HTTP APIs belong to the architecture subject; this guide is about doing them well with this API.

Application, resources and matching

A resource class is a plain class, usually a CDI bean, with a @Path. Its methods carry an HTTP-method annotation, optionally a sub-path, and declarations of what they consume and produce. One Application subclass with @ApplicationPath sets the root of the API and, if you leave it empty, registers every resource and provider the runtime finds.

package shop.api;

import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;

@ApplicationPath("/api")            // all resources live under /<context>/api
public class ShopApplication extends Application { }
package shop.api;

import java.net.URI;
import java.util.List;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.*;

@Path("/orders")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@RequestScoped
public class OrderResource {

    @Inject OrderService orders;
    @Context UriInfo uriInfo;           // request-scoped injection of URI details

    @GET
    public List<OrderSummary> list(@QueryParam("status") OrderStatus status,
                                   @QueryParam("page") @DefaultValue("0") int page,
                                   @QueryParam("size") @DefaultValue("20") int size) {
        return orders.list(status, page, size);
    }

    @GET
    @Path("/{id}")
    public OrderDetail get(@PathParam("id") long id) {
        return orders.find(id).orElseThrow(NotFoundException::new);   // 404
    }

    @POST
    public Response create(@Valid NewOrder request) {
        OrderDetail created = orders.place(request);
        URI location = uriInfo.getAbsolutePathBuilder().path(Long.toString(created.id())).build();
        return Response.created(location).entity(created).build();    // 201 + Location
    }

    @PATCH
    @Path("/{id}/status")
    public OrderDetail changeStatus(@PathParam("id") long id, StatusChange change) {
        return orders.changeStatus(id, change.status());
    }

    @DELETE
    @Path("/{id}")
    public void cancel(@PathParam("id") long id) {
        orders.cancel(id);                                             // void -> 204 No Content
    }
}

Matching proceeds in stages: the runtime picks the resource class whose @Path matches the longest prefix, then a method whose sub-path and HTTP verb match, then filters by the request's Content-Type against @Consumes and the Accept header against @Produces. A path that matches but no verb gives 405 Method Not Allowed; a verb that matches but no media type gives 415 Unsupported Media Type or 406 Not Acceptable. Path templates can carry regular expressions — @Path("/{id: \\d+}") — so that /orders/abc is a 404 rather than a conversion error. A method with a @Path but no verb annotation is a sub-resource locator: it returns another resource object that continues the matching, which is how you factor /orders/{id}/lines into its own class.

Resource classes are request-scoped by default when they are not CDI beans; declaring @RequestScoped or @ApplicationScoped explicitly makes the life cycle obvious and lets CDI inject into them. An application-scoped resource must be thread-safe, and @Context fields in it are proxies that resolve per request.

Parameters and bodies

Parameters come from one of several sources, each with an annotation: @PathParam, @QueryParam, @HeaderParam, @CookieParam, @FormParam (URL-encoded form bodies) and @MatrixParam. Conversion from the string handles primitives, enums, anything with a String constructor or static valueOf/fromString, and List<T> for repeated values; @DefaultValue covers absent parameters. A group of related parameters can be bundled in a class annotated on its fields and injected with @BeanParam, which keeps signatures short for search endpoints.

The one unannotated parameter is the entity body. It is read by a MessageBodyReader chosen by the Content-Type: JSON bodies become objects through JSON Binding, String, byte[], InputStream and File are supported natively, and Jakarta REST 3.1 finally standardised multipart with EntityPart:

@POST
@Path("/{id}/attachments")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response attach(@PathParam("id") long id, List<EntityPart> parts) throws IOException {
    for (EntityPart part : parts) {
        if (part.getFileName().isPresent()) {
            orders.attach(id, part.getFileName().get(), part.getMediaType(), part.getContent());
        }
    }
    return Response.noContent().build();
}

JSON Binding needs a public no-argument constructor and getters/setters or public fields for classic classes; records are supported by Yasson 3, the JSON-B compatible implementation, since JSON-B 3.0. Field naming, date formats, null handling and property order are controlled with @JsonbProperty, @JsonbDateFormat, @JsonbNillable and @JsonbPropertyOrder, or globally with a JsonbConfig registered through a ContextResolver<Jsonb>. Keep API types (NewOrder, OrderDetail) separate from JPA entities: serialising an entity walks lazy associations, leaks internal fields and couples your API to your schema.

Responses and status codes

A method returning an object produces 200 OK with the serialised entity, void produces 204 No Content, and null produces 204 as well. Anything else goes through Response:

SituationBuild withStatus
Resource createdResponse.created(uri).entity(body)201 with Location
Accepted for background processingResponse.accepted()202
Nothing to returnResponse.noContent()204
Conditional GET matchedrequest.evaluatePreconditions(etag) returns non-null304
Client error with a bodyResponse.status(Status.CONFLICT).entity(problem)409 etc.

Headers are added with .header(...), caching with .cacheControl(...) and .tag(...), and Response.temporaryRedirect(uri) covers redirects. Response also carries a GenericEntity for returning a List<T> with its type information intact when the runtime cannot infer it. Status codes carry meaning to clients and intermediaries; the web subject has a status-code reference to check the exact semantics before you pick one.

Errors: exceptions and mappers

Throwing a WebApplicationException subclass — NotFoundException, BadRequestException, ForbiddenException, NotAuthorizedException, ClientErrorException(Response) — sends the matching status. For a consistent error body across the API, register an ExceptionMapper per exception type:

import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;

@Provider
public class DomainExceptionMapper implements ExceptionMapper<DomainException> {

    @Override
    public Response toResponse(DomainException e) {
        var problem = new Problem("https://api.example.com/problems/" + e.code(),
                                  e.getMessage(), e.status());
        return Response.status(e.status())
                       .type("application/problem+json")     // RFC 9457 problem details
                       .entity(problem)
                       .build();
    }
}

@Provider classes are discovered automatically. The runtime chooses the mapper for the nearest superclass of the thrown exception, so a mapper for Throwable catches everything the others miss — and should log the stack trace and return a generic 500 without the exception message, which may contain SQL or internal paths. Bean Validation failures (ConstraintViolationException) are mapped by the runtime to 400 for request data; add your own mapper if you want the violations listed in the body. Never let a PersistenceException reach the client unmapped.

Validation

Annotate DTO fields with Bean Validation constraints and the parameter with @Valid, as in create above; constraints directly on parameters (@QueryParam("size") @Max(100) int size) work too. Validation happens before the method runs, in the same interceptor chain as everything else, so a resource method can assume its inputs are structurally valid and concentrate on business rules. Validation of return values (@Valid on the method) exists but is rarely worth the cost.

Filters, interceptors and other providers

Cross-cutting behaviour lives in providers:

  • ContainerRequestFilter runs before the resource method — authentication, correlation ids, rate limiting. Annotate it @PreMatching to run before routing (needed to rewrite the method or URI) or leave it post-matching so it can inspect the matched resource through ResourceInfo. Abort the request with requestContext.abortWith(Response.status(401).build()).
  • ContainerResponseFilter runs after — CORS and security headers, response logging.
  • ReaderInterceptor / WriterInterceptor wrap the entity streams — compression, signing, encryption.
  • MessageBodyReader / MessageBodyWriter add media types the runtime does not know, such as CSV or Protocol Buffers.
  • ParamConverterProvider teaches the runtime to convert parameters to your own types, such as a Money or an OrderId.

Filters apply globally by default. To target specific methods, define a name binding: an annotation meta-annotated with @NameBinding, placed on both the filter and the resource methods that need it, so @Secured on a method attaches the authentication filter only there. Ordering among filters uses @Priority with the constants in jakarta.ws.rs.Priorities (AUTHENTICATION runs before AUTHORIZATION, then HEADER_DECORATOR, ENTITY_CODER, USER).

Security itself is delegated: with Jakarta Security configured on the server, @RolesAllowed on a resource method (an enterprise bean, or a CDI bean on servers that support it) or securityContext.isUserInRole("admin") from an injected SecurityContext performs the check; with token-based APIs, a request filter validates the bearer token and installs a SecurityContext of its own. The JWT guide covers the token side.

The client API

Jakarta REST includes a fluent client for calling other services, which is also the basis of MicroProfile's type-safe Rest Client:

import jakarta.ws.rs.client.*;
import jakarta.ws.rs.core.*;

Client client = ClientBuilder.newBuilder()
        .connectTimeout(2, TimeUnit.SECONDS)
        .readTimeout(5, TimeUnit.SECONDS)
        .build();                                    // heavyweight: create once, reuse, close at shutdown

WebTarget orders = client.target("https://shop.example.com/api/orders");

try (Response response = orders.path("{id}").resolveTemplate("id", 42)
                               .request(MediaType.APPLICATION_JSON)
                               .header("Authorization", "Bearer " + token)
                               .get()) {
    if (response.getStatus() == 200) {
        OrderDetail order = response.readEntity(OrderDetail.class);
    }
}

OrderDetail created = orders.request()
        .post(Entity.json(new NewOrder("C-17", List.of(new Line("SKU-1", 2)))), OrderDetail.class);

WebTarget is immutable and reusable; Invocation.Builder sets headers per call. Reading the entity directly (get(OrderDetail.class)) throws WebApplicationException on error statuses, which is convenient in scripts and a nuisance in services — prefer reading the Response and mapping statuses explicitly. Always set timeouts: the defaults are infinite on most implementations. The client supports the same filters and providers as the server, plus reactive invocation (.rx().get(...) returning a CompletionStage).

Asynchronous responses and Server-Sent Events

A resource method can release the container thread while waiting: declare an @Suspended AsyncResponse parameter, return void, and call asyncResponse.resume(result) from another thread — a managed executor or a message listener. setTimeout plus a TimeoutHandler prevents requests hanging forever. This is the Jakarta REST face of servlet async processing and is worth it only when the wait is on something external.

Server-Sent Events stream a sequence of events over one long-lived response, which suits notifications and progress updates without WebSocket:

@GET
@Path("/{id}/events")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void events(@PathParam("id") long id, @Context SseEventSink sink, @Context Sse sse) {
    subscriptions.register(id, status ->
        sink.send(sse.newEventBuilder().name("status").data(status).mediaType(MediaType.APPLICATION_JSON).build()));
}

SseBroadcaster fans one event out to many sinks. Remember that each open sink is a held connection; put an idle timeout on the load balancer and close sinks when the client disappears.

Java SE bootstrap

Jakarta REST 3.1 added SeBootstrap so an application can run without a servlet container: SeBootstrap.start(new ShopApplication(), SeBootstrap.Configuration.builder().port(8080).build()) starts the implementation's embedded server. It is handy for tools and tests, though in a Jakarta EE deployment the servlet container remains the host.

Common mistakes

  • Exposing JPA entities. Lazy-loading exceptions during serialisation, leaked fields and a schema-shaped API. Map to DTOs.
  • Returning 200 with an error body. Clients cannot rely on status codes; monitoring cannot count failures. Throw and map.
  • Catch-all mapper that echoes e.getMessage(). Leaks internals. Log server-side, return a generic problem.
  • No timeouts on the client. A stalled downstream service exhausts your thread pool. Set connect and read timeouts, and consider circuit breakers.
  • Creating a Client per request. Expensive and leaks connections. One per application, closed on shutdown.
  • @Path on a class without a scope. Works, but the life cycle is implementation-specific and CDI injection may not. Declare @RequestScoped or @ApplicationScoped.
  • Trusting @Consumes to validate input. It only matches the media type. Add Bean Validation and business checks.
  • Using GET for actions. Caches and prefetchers will call it. Use POST for anything with side effects.

Key takeaways

  • An @ApplicationPath application plus @Path resource classes is a complete API; matching considers path, verb and media types in that order, and mismatches produce 404, 405, 415 or 406 automatically.
  • Bind inputs with @PathParam, @QueryParam, @HeaderParam, @BeanParam and an unannotated body; JSON Binding handles JSON, and 3.1 standardised multipart with EntityPart.
  • Return objects for plain 200s and Response for everything else; use created(uri), noContent() and preconditions rather than hand-built statuses.
  • Throw exceptions and translate them in ExceptionMapper providers, ideally to RFC 9457 problem details; never leak internal messages.
  • Filters, interceptors, readers, writers and param converters are the extension points; name bindings and @Priority control where and in what order they apply.
  • The client API is fluent and reusable — one Client per application, explicit timeouts, explicit status handling.
  • @Suspended AsyncResponse, Server-Sent Events and SeBootstrap cover long waits, streaming and stand-alone use.

Sources and further reading

Frequently asked questions

Which implementation of Jakarta REST should I use?
Whichever your runtime ships: Jersey in GlassFish and Payara, RESTEasy in WildFly and Quarkus, the Liberty implementation (based on RESTEasy) in Open Liberty, Apache CXF in TomEE. Code written to the specification runs on all of them. Pick an implementation deliberately only for stand-alone use on Tomcat or with the Java SE bootstrap API.
How does Jakarta REST turn my object into JSON?
Through a MessageBodyWriter. Jakarta EE servers provide one backed by JSON Binding (JSON-B), so any class with getters or public fields is serialised automatically and annotations such as @JsonbProperty and @JsonbTransient customise it. Stand-alone deployments must add a JSON provider (Yasson for JSON-B, or Jackson) themselves.
Should a resource method return the entity or a Response?
Return the entity when success is always 200 with a body; the framework handles serialisation and content negotiation. Return Response when you need a different status, headers such as Location, or a conditional result. Never return Response just to wrap an error — throw an exception and let an ExceptionMapper produce the error body consistently.
Is Jakarta REST the same as Spring's @RestController?
Same idea, different annotations and container. Both map HTTP methods and paths to Java methods, bind parameters and serialise JSON. Jakarta REST is the standard implemented by several vendors and runs in any Jakarta EE server; Spring MVC is Spring's own. MicroProfile runtimes such as Quarkus and Helidon use Jakarta REST, which makes it the more portable skill across Java stacks.