CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-quarkus--quarkus-bom

Cloud Native, Container First Java framework for building efficient Java applications with fast startup times and low memory usage

Pending
Overview
Eval results
Files

rest-web-services.mddocs/

RESTful Web Services

Quarkus provides RESTEasy Reactive, a high-performance JAX-RS implementation optimized for reactive and imperative programming models with full OpenAPI integration and native compilation support.

JAX-RS Core Annotations

Resource Path Annotations

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Path {
    String value();
}

Defines the URI path template for a resource class or method.

Usage Example:

@Path("/users")
public class UserResource {
    
    @GET
    @Path("/{id}")
    public User getUser(@PathParam("id") Long id) {
        return userService.findById(id);
    }
}

HTTP Method Annotations

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("GET")
public @interface GET {
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("POST")
public @interface POST {
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PUT")
public @interface PUT {
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("DELETE")
public @interface DELETE {
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("HEAD")
public @interface HEAD {
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("OPTIONS")
public @interface OPTIONS {
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PATCH")
public @interface PATCH {
}

Standard HTTP method annotations for REST endpoints.

Content Type Annotations

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Consumes {
    String[] value() default {};
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Produces {
    String[] value() default {};
}

Specify media types for request/response content.

Usage Example:

@Path("/api/orders")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class OrderResource {
    
    @POST
    public Response createOrder(Order order) {
        Order created = orderService.create(order);
        return Response.status(Response.Status.CREATED).entity(created).build();
    }
}

Parameter Injection Annotations

Path and Query Parameters

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PathParam {
    String value();
}

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface QueryParam {
    String value();
}

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MatrixParam {
    String value();
}

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface FormParam {
    String value();
}

Parameter extraction annotations for different HTTP parameter types.

Usage Example:

@Path("/search")
public class SearchResource {
    
    @GET
    public List<Product> search(@QueryParam("q") String query,
                               @QueryParam("limit") @DefaultValue("10") int limit,
                               @QueryParam("offset") @DefaultValue("0") int offset) {
        return searchService.search(query, limit, offset);
    }
}

Header and Cookie Parameters

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface HeaderParam {
    String value();
}

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CookieParam {
    String value();
}

Extract values from HTTP headers and cookies.

Context Injection

@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Context {
}

Inject JAX-RS context objects like UriInfo, HttpHeaders, SecurityContext, etc.

Usage Example:

@GET
@Path("/info")
public Response getRequestInfo(@Context UriInfo uriInfo,
                              @Context HttpHeaders headers,
                              @Context SecurityContext securityContext) {
    Map<String, Object> info = Map.of(
        "uri", uriInfo.getRequestUri().toString(),
        "userAgent", headers.getHeaderString("User-Agent"),
        "authenticated", securityContext.getUserPrincipal() != null
    );
    return Response.ok(info).build();
}

Response Building

Response Class

public abstract class Response {
    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 Object getEntity();
    public abstract MultivaluedMap<String, Object> getMetadata();
}

Core response building functionality.

public abstract static class ResponseBuilder {
    public abstract Response build();
    public abstract ResponseBuilder entity(Object entity);
    public abstract ResponseBuilder type(MediaType type);
    public abstract ResponseBuilder type(String type);
    public abstract ResponseBuilder header(String name, Object value);
    public abstract ResponseBuilder cookie(NewCookie... cookies);
    public abstract ResponseBuilder status(Status status);
    public abstract ResponseBuilder status(int status);
}

Builder for constructing HTTP responses.

Usage Example:

@POST
@Path("/users")
public Response createUser(User user) {
    try {
        User created = userService.create(user);
        return Response.created(
            URI.create("/users/" + created.getId())
        ).entity(created).build();
    } catch (ValidationException e) {
        return Response.status(Response.Status.BAD_REQUEST)
            .entity(Map.of("error", e.getMessage()))
            .build();
    }
}

Status Enum

public enum Status {
    OK(200, "OK"),
    CREATED(201, "Created"),
    ACCEPTED(202, "Accepted"),
    NO_CONTENT(204, "No Content"),
    MOVED_PERMANENTLY(301, "Moved Permanently"),
    FOUND(302, "Found"),
    NOT_MODIFIED(304, "Not Modified"),
    BAD_REQUEST(400, "Bad Request"),
    UNAUTHORIZED(401, "Unauthorized"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found"),
    METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
    CONFLICT(409, "Conflict"),
    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    SERVICE_UNAVAILABLE(503, "Service Unavailable");
    
    public int getStatusCode();
    public String getReasonPhrase();
}

Standard HTTP status codes.

Exception Handling

Exception Mappers

public interface ExceptionMapper<T extends Throwable> {
    Response toResponse(T exception);
}

Interface for mapping exceptions to HTTP responses.

Usage Example:

@Provider
public class ValidationExceptionMapper implements ExceptionMapper<ValidationException> {
    
    @Override
    public Response toResponse(ValidationException exception) {
        return Response.status(Response.Status.BAD_REQUEST)
            .entity(Map.of("error", exception.getMessage()))
            .build();
    }
}

WebApplicationException

public class WebApplicationException extends RuntimeException {
    public WebApplicationException();
    public WebApplicationException(String message);
    public WebApplicationException(Response response);
    public WebApplicationException(int status);
    public WebApplicationException(Status status);
    
    public Response getResponse();
}

Runtime exception that automatically maps to HTTP responses.

Filters and Interceptors

Request and Response Filters

public interface ContainerRequestFilter {
    void filter(ContainerRequestContext requestContext) throws IOException;
}

public interface ContainerResponseFilter {
    void filter(ContainerRequestContext requestContext, 
               ContainerResponseContext responseContext) throws IOException;
}

Interfaces for filtering HTTP requests and responses.

Usage Example:

@Provider
@PreMatching
public class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {
    
    @Override
    public void filter(ContainerRequestContext requestContext) {
        System.out.println("Request: " + requestContext.getMethod() + " " + 
                          requestContext.getUriInfo().getPath());
    }
    
    @Override
    public void filter(ContainerRequestContext requestContext,
                      ContainerResponseContext responseContext) {
        System.out.println("Response: " + responseContext.getStatus());
    }
}

Filter Annotations

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PreMatching {
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Provider {
}

Annotations for configuring filters and providers.

Reactive Support

Reactive Return Types

// Mutiny Uni for single async values
@GET
@Path("/async-user/{id}")
public Uni<User> getUserAsync(@PathParam("id") Long id) {
    return userService.findByIdAsync(id);
}

// Mutiny Multi for streaming responses
@GET
@Path("/stream/users")
@Produces(MediaType.SERVER_SENT_EVENTS)
public Multi<User> streamUsers() {
    return userService.streamAll();
}

// CompletionStage for async responses
@GET
@Path("/future-user/{id}")
public CompletionStage<User> getUserFuture(@PathParam("id") Long id) {
    return userService.findByIdFuture(id);
}

RESTEasy Reactive supports reactive return types for non-blocking operations.

OpenAPI Integration

OpenAPI Annotations

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Operation {
    String summary() default "";
    String description() default "";
    String operationId() default "";
    String[] tags() default {};
}

@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Parameter {
    String name() default "";
    String description() default "";
    boolean required() default false;
    ParameterIn in() default ParameterIn.DEFAULT;
}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface APIResponse {
    String responseCode() default "default";
    String description() default "";
    Class<?> content() default Void.class;
}

OpenAPI documentation annotations for API specification generation.

Usage Example:

@Path("/users")
@Tag(name = "Users", description = "User management operations")
public class UserResource {
    
    @GET
    @Path("/{id}")
    @Operation(summary = "Get user by ID", description = "Retrieves a user by their unique identifier")
    @APIResponse(responseCode = "200", description = "User found", content = User.class)
    @APIResponse(responseCode = "404", description = "User not found")
    public Response getUser(@Parameter(description = "User ID") @PathParam("id") Long id) {
        User user = userService.findById(id);
        if (user != null) {
            return Response.ok(user).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }
}

WebSocket Support

WebSocket Annotations

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface WebSocket {
    String path() default "";
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface WebSocketClient {
    String path() default "";
}

Annotations for defining WebSocket endpoints and clients.

WebSocket Message Handling

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OnTextMessage {
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OnBinaryMessage {
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OnOpen {
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OnClose {
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OnError {
}

Annotations for WebSocket lifecycle and message handling methods.

Usage Example:

@WebSocket(path = "/chat")
public class ChatSocket {
    
    @OnOpen
    public void onOpen(WebSocketConnection connection) {
        System.out.println("Client connected: " + connection.id());
    }
    
    @OnTextMessage
    public void onMessage(String message, WebSocketConnection connection) {
        // Broadcast message to all connections
        connection.broadcast().sendTextAndAwait(message);
    }
    
    @OnClose
    public void onClose(WebSocketConnection connection) {
        System.out.println("Client disconnected: " + connection.id());
    }
}

Client Support

REST Client Interface

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface RegisterRestClient {
    String configKey() default "";
    String baseUri() default "";
}

Annotation for registering REST client interfaces.

Usage Example:

@RegisterRestClient(configKey = "user-service")
@Path("/users")
public interface UserServiceClient {
    
    @GET
    @Path("/{id}")
    User getUser(@PathParam("id") Long id);
    
    @POST
    User createUser(User user);
}

// Usage in a service
@ApplicationScoped
public class ExternalUserService {
    
    @RestClient
    UserServiceClient userClient;
    
    public User getExternalUser(Long id) {
        return userClient.getUser(id);
    }
}

Install with Tessl CLI

npx tessl i tessl/maven-io-quarkus--quarkus-bom

docs

cdi-dependency-injection.md

configuration.md

core-runtime.md

data-persistence.md

index.md

reactive-programming.md

rest-web-services.md

scheduling.md

security.md

testing.md

tile.json