Java API for RESTful Web Services
npx @tessl/cli install tessl/maven-javax-ws-rs--javax-ws-rs-api@2.1.0JAX-RS (Java API for RESTful Web Services) is the Java EE standard specification for building RESTful web services. It provides annotations, interfaces, and utilities for creating both server-side REST endpoints and client-side REST consumers with support for content negotiation, parameter injection, asynchronous processing, and modern features like Server-Sent Events.
<dependency><groupId>javax.ws.rs</groupId><artifactId>javax.ws.rs-api</artifactId><version>2.1.1</version></dependency>// Core annotations for REST endpoints
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.PATCH;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.BeanParam;
// Client API
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.client.Entity;
// Core types
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MultivaluedMap;
// Extensions and providers
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.ExceptionMapper;
// Container and filters
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseFilter;
// Server-sent events
import javax.ws.rs.sse.Sse;
import javax.ws.rs.sse.SseEventSink;// Simple REST resource
@Path("/users")
public class UserResource {
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUser(@PathParam("id") String userId) {
User user = findUser(userId);
return Response.ok(user).build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createUser(User user) {
User created = saveUser(user);
return Response.status(Response.Status.CREATED).entity(created).build();
}
}
// Client usage
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://api.example.com/users/123");
Response response = target.request(MediaType.APPLICATION_JSON).get();
User user = response.readEntity(User.class);JAX-RS follows a resource-oriented architecture with these key concepts:
@Path that handle HTTP requests@GET, @POST, etc.)@Produces and @ConsumesCore annotations for defining REST endpoints, HTTP method mapping, and parameter injection.
@Target({ElementType.TYPE, ElementType.METHOD})
@Path(String value);
// HTTP method annotations
@Target(ElementType.METHOD)
@GET;
@POST;
@PUT;
@DELETE;
@HEAD;
@OPTIONS;
@PATCH;
// Parameter injection annotations
@Target(ElementType.PARAMETER)
@PathParam(String value);
@QueryParam(String value);
@HeaderParam(String value);
@CookieParam(String value);
@FormParam(String value);
@MatrixParam(String value);
@BeanParam;
@DefaultValue(String value);
// Content negotiation
@Target({ElementType.TYPE, ElementType.METHOD})
@Consumes(String[] value);
@Produces(String[] value);
// Context injection
@Target(ElementType.PARAMETER)
@Context;Fluent API for consuming RESTful web services with support for synchronous, asynchronous, and reactive invocations.
interface Client extends Configurable<Client>, AutoCloseable {
WebTarget target(String uri);
WebTarget target(URI uri);
WebTarget target(UriBuilder uriBuilder);
WebTarget target(Link link);
}
interface WebTarget extends Configurable<WebTarget> {
URI getUri();
UriBuilder getUriBuilder();
WebTarget path(String path);
WebTarget queryParam(String name, Object... values);
Invocation.Builder request();
Invocation.Builder request(String... acceptedResponseTypes);
Invocation.Builder request(MediaType... acceptedResponseTypes);
}Server-side processing including filters, interceptors, asynchronous processing, and resource management.
interface ContainerRequestFilter {
void filter(ContainerRequestContext requestContext) throws IOException;
}
interface ContainerResponseFilter {
void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException;
}
interface AsyncResponse {
boolean resume(Object response);
boolean resume(Throwable response);
boolean cancel();
boolean cancel(int retryAfter);
boolean cancel(Date retryAfter);
boolean isSuspended();
boolean isCancelled();
boolean isDone();
boolean setTimeout(long time, TimeUnit unit);
}Essential JAX-RS types for HTTP handling, URI manipulation, media types, and response building.
abstract class Response implements AutoCloseable {
public static ResponseBuilder status(Status status);
public static ResponseBuilder status(int status);
public static ResponseBuilder ok();
public static ResponseBuilder ok(Object entity);
public static ResponseBuilder created(URI location);
public static ResponseBuilder noContent();
public static ResponseBuilder notModified();
public abstract int getStatus();
public abstract StatusType getStatusInfo();
public abstract Object getEntity();
public abstract <T> T readEntity(Class<T> entityType);
}
abstract class UriBuilder {
public static UriBuilder newInstance();
public static UriBuilder fromUri(String uri);
public static UriBuilder fromUri(URI uri);
public abstract UriBuilder path(String path);
public abstract UriBuilder queryParam(String name, Object... values);
public abstract URI build(Object... values);
}Extension APIs including providers, message body readers/writers, exception mappers, and parameter converters.
@Provider
interface MessageBodyReader<T> {
boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType);
T readFrom(Class<T> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException;
}
@Provider
interface MessageBodyWriter<T> {
boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType);
void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException;
}
@Provider
interface ExceptionMapper<E extends Throwable> {
Response toResponse(E exception);
}Modern Server-Sent Events (SSE) API for real-time server-to-client communication.
interface Sse {
OutboundSseEvent.Builder newEventBuilder();
SseBroadcaster newBroadcaster();
}
interface SseEventSink extends AutoCloseable {
CompletionStage<?> send(OutboundSseEvent event);
boolean isClosed();
}
interface OutboundSseEvent extends SseEvent {
String getName();
String getId();
String getComment();
String getData();
long getReconnectDelay();
boolean isReconnectDelaySet();
MediaType getMediaType();
}
interface SseBroadcaster extends AutoCloseable {
CompletionStage<?> broadcast(OutboundSseEvent event);
void register(SseEventSink sseEventSink);
}