Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 119 ยท Servlets and JSP

JAX-RS: RESTful Services with Jakarta REST

Build REST services with JAX-RS (Jakarta REST) - @Path resources, parameter injection, content negotiation, ExceptionMapper, filters, the client API and how it compares with Spring MVC.

You have already built REST APIs with plain Java and with Spring controllers. Before Spring Boot dominated, the Java EE platform had its own standard for the same job: JAX-RS, the Java API for RESTful Web Services, now called Jakarta REST (package jakarta.ws.rs, current version 4.0). It is the REST layer of every Jakarta EE server, and it is the programming model behind Quarkus (RESTEasy Reactive), WildFly, Open Liberty, Payara and Helidon. If you meet a codebase full of @Path and @Produces, this is it.

The model is delightfully small: you write a plain class, annotate it, and the runtime maps HTTP requests onto its methods. In this lesson you will learn the annotations, how parameters are injected, how content negotiation and error mapping work, and how the client API calls other services. No Jakarta REST implementation runs in this course's code runner, so the real framework code is read-only, and a runnable stand-in written in plain Java shows what the runtime does for you: scan annotations with reflection, match URLs, convert parameters, and serialize results with Jackson.

Resources and URL templates

A root resource class is any class annotated with @Path. Methods get an HTTP method annotation (@GET, @POST, @PUT, @DELETE, @PATCH, @HEAD, @OPTIONS) and optionally their own @Path, which is appended to the class path.

Java
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.*;
import java.net.URI;
import java.util.List;

@Path("/books")
@Produces(MediaType.APPLICATION_JSON)     // default response type for all methods
@Consumes(MediaType.APPLICATION_JSON)     // default request type
public class BookResource {

    @Inject BookService service;           // CDI injection (see the next lessons)

    @GET
    public List<Book> list(@QueryParam("q") String query,
                           @QueryParam("page") @DefaultValue("0") int page) {
        return service.search(query, page);
    }

    @GET
    @Path("/{id}")
    public Book get(@PathParam("id") int id) {
        return service.find(id).orElseThrow(() -> new NotFoundException("No book " + id));
    }

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

    @DELETE
    @Path("/{id}")
    public void delete(@PathParam("id") int id) {                  // void = 204 No Content
        service.delete(id);
    }
}

An application activates its resources with a small subclass of Application; on a Jakarta EE server the annotation alone is enough:

Java
@ApplicationPath("/api")
public class RestApplication extends Application { }   // books are now at /api/books

URL templates use placeholders, and you can add a regular expression: @Path("/{id: [0-9]+}") matches only numeric ids. When several methods could match, the runtime prefers the one with the most literal characters, then the most templates. HTTP method and media type then narrow the choice, which is why you can have two methods on the same path as long as their verbs or @Consumes/@Produces differ.

Parameter injection

The runtime reads the request and hands your method exactly what it asked for. The most common injection annotations:

Annotation Reads from
@PathParam("id") a template variable
@QueryParam("q") the query string (?q=dune)
@HeaderParam("Accept-Language") a request header
@CookieParam("session") a cookie
@FormParam("email") an application/x-www-form-urlencoded body
@MatrixParam, @BeanParam matrix parameters, or a bean that gathers several of the above
@DefaultValue("0") a fallback when the parameter is missing
@Context request-scoped helpers: UriInfo, HttpHeaders, SecurityContext, Request

A parameter without any annotation is the entity parameter: the request body, converted by a provider. Strings are converted to int, long, enums, LocalDate and any type with a valueOf(String) or a String constructor automatically. If conversion fails, the runtime answers 404 for a path or query parameter, or 400 for a header, cookie or form parameter, before your code runs.

Here is the heart of that process, rebuilt in plain Java. Custom @Path, @GET and friends are scanned with reflection, templates become regular expressions, and the entity is read with Jackson. The "HTTP requests" are just method calls so the focus stays on dispatching:

Java A tiny JAX-RS dispatcher with reflection

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.

Notice the 405 for PUT /books/2: the path matched but no method accepts that verb. A real runtime also sends an Allow header and handles HEAD and OPTIONS for you.

Entity providers and content negotiation

How does a Book become JSON? Through providers. A MessageBodyWriter turns a Java object into bytes for a media type, and a MessageBodyReader does the opposite. The runtime picks one by matching the Java type against the media type. You rarely write them: Jakarta REST servers ship with JSON-B or Jackson support, and Quarkus/RESTEasy use Jackson when quarkus-rest-jackson is present.

Negotiation works with the Accept request header and your @Produces. A resource can offer several formats:

Java
@GET
@Path("/{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Book get(@PathParam("id") int id) { ... }

A client that sends Accept: application/xml receives XML; one that asks for text/csv receives 406 Not Acceptable. A request body in an unsupported format, checked against @Consumes, yields 415 Unsupported Media Type. You get these status codes without writing any code.

When you need control over status, headers or cookies, return a Response. The builder is a fluent API: Response.ok(entity), Response.created(uri), Response.status(Response.Status.CONFLICT).entity(error), Response.noContent(), plus .header("ETag", ...), .cacheControl(...) and .link(...). A generic result can be returned with new GenericEntity<List<Book>>(books) {} when type erasure would hide the element type.

Exceptions and ExceptionMappers

Throw a WebApplicationException (or one of its subclasses such as NotFoundException, BadRequestException or ForbiddenException) and the runtime turns it into the matching status. For your own exception types, register an ExceptionMapper, the Jakarta REST counterpart of Spring's @RestControllerAdvice:

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

public record ApiError(int status, String message) { }

@Provider
public class BookNotFoundMapper implements ExceptionMapper<BookNotFoundException> {
    @Override
    public Response toResponse(BookNotFoundException e) {
        return Response.status(404)
                       .type(MediaType.APPLICATION_JSON)
                       .entity(new ApiError(404, e.getMessage()))
                       .build();
    }
}

@Provider makes the class discoverable. The runtime chooses the mapper whose type parameter is closest to the thrown exception, and an unmapped RuntimeException becomes a 500 response. A mapper is the right place to translate bean-validation failures (ConstraintViolationException) into a 400 with a field list.

The same idea, an extension point chosen by type, is shown below in a runnable form that uses the JDK's built-in HTTP server on the loopback address. A mapper registry converts exceptions to responses, and a request filter adds a header to every response. The client side uses the standard java.net.http.HttpClient:

Java Providers: mappers and filters 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.

Filters, interceptors and name binding

Beyond mappers, Jakarta REST has two more provider types you will use constantly:

  • Filters (ContainerRequestFilter, ContainerResponseFilter) inspect or change the request and response: authentication, CORS headers, request ids, logging. A request filter can stop processing with requestContext.abortWith(Response.status(401).build()).
  • Entity interceptors (ReaderInterceptor, WriterInterceptor) wrap the body conversion, for example to add compression or encryption.

By default a filter applies to every resource. A name binding limits it: define your own annotation marked @NameBinding, put it on the filter and on the resources or methods that need it.

Java
@NameBinding @Retention(RetentionPolicy.RUNTIME)
public @interface Secured { }

@Provider @Secured @Priority(Priorities.AUTHENTICATION)
public class TokenFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext ctx) {
        String header = ctx.getHeaderString(HttpHeaders.AUTHORIZATION);
        if (header == null || !header.startsWith("Bearer ")) {
            ctx.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
        }
    }
}

@DELETE @Path("/{id}") @Secured          // only this method runs the filter
public void delete(@PathParam("id") int id) { ... }

@Priority orders filters; lower numbers run first on the request path and last on the response path.

The client API

Jakarta REST also standardizes the client side, so a service can call another service with the same vocabulary of media types and entities:

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

try (Client client = ClientBuilder.newClient()) {
    WebTarget books = client.target("https://api.example.com").path("books");

    Book book = books.path("{id}").resolveTemplate("id", 42)
                     .request(MediaType.APPLICATION_JSON)
                     .get(Book.class);                              // maps 4xx/5xx to WebApplicationException

    Response created = books.request()
                            .post(Entity.json(new Book(0, "Emma")));
    System.out.println(created.getStatus() + " " + created.getLocation());
    created.close();                                                  // always close a raw Response
}

get(Book.class) throws a WebApplicationException subclass for error statuses, while reading a raw Response lets you inspect the status yourself. Reuse one Client for many calls, because creating it is expensive. Jakarta REST 3.1+ also has a reactive flavor (.rx().get(...) returning a CompletionStage). The JDK's own HttpClient does the same job without Jakarta dependencies, and MicroProfile Rest Client lets you declare a client as an annotated interface, much like Spring's OpenFeign.

JAX-RS versus Spring MVC

The two models solve the same problem with almost mirrored vocabulary:

Concept Jakarta REST Spring MVC
Controller class @Path class @RestController
Mapping @GET @Path("/{id}") @GetMapping("/{id}")
Path / query parameter @PathParam, @QueryParam @PathVariable, @RequestParam
Request body unannotated entity parameter @RequestBody
Response control Response ResponseEntity
Error translation ExceptionMapper @ExceptionHandler, @RestControllerAdvice
Interceptors filters and interceptors HandlerInterceptor, servlet filters
Dependency injection CDI (@Inject) Spring beans (@Autowired)

Choose Jakarta REST when you target a Jakarta EE server or Quarkus, or when portability across runtimes matters. Choose Spring when you want its ecosystem (Data, Security, Cloud). The next lesson, CDI and EJB, covers the @Inject that makes resource classes useful.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a JAX-RS method that returns void produce?

    A void resource method has nothing to send, so the runtime answers 204 No Content.
  2. 2. In a resource method, which parameter is treated as the request body?

    The single unannotated parameter is the entity parameter. A MessageBodyReader converts the request body into that type.
  3. 3. A client sends Accept text/csv but the method has @Produces(application/json). What status does the runtime return?

    406 means the server cannot produce any format the client accepts. 415 is for an unsupported request body type.
  4. 4. How do you apply a filter to only some resource methods?

    Name binding connects a filter or interceptor to the resources that carry the same binding annotation. Without it, the filter applies to every resource.
  5. 5. What is the role of an ExceptionMapper?

    The runtime picks the mapper closest to the exception type and uses the Response it returns, similar to Spring's exception handlers.

Summary

  • Jakarta REST (JAX-RS) is the standard REST API of Jakarta EE; resources are plain classes with @Path and HTTP method annotations.
  • Parameters are injected with @PathParam, @QueryParam, @HeaderParam, @FormParam, @BeanParam and @Context; the unannotated parameter is the request body.
  • Providers convert entities (MessageBodyReader/Writer), map exceptions (ExceptionMapper), and filter or intercept requests and responses.
  • @Produces and @Consumes drive content negotiation and yield 406 and 415 automatically; Response gives full control over status and headers.
  • The client API (ClientBuilder, WebTarget) calls other REST services with the same vocabulary.
  • The concepts map almost one-to-one onto Spring MVC annotations.

Next: CDI and Enterprise JavaBeans shows how resource classes get their dependencies and transactions.