Annotation Interface Rest


Used to denote that a class is a REST resource and to associate metadata on it.

Usually used on a subclass of RestServlet, but can be used to annotate any class that you want to expose as a REST resource.

Default response format (content negotiation):

The response format is not hardwired to JSON. The serializer used to render a response body is chosen by ordinary HTTP content negotiation — the request's Accept header is best-matched against the media types of the configured serializers (see Serializer.getMediaTypeRanges()). A request that sends no Accept header (or a non-specific one such as */*, which browsers send by default) is treated as */* and matches the first serializer in the set.

In the default configuration (BasicRestServlet / BasicRestResource, via BasicUniversalConfig) the serializer set lists HTML first, so a browser — or any client that omits Accept — receives HTML, not JSON. To always get JSON, send an explicit Accept: application/json header. See serializers() for how serializer ordering determines this default.

See Also:
  • Element Details

    • allowedHeaderParams

      Allowed header URL parameters.

      When specified, allows headers such as "Accept" and "Content-Type" to be passed in as URL query parameters.
      For example:

      ?Accept=text/json&Content-Type=text/json

      Notes:
      • Supports REST Server SVL Variables (e.g. "$L{my.localized.variable}").
      • Use "*" to represent all methods.
      • Use "NONE" (case insensitive) to suppress inheriting a value from a parent class.
      Returns:
      The annotation value.
      Default:
      ""
    • allowedMethodHeaders

      Allowed method headers.

      A comma-delimited list of HTTP method names that are allowed to be passed as values in an X-Method, X-HTTP-Method-Override, X-HTTP-Method or X-Method-Override HTTP header to override the real HTTP method name. All four headers share this list; when more than one is sent they are tried in that order.

      Allows you to override the actual HTTP method with a simulated method.
      For example, if an HTTP Client API doesn't support PATCH but does support POST (because PATCH is not part of the original HTTP spec), you can add a X-Method: PATCH header on a normal HTTP POST /foo request call which will make the HTTP call look like a PATCH request in any of the REST APIs.

      Notes:
      • Supports REST Server SVL Variables (e.g. "$L{my.localized.variable}").
      • Method names are case-insensitive.
      • Use "*" to represent all methods.
      • Use "NONE" (case insensitive) to suppress inheriting a value from a parent class.
      • Once the list admits at least one method, override claims must agree: a request whose override headers (or method query parameter) name more than one distinct method is refused with 400, whether or not the list admits them.
      • On a safe request (GET, HEAD, OPTIONS, TRACE), an override is honored only when it names another safe method or an operation declared read=true; anything else is refused with 405. Overrides on a POST are unaffected.
      Returns:
      The annotation value.
      Default:
      ""
    • allowedMethodParams

      Allowed method parameters.

      When specified, the HTTP method can be overridden by passing in a "method" URL parameter.
      For example:

      ?method=OPTIONS

      On a safe request (GET, HEAD, OPTIONS, TRACE), which is what a link or a typed URL sends, the parameter may only name another safe method or a custom method whose operation is declared read=true. Anything else, for example GET /foo?method=DELETE, is refused with 405 Method Not Allowed, so a link can never trigger a write. On a POST, the parameter may name any method in this list.

      Notes:
      • Supports REST Server SVL Variables (e.g. "$L{my.localized.variable}").
      • Use "*" to represent all methods.
      • Use "NONE" (case insensitive) to suppress inheriting a value from a parent class.
      Returns:
      The annotation value.
      Default:
      ""
    • authenticator

      Resource-level authenticator.

      Resolves the Principal and roles for requests to this resource and its descendant child resources (inherited unless cut off via noInherit={"authenticator"}), so that roleGuard / RoleBasedRestGuard / @Auth / isUserInRole resolve against the computed identity.

      Notes:
      • The implementation is instantiated through the resource's bean store (constructor injection).
      • The default RestAuthenticator.Null sentinel means "not specified."
      See Also:
      Returns:
      The annotation value.
      Since:
      10.0.0
      Default:
      org.apache.juneau.rest.server.auth.RestAuthenticator.Null.class
    • children

      REST children.

      Defines children of this resource. Each child resource is mounted under its own URL subtree (per the child's own @Rest(path=...) / @Rest(paths=...)) and constructs its own RestContext.

      Children vs. mixins (resolution semantics)

      Children are isolated from the parent's resolution chain by design — a child's serializers, parsers, guards, hooks, etc. are all resolved against the child's own RestContext only, NOT walked through the parent. This is the opposite of how mixins resolve. See the Mixin-vs-child divergence topic for the rationale (children own their lifecycle and are externally mounted; mixins are inline composers sharing the host's URL namespace and resolution chain).

      Inheritance Rules
      • Children on child are combined with those on parent class.
      • Children are list parent-to-child in the order they appear in the annotation.
      See Also:
      Returns:
      The annotation value.
      Default:
      {}
    • childrenDefs

      Rich child definitions — the host-side seed form of children().

      Each @Child entry names a child class (via Child.type()) and lets the host seed a curated set of @Rest-level settings onto that child's otherwise-isolated RestContext — guards, role guards, part serializer/parser, and a handful of default-scalar settings — without editing the child class.

      Unlike mixinDefs, this does not override an inherited chain (children never inherit from the host); it seeds settings onto an isolated context. Additive-security seed members (guards, converters, roleGuard, rolesDeclared) can't be removed or weakened by the child; the remaining scalar seed members are a fallback the child's own explicit @Rest declaration wins over. See Child for the full semantics.

      Example:

      @Rest( childrenDefs=@Child(type=FooChild.class, maxInput="10M") ) public class MyResource { ... }

      This attribute is additive to children(): bare-class entries in children() and rich entries here are discovered together (bare classes first, then childrenDefs). A @Child(type=X.class) with no seed members is the exact equivalent of a bare children=X.class entry.

      See Also:
      Returns:
      The annotation value.
      Since:
      10.0.0
      Default:
      {}
    • mixins

      REST mixins.

      Defines operation-provider classes whose @RestOp-group methods should be composed into this resource.

      Mixin methods are discovered the same way as local operation methods and surface under this resource's URL namespace. On path/method collisions, local methods on this resource win over mixin methods.

      Per-mixin RestContext + host-to-mixin inheritance (since 10.0.0)

      Each mixin class is elevated to its own RestContext parent-linked to this host's RestContext. The mixin's class-level @Rest(...) configuration applies to its own endpoints, with inheritance from the host:

      • List-shaped properties (serializers, parsers, encoders, converters, responseProcessors, restOpArgs, guards) — host's chain runs first, then the mixin's appended. Host endpoints see only the host's chain.
      • Replace-shaped properties (partSerializer, partParser) — the mixin's value wins over the host's for mixin endpoints when declared; otherwise the host's value is inherited.
      • messages — the mixin's bundle is chained as a child of the host's via Messages.chain(child, parent) so mixin keys win and missing keys fall through to the host.
      • Lifecycle hooks (@RestStartCall, @RestEndCall, @RestPreCall, @RestPostCall, @RestDestroy) — dual-fire host-then-mixin for mixin-endpoint requests; host-only for host-endpoint requests.

      Use @Rest(noInherit={...}) on a mixin class to cut off inheritance for a specific property — same token set as the host's noInherit machinery (e.g. "serializers", "guards", "messages").

      Mixins vs. children

      Mixins are inline composers that share the host's URL namespace and inherit from the host's resolution chain. Children are independently-mounted resources isolated from the host's resolution chain. See the Mixin-vs-child divergence topic for the rationale.

      Inheritance Rules
      • Mixins on child are combined with those on parent class.
      • Mixins are listed parent-to-child in the order they appear in the annotation.
      • Transitive mixins (A mixes in B) parent-link flat to the host — both A and B get parentContext = host, never an A → B chain.

      For host-side per-mixin setting overrides (applying guards / serializers / a mount path / etc. to a specific mixin's endpoints without editing the mixin class), see the rich mixinDefs companion attribute.

      See Also:
      Returns:
      The annotation value.
      Default:
      {}
    • mixinDefs

      Rich mixin definitions — the host-side override form of mixins().

      Each @Mixin entry names a mixin class (via Mixin.type()) and lets the host override selected @Rest-level settings for that mixin's mixed-in endpoints — guards, role guards, serializers, default headers, mount path, etc. — without subclassing or editing the mixin class.

      Example:

      @Rest( mixinDefs=@Mixin(type=FooMixin.class, guards=AdminGuard.class) ) public class MyResource { ... }

      This attribute is additive to mixins(): bare-class entries in mixins() and rich entries here are discovered together (bare classes first, then mixinDefs). A @Mixin(type=X.class) with no overrides is the exact equivalent of a bare mixins=X.class entry.

      See Also:
      Returns:
      The annotation value.
      Since:
      10.0.0
      Default:
      {}
    • mergeResponseProcessorsIntoHost

      Mixin-declared opt-in: fold this class's own responseProcessors into the host resource's chain whenever this class is composed as a mixin via a plain @Rest(mixins=...) reference.

      By default (false) a mixin's responseProcessors apply only to the mixin's own endpoints — a host's own @RestOp methods see only the host's chain (the standard mixin inheritance rule "host's chain runs first, then the mixin's appended; host endpoints see only the host's chain"). Setting this to true on the mixin class itself makes a plain @Rest(mixins=ThisClass.class) reference additionally append this class's own responseProcessors to the end of the host's own chain, so the host's own endpoints pick them up too.

      This is the mixin-declared, response-processor-scoped counterpart to @Mixin(mergeIntoHost=true) (which is host-declared and folds all list-shaped attributes). Unlike mergeIntoHost, this directive lives with the mixin and folds only responseProcessors — never guards, serializers, or any other list-shaped attribute. It is intended for view-renderer mixins (e.g. FreemarkerMixin) so that declaring the mixin is enough to route the host's own View returns through the renderer.

      Strictly opt-in and non-silent: it has no effect for a mixin that leaves it false, so existing mixins keep today's scoping exactly. Same-class de-duplication applies, so a response processor the host already declares is not added twice.

      Returns:
      The annotation value.
      Since:
      10.0.0
      Default:
      false
    • clientVersionHeader

      Client version header.

      Specifies the name of the header used to denote the client version on HTTP requests.

      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • config

      Optional location of configuration file for this servlet.

      The configuration file .

      Inheritance Rules
      • Config file is searched for in child-to-parent order.
      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • eagerInit

      Eagerly initializes framework-managed memoizers during RestContext construction.

      When enabled, framework bean memoizers and operation/child-context memoizers are force-fired inside the constructor try/catch so startup-time configuration errors fail fast.

      This setting is disabled by default.

      • "true" - Force eager initialization during context construction.
      • "false" - Keep initialization lazy until first use (default).
      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • lazyChildren

      Opt this parent resource into deferred (first-invocation) construction of its children() sub-resources.

      When "true", the RestContext instances for all @Rest(children=...) entries are not built at parent startup. Instead, each child's routing entry is registered immediately (so URL matching is fully operational from the first request), but the full RestContext — including all of its bean-store setup, memoizers, and lifecycle hooks — is constructed on the first inbound request to that child's URL prefix. Subsequent requests reuse the already-built context.

      This is particularly useful when a parent resource exposes heavyweight admin or diagnostic children that are rarely invoked in production. Setting lazyChildren="true" on the parent lets the parent boot fast; each child pays its construction cost only when (and if) it is first accessed.

      • "true" - Children are constructed on first invocation (deferred).
      • "false" (default) - Children are constructed eagerly at parent startup.
      Notes:
      • The first request to a lazy child pays the full construction cost, which can be significant for heavyweight children. If predictable first-request latency is required, do not opt in.
      • Concurrent first-requests to the same lazy child are serialized: only one thread runs the construction; others block until it completes.
      • A lazy child that is never invoked is never constructed. Its lifecycle @RestDestroy / shutdown hooks are skipped at parent destruction time.
      • The programmatic knob RestContext.Builder.lazyChildInit(boolean) overrides this annotation.
      • Supports REST Server SVL Variables (e.g. "$E{LAZY_CHILDREN,false}").
      See Also:
      • RestContext.Builder.lazyChildInit(boolean)
      • children()
      Returns:
      The annotation value.
      Default:
      ""
    • consumes

      Supported content media types.

      Overrides the media types inferred from the parsers that identify what media types can be consumed by the resource.

      Notes:
      Returns:
      The annotation value.
      Default:
      {}
    • allowedSerializerOptions

      Allowed serializer session option keys for this resource (ordered merge, prefix -key removes a key).

      Comma-delimited list of session property keys (e.g. "escapeSolidus,maxIndent") that clients may send via the "X-Juneau-Serializer-Options" header or "juneauSerializerOptions" query parameter. Keys not in the effective allowlist cause a 400 Bad Request response.

      Entries are merged in application order. A leading hyphen removes a previously added key: "-escapeSolidus". Method-level RestGet.allowedSerializerOptions() values are always merged on top. Use noInherit() to prevent inheriting less-derived contributions.

      See Also:
      Returns:
      The annotation value.
      Default:
      {}
    • allowedParserOptions

      Allowed parser session option keys for this resource (ordered merge, prefix -key removes a key).

      Comma-delimited list of session property keys that clients may send via the "X-Juneau-Parser-Options" header or "juneauParserOptions" query parameter. Parser options are ignored for operations without a request-body parser. Keys not in the effective allowlist cause a 400 Bad Request response.

      Use noInherit() to prevent inheriting less-derived contributions.

      See Also:
      Returns:
      The annotation value.
      Default:
      {}
    • noInherit

      Property names for which less-derived contributions are NOT inherited.

      Accepted values include "allowedParserOptions", "allowedSerializerOptions", "allowedHeaderParams", "allowedMethodHeaders", "allowedMethodParams", "disableContentParam", "renderResponseStackTraces", "problemDetails", "debugMarshalling", "eagerInit", "lazyChildren", "clientVersionHeader", "uriAuthority", "uriContext", "uriRelativity", and "uriResolution". Each entry is SVL-resolved then comma-split. Prevents the named property from inheriting values from parent @Rest annotations (router hierarchy). The noInherit attribute itself is never inherited.

      Mixin sub-contexts (since 10.0.0)

      On a class declared via @Rest(mixins=...) on a host, noInherit also blocks the host-to-mixin inheritance walk for the named property. The token set extends to every contribution list exposed by @Rest: "serializers", "parsers", "encoders", "converters", "responseProcessors", "restOpArgs", "guards", "partSerializer", "partParser", and "messages". For example, @Rest(noInherit={"guards"}) on a mixin removes the host's guard chain from the mixin's endpoints (typical pattern for deliberately-unguarded probes like HealthMixin).

      See Also:
      Returns:
      The annotation value.
      Default:
      {}
    • converters

      Class-level response converters.

      Associates one or more converters with a resource class.

      Inheritance Rules
      • Converters on child are combined with those on parent class.
      • Converters are executed child-to-parent in the order they appear in the annotation.
      • Converters on methods are executed before those on classes.
      Returns:
      The annotation value.
      Default:
      {}
    • defaultAccept

      Default Accept header.

      The default value for the Accept header if not specified on a request.

      This is a shortcut for using defaultRequestHeaders() for just this specific header.

      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • defaultCharset

      Default character encoding.

      The default character encoding for the request and response if not specified on the request.

      Notes:
      See Also:
      Returns:
      The annotation value.
      Default:
      ""
    • defaultContentType

      Default Content-Type header.

      The default value for the Content-Type header if not specified on a request.

      This is a shortcut for using defaultRequestHeaders() for just this specific header.

      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • defaultRequestAttributes

      Default request attributes.

      Specifies default values for request attributes if they're not already set on the request.

      Affects values returned by the following methods:

      Example:

      // Defined via annotation resolving to a config file setting with default value. @Rest(defaultRequestAttributes={"Foo=bar", "Baz: $C{REST/myAttributeValue}"}) public class MyResource { // Override at the method level. @RestGet(defaultRequestAttributes={"Foo: bar"}) public Object myMethod() {...} }

      Notes:
      See Also:
      Returns:
      The annotation value.
      Default:
      {}
    • defaultRequestHeaders

      Default request headers.

      Specifies default values for request headers if they're not passed in through the request.

      Notes:
      Returns:
      The annotation value.
      Default:
      {}
    • defaultResponseHeaders

      Default response headers.

      Specifies default values for response headers if they're not set after the Java REST method is called.

      Notes:
      Returns:
      The annotation value.
      Default:
      {}
    • description

      Optional servlet description.

      It is used to populate the Swagger description field.

      Inheritance Rules
      • Description is searched for in child-to-parent order.
      Notes:
      • Supports REST Server SVL Variables (e.g. "$L{my.localized.variable}").
      • The format is plain-text.
        Multiple lines are concatenated with newlines.
      Returns:
      The annotation value.
      Default:
      {}
    • disableContentParam

      Disable content URL parameter.

      When enabled (the default — this attribute is false unless explicitly set), the HTTP request content on PUT and POST requests can be passed in as text using the "content" URL parameter, letting a caller exercise an endpoint's body-consuming logic straight from a URL (handy for a quick manual test or a bookmarked link) without an actual PUT/POST body.
      For example:

      ?content=(name='John%20Smith',age=45)

      Because the override is on by default, treat it the same way as any other feature that lets untrusted URL content reach parsing/business logic: a link to a PUT/POST endpoint with a crafted "content" parameter is just as reproducible by a third party (e.g. embedded in a page that an authenticated user happens to load) as the equivalent real request body would be. The override is deliberately restricted to PUT/POST methods so that a simple cross-origin GET (the kind a browser issues with no preflight and no caller-controlled header for something as ordinary as an <img src=...> tag) can never trigger it this way, but resources that don't already validate that PUT/POST submissions are same-site in origin (e.g. with a token check, a custom-header check, or SameSite cookies) gain no additional protection here. Set this to true to disable the override entirely on any resource where it isn't a deliberate feature.

      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • problemDetails

      Opt the resource into RFC 7807 / RFC 9457 application/problem+json error responses.

      When enabled, the resource:

      • Emits application/problem+json for thrown BasicHttpExceptions — regardless of the client's Accept header. The body is a serialized Problem populated from the exception's status code, reason phrase, and message.
      • Honors the client's Accept header on the success path. When a @RestOp method returns a Problem (or throws a ProblemException), the ProblemDetailsProcessor only serializes it as application/problem+json when the Accept header matches that media type (or *&#47;*).
      • "true" — enable problem-details responses for this resource.
      • "false" — disable problem-details responses for this resource (overrides an inherited "true" from a parent @Rest).
      • "" (default) — inherit from the next-most-derived @Rest in the resource-class hierarchy. Default behavior (no opt-in anywhere in the chain) is unchanged from prior releases.
      Notes:
      See Also:
      Returns:
      The annotation value.
      Default:
      ""
    • debugMarshalling

      Opt the resource into REST-driven serializer/parser debug behavior.

      When enabled, the REST layer forces Context.debug on the serializer/parser sessions it creates to handle requests for this resource — engaging recursion-detection-that-throws (a genuine cycle throws MarshallingRecursionException instead of being size-guard-truncated), parse-input buffering (parse errors can quote the offending input), and stack-trace-prefixed marshalling exceptions.

      This is a behavior switch, independent of the JUL logger level: raising a logger to FINE/FINEST changes logging verbosity only and never changes marshalling behavior. A serializer/parser configured with Context.debug directly is unaffected by this setting.

      • "true" — enable marshalling debug for this resource.
      • "false" — disable marshalling debug for this resource (overrides an inherited "true" from a parent @Rest).
      • "" (default) — inherit from the next-most-derived @Rest in the resource-class hierarchy. Default behavior (no opt-in anywhere in the chain) is marshalling debug OFF.
      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • virtualThreads

      Opt this resource into per-request virtual-thread dispatch (Java 21+).

      When enabled, every @RestOp-annotated handler invocation on this resource is submitted to a Executors.newVirtualThreadPerTaskExecutor() virtual-thread-per-task executor lazily built by the RestContext. The platform request thread blocks on the virtual thread's completion (so the handler's return value, exceptions, and observability hooks are preserved verbatim), but blocking I/O inside the handler now parks a virtual thread instead of the carrier — i.e. the carrier thread is freed to service other concurrent requests while the handler is parked on socket / file / lock waits. Combined with CompletableFuture return types (@RestGet / @RestPost returning CompletableFuture<T>) this is the high-throughput pattern.

      Graceful degradation on Java 17/18/19/20: the flag is detected during RestContext initialization. If the runtime is older than Java 21, a one-shot WARNING is logged and the resource falls back to the standard caller-thread dispatch path — no runtime error.

      Per-@RestOp overrides are available via RestOp.virtualThreads(); the op-level setting takes precedence over the resource-level setting.

      • "true" — enable virtual-thread dispatch on Java 21+ (silently disabled on older JVMs).
      • "false" — explicitly disable.
      • "" (default) — inherit from the next-most-derived @Rest in the resource-class hierarchy.
      Notes:
      • Supports REST Server SVL Variables (e.g. "$E{ENABLE_VIRTUAL_THREADS,false}").
      • Synchronized blocks and JNI calls in handler code pin a virtual thread to its carrier thread — prefer ReentrantLock over synchronized in handlers run under this flag.
      See Also:
      Returns:
      The annotation value.
      Default:
      ""
    • observability

      Per-resource observability opt-in / opt-out control.

      Controls whether the observability block (MetricsRecorder / TracerHook) fires for operations on this resource. Per-operation overrides are available via RestOp.observability() (and the verb annotations).

      • "true" — strict opt-in: the resource requires a wired observability backend. If neither a @Bean MetricsRecorder nor a @Bean TracerHook is registered when the RestContext is built, construction fails with a precise error. All operations on this resource have observability enabled.
      • "false" — explicit opt-out: the observability block is short-circuited for every operation on this resource, even when a wired backend is present. Also suppresses TraceContextResponseProcessor header injection for this resource.
      • "" (default) — inherits the existing behavior: the observability block runs per-op, but a missing @Bean silently falls back to the NoOp singleton — no startup error.
      Notes:
      See Also:
      Returns:
      The annotation value.
      Since:
      10.0.0
      Default:
      ""
    • asyncTimeoutMillis

      Configurable timeout (milliseconds) applied to CompletableFuture-returning handlers by AsyncResponseProcessor. Default is 30,000 ms.

      On timeout, the future is cancelled with mayInterruptIfRunning=true and the response is committed as 504 Gateway Timeout. Set to "0" to disable the timeout entirely.

      Per-@RestOp overrides are available via RestOp.asyncTimeoutMillis(); the op-level setting takes precedence over the resource-level setting.

      Notes:
      See Also:
      Returns:
      The annotation value.
      Since:
      10.0.0
      Default:
      ""
    • asyncCompletionExecutor

      Names the Executor bean used to route CompletableFuture completion callbacks through a dedicated thread pool.

      When set, the AsyncResponseProcessor switches from future.whenComplete(callback) to future.whenCompleteAsync(callback, executor), so the response-handler work runs on the named pool instead of the future's natural completion thread (often an I/O-driver or database-callback thread).

      The value is the @Bean(name=...) lookup key for an Executor registered in the resource's bean store. Empty string (default) means no override — completion callbacks run on the future's natural thread (the existing behavior).

      Example:

      @Rest(path="/api", asyncCompletionExecutor="myCompletionPool") public class ApiResource extends RestServlet { @Bean(name="myCompletionPool") public Executor completionPool() { return Executors.newFixedThreadPool(8); } @RestGet("/orders/{id}") public CompletableFuture<Order> getOrder(@Path String id) { return orderService.fetchAsync(id); // callback runs on myCompletionPool } }

      Per-operation overrides are available via RestOp.asyncCompletionExecutor() (and the verb annotations). A reference to a bean name that does not resolve in the bean store causes a startup failure.

      Notes:
      • MDC propagation still works when this executor is set — the MdcAsyncListener wraps the callback before it is routed through the executor, so the MDC snapshot is restored on whichever thread the executor picks.
      See Also:
      Returns:
      The annotation value.
      Since:
      10.0.0
      Default:
      ""
    • encoders

      Class<? extends Encoder>[] encoders
      Specifies the compression encoders for this resource.

      Encoders are used to enable various kinds of compression (e.g. "gzip") on requests and responses.

      Encoders are automatically inherited from encoders() annotations on parent classes with the encoders on child classes prepended to the encoder group. The EncoderSet.NoInherit class can be used to prevent inheriting from the parent class.

      Example:

      // Define a REST resource that handles GZIP compression. @Rest( encoders={ GzipEncoder.class } ) public class MyResource { ... }

      The encoders can also be tailored at the method level using RestOp.encoders() (and related annotations).

      For programmatic equivalents, contribute an EncoderSet bean via @Bean(name="encoders").

      Inheritance Rules
      • Encoders on child are combined with those on parent class.
      See Also:
      Returns:
      The annotation value.
      Default:
      {}
    • formDataParams

      Default form data parameter definitions.

      Provides default values for @FormData annotations on method parameters across all methods in this class.

      Example:

      @Rest( formDataParams={ @FormData(name="action", def="submit") } ) public class MyResource {...}

      Returns:
      The annotation value.
      Since:
      9.2.0
      Default:
      {}
    • guards

      Class<? extends RestGuard>[] guards
      Class-level guards.

      Associates one or more RestGuards with all REST methods defined in this class.

      Inheritance Rules
      • Guards on child are combined with those on parent class.
      • Guards are executed child-to-parent in the order they appear in the annotation.
      • Guards on methods are executed before those on classes.
      Returns:
      The annotation value.
      Default:
      {}
    • headerParams

      Default header parameter definitions.

      Provides default values for @Header annotations on method parameters across all methods in this class.

      Example:

      @Rest( headerParams={ @Header(name="Accept-Language", def="en-US"), @Header(name="X-API-Version", def="1.0") } ) public class MyResource {...}

      Returns:
      The annotation value.
      Since:
      9.2.0
      Default:
      {}
    • maxInput

      The maximum allowed input size (in bytes) on HTTP requests.

      Useful for alleviating DoS attacks by throwing an exception when too much input is received instead of resulting in out-of-memory errors which could affect system stability.

      Applies uniformly across body-reading paths, including multipart/form-data uploads: a request whose declared Content-Length or parsed part sizes exceed this ceiling is rejected with a 413 response before (or as soon as) the oversized content would otherwise be buffered.

      Notes:
      See Also:
      Returns:
      The annotation value.
      Default:
      ""
    • messages

      Messages. Identifies the location of the resource bundle for this class.

      There are two possible formats:

      • A simple string - Represents the name of the resource bundle.

        Example:

        // Bundle name is Messages.properties. @Rest(messages="Messages")

      • Simplified JSON - Represents parameters for the Messages.Builder class.

        Example:

        // Bundles can be found in two packages. @Rest(messages="{name:'Messages',baseNames:['{package}.{name}','{package}.i18n.{name}']")

      If the bundle name is not specified, the class name of the resource object is used.

      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • parsers

      Specifies the parsers for converting HTTP request bodies into POJOs.

      Parsers are used to convert the content of HTTP requests into POJOs.
      Any of the Juneau framework parsers can be used in this setting.
      The parser selected is based on the request Content-Type header matched against the values returned by the following method using a best-match algorithm:

      Parsers are automatically inherited from parsers() annotations on parent classes with the parsers on child classes prepended to the parser group. The ParserSet.NoInherit class can be used to prevent inheriting from the parent class.

      Example:

      // Define a REST resource that can consume JSON and XML. @Rest( parsers={ JsonParser.class, XmlParser.class } ) public class MyResource { ... }

      The parsers can also be tailored at the method level using RestOp.parsers() (and related annotations).

      For programmatic equivalents, contribute a ParserSet bean via @Bean(name="parsers").

      Inheritance Rules
      • Parsers on child override those on parent class.
      • ParserSet.Inherit class can be used to inherit and augment values from parent.
      • ParserSet.NoInherit class can be used to suppress inheriting from parent.
      • Parsers on methods take precedence over those on classes.
      See Also:
      Returns:
      The annotation value.
      Default:
      {}
    • partParser

      HTTP part parser.

      Specifies the HttpPartParser to use for parsing headers, query/form parameters, and URI parts.

      Returns:
      The annotation value.
      Default:
      org.apache.juneau.marshall.httppart.HttpPartParser.Void.class
    • partSerializer

      HTTP part serializer.

      Specifies the HttpPartSerializer to use for serializing headers, query/form parameters, and URI parts.

      Returns:
      The annotation value.
      Default:
      org.apache.juneau.marshall.httppart.HttpPartSerializer.Void.class
    • path

      Resource path.

      Used in the following situations:

      • On child resources (resource classes attached to parents via the children() annotation) to identify the subpath used to access the child resource relative to the parent.
      • On top-level RestServlet classes deployed as Spring beans when JuneauRestInitializer is being used.
      On child resources

      The typical usage is to define a path to a child resource relative to the parent resource.

      Example:

      @Rest( children={ChildResource.class} ) public class TopLevelResource extends BasicRestServlet {...} @Rest( path="/child", children={GrandchildResource.class} ) public class ChildResource {...} @Rest( path="/grandchild" ) public class GrandchildResource { @RestGet("/") public String sayHello() { return "Hello!"; } }

      In the example above, assuming the TopLevelResource servlet is deployed to path /myContext/myServlet, then the sayHello method is accessible through the URI /myContext/myServlet/child/grandchild.

      Note that in this scenario, the path attribute is not defined on the top-level resource. Specifying the path on the top-level resource has no effect, but can be used for readability purposes.

      Path variables

      The path can contain variables that get resolved to @Path parameters or access through the RestRequest.getPathParams() method.

      Example:

      @Rest( path="/myResource/{foo}/{bar}" ) public class MyResource extends BasicRestServlet { @RestGet("/{baz}") public void String doX(@Path String foo, @Path int bar, @Path MyPojo baz) { ... } }

      Variables can be used on either top-level or child resources and can be defined on multiple levels.

      All variables in the path must be specified or else the target will not resolve and a 404 will result.

      When variables are used on a path of a top-level resource deployed as a Spring bean in a Spring Boot application, the first part of the URL must be a literal which will be used as the servlet path of the registered servlet.

      Notes:
      • The leading slash is optional. "/myResource" and "myResource" is equivalent.
      • The paths "/myResource" and "/myResource/*" are equivalent.
      • Paths must not end with "/" (per the servlet spec).
      • Effective only when this class is registered directly with the servlet container as a top-level resource. When this class is imported as a mixin via @Rest(mixins=...), the importing host's own path() or paths() governs the mount and this annotation is silently ignored — mixin endpoints land in the host's URL namespace.
      Inheritance Rules
      • Path is searched for in child-to-parent order.
      Returns:
      The annotation value.
      Default:
      ""
    • paths

      Additional servlet mount paths.

      Optional multi-mount companion to path() for top-level servlet deployment.

      When specified, servlet containers may mount this resource on each listed path. This is primarily intended for built-in support endpoints such as health probes where multiple exact URLs should be served by a single servlet instance.

      Runtime substitution (since 10.0.0)

      Each array element is treated as a template:

      1. The element runs through REST Server SVL Variables variable substitution (e.g. $C{health.paths}, $E{HEALTH_PATHS,/healthz}, $S{my.system.prop,/healthz}) using the bootstrap VarResolver on the bean store.
      2. The post-SVL value is split on ,; each piece is trimmed and empty pieces are dropped. A single template element can therefore expand to zero, one, or many mount paths.
      Examples:

      // 1. Single key resolving to a multi-value config string. @Rest(paths={"$C{health.paths}"}) // 2. Mix literal + resolved element. @Rest(paths={"/api", "$C{extra.paths}"}) // 3. Env var with comma-separated defaults baked in. @Rest(paths={"$E{HEALTH_PATHS,/healthz,/readyz}"})

      Notes:
      • Paths are normalized to servlet path-specs by the hosting runtime.
      • When both path() and paths() are present, runtimes may use paths() for top-level mounting and continue using path() for child-resource composition.
      • The annotation default sits at the lowest rung of the runtime-override resolution chain — see RestContext.getPaths() for the full precedence order (programmatic > getter > annotation).
      • An SVL failure (unresolved variable with no default) falls back to the literal element rather than throwing during construction.
      • Effective only when this class is registered directly with the servlet container as a top-level resource. When this class is imported as a mixin via @Rest(mixins=...), the importing host's own path() or paths() governs the mount and this annotation is silently ignored — mixin endpoints land in the host's URL namespace.
      Returns:
      The annotation value.
      Default:
      {}
    • pathParams

      Default path parameter definitions.

      Provides default values for @Path annotations on method parameters across all methods in this class.

      Example:

      @Rest( pathParams={ @Path(name="version", def="v1") } ) public class MyResource {...}

      Returns:
      The annotation value.
      Since:
      9.2.0
      Default:
      {}
    • produces

      Supported accept media types.

      Overrides the media types inferred from the serializers that identify what media types can be produced by the resource.

      Notes:
      Returns:
      The annotation value.
      Default:
      {}
    • queryParams

      Default query parameter definitions.

      Provides default values for @Query annotations on method parameters across all methods in this class. Values specified here are used as defaults when the same property is not explicitly defined on a method parameter's @Query annotation.

      Example:

      // Define common query parameters at class level @Rest( queryParams={ @Query(name="format", def="json", description="Output format"), @Query(name="verbose", def="false", schema=@Schema(type="boolean")) } ) public class MyResource { // Method will inherit the default query parameter definitions @RestGet public String doGet(@Query("format") String format, @Query("verbose") boolean verbose) {...} // Can override defaults on a per-method basis @RestGet public String doGet2(@Query(name="format", def="xml") String format) {...} }

      Notes:
      • These defaults apply to validation, parsing, and OpenAPI/Swagger documentation generation.
      • Method-level @Query annotations take precedence over class-level definitions.
      • The name attribute must be specified for each query definition.
      Returns:
      The annotation value.
      Since:
      9.2.0
      Default:
      {}
    • renderResponseStackTraces

      Render response stack traces in responses.

      Render stack traces in HTTP response bodies when errors occur.

      Off by default. Besides the stack trace itself, this same setting also determines whether the Thrown response header is set and whether an error whose exception type wasn't deliberately thrown by application code (i.e. not a BasicHttpException or one of its subclasses) has its class name/message echoed into the error body. Leave this off in production so that an unplanned exception type (a database driver error, a file-system exception, and the like) can't incidentally leak implementation detail to the caller; turn it on only for local debugging.

      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • responseProcessors

      Response processors.

      Specifies a list of ResponseProcessor classes that know how to convert POJOs returned by REST methods or set via RestResponse.setContent(Object) into appropriate HTTP responses.

      These processors run in order and are the extension point that turns a method's return value into the response body. The built-in SerializedPojoProcessor is the default POJO handler — it runs the content-negotiated serializer, so for ordinary POJO returns the effective response format is governed by serializer ordering and the request Accept header (see serializers()), not by this list.

      A custom view-renderer ResponseProcessor installed here (for example a template-rendering processor contributed by a view mixin — see mergeResponseProcessorsIntoHost()) can instead claim a return value and render it directly (e.g. as HTML from a template) before serializer negotiation is reached, changing the effective response for the returns it handles.

      Returns:
      The annotation value.
      Default:
      {}
    • restOpArgs

      Class<? extends RestOpArg>[] restOpArgs
      Java REST operation method parameter resolvers.

      By default, the Juneau framework will automatically Java method parameters of various types (e.g. RestRequest, Accept, Reader).
      This setting allows you to provide your own resolvers for your own class types that you want resolved.

      Returns:
      The annotation value.
      Default:
      {}
    • roleGuard

      Role guard.

      An expression defining if a user with the specified roles are allowed to access methods on this class.

      This is a shortcut for specifying RestOp.roleGuard() on all the REST operations on a class.

      Example:

      @Rest( path="/foo", roleGuard="ROLE_ADMIN || (ROLE_READ_WRITE && ROLE_SPECIAL)" ) public class MyResource extends BasicRestServlet { ... }

      Notes:
      • Supports any of the following expression constructs:
        • "foo" - Single arguments.
        • "foo,bar,baz" - Multiple OR'ed arguments.
        • "foo | bar | baz" - Multiple OR'ed arguments, pipe syntax.
        • "foo || bar || baz" - Multiple OR'ed arguments, Java-OR syntax.
        • "fo*" - Patterns including '*' and '?'.
        • "fo* & *oo" - Multiple AND'ed arguments, ampersand syntax.
        • "fo* && *oo" - Multiple AND'ed arguments, Java-AND syntax.
        • "fo* || (*oo || bar)" - Parenthesis.
      • AND operations take precedence over OR operations (as expected).
      • Whitespace is ignored.
      • null or empty expressions always match as false.
      • If patterns are used, you must specify the list of declared roles using rolesDeclared().
      • Supports REST Server SVL Variables (e.g. "$L{my.localized.variable}").
      Returns:
      The annotation value.
      Default:
      ""
    • rolesDeclared

      Declared roles.

      A comma-delimited list of all possible user roles.

      Used in conjunction with roleGuard() is used with patterns.

      This is a shortcut for specifying RestOp.rolesDeclared() on all the REST operations on a class.

      Example:

      @Rest( rolesDeclared="ROLE_ADMIN,ROLE_READ_WRITE,ROLE_READ_ONLY,ROLE_SPECIAL", roleGuard="ROLE_ADMIN || (ROLE_READ_WRITE && ROLE_SPECIAL)" ) public class MyResource extends BasicRestServlet { ... }

      Returns:
      The annotation value.
      Default:
      ""
    • serializers

      Specifies the serializers for POJOs into HTTP response bodies.

      Serializer are used to convert POJOs to HTTP response bodies.
      Any of the Juneau framework serializers can be used in this setting.
      The serializer selected is based on the request Accept header matched against the values returned by the following method using a best-match algorithm:

      Ordering determines the default response format. A request that sends no Accept header (or a non-specific one such as */*, which browsers send by default) is treated as */* and matches the first serializer in this list. That is why the default configuration (BasicUniversalConfig) lists HTML first — so a browser, or any client that omits Accept, receives HTML rather than JSON. Order this list deliberately, and send an explicit Accept: application/json to force JSON regardless of ordering.

      Serializers are automatically inherited from serializers() annotations on parent classes with the serializers on child classes prepended to the serializer group. The SerializerSet.NoInherit class can be used to prevent inheriting from the parent class.

      Example:

      // Define a REST resource that can produce JSON and XML. @Rest( serializers={ JsonParser.class, XmlParser.class } ) public class MyResource { ... }

      The serializers can also be tailored at the method level using RestOp.serializers() (and related annotations).

      For programmatic equivalents, contribute a SerializerSet bean via @Bean(name="serializers").

      Inheritance Rules
      • Serializers on child override those on parent class.
      • SerializerSet.Inherit class can be used to inherit and augment values from parent.
      • SerializerSet.NoInherit class can be used to suppress inheriting from parent.
      • Serializers on methods take precedence over those on classes.
      See Also:
      Returns:
      The annotation value.
      Default:
      {}
    • siteName

      Optional site name.

      The site name is intended to be a title that can be applied to the entire site.

      One possible use is if you want to add the same title to the top of all pages by defining a header on a common parent class like so:

      @HtmlDocConfig( header={ "<h1>$RS{siteName}</h1>", "<h2>$RS{title}</h2>" } )

      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • staticFiles

      Static files.

      Used to retrieve localized files to be served up as static files through the REST API via the following predefined methods:

      • BasicRestResource.getHtdoc(String, Locale).
      • BasicRestServlet.getHtdoc(String, Locale).

      The static file finder can be accessed through the following methods:

      Inheritance Rules
      • Static files on child are combined with those on parent class.
      • Static files are are executed child-to-parent in the order they appear in the annotation.
      Returns:
      The annotation value.
      Default:
      org.apache.juneau.rest.server.staticfile.StaticFiles.Void.class
    • swagger

      Provides swagger-specific metadata on this resource.

      Used to populate the auto-generated OPTIONS swagger documentation.

      Example:

      @Rest( path="/addressBook", // Swagger info. swagger=@Swagger({ "contact:{name:'John Smith',email:'john@smith.com'},", "license:{name:'Apache 2.0',url:'http://www.apache.org/licenses/LICENSE-2.0.html'},", "version:'2.0',, "termsOfService:'You are on your own.',", "tags:[{name:'Java',description:'Java utility',externalDocs:{description:'Home page',url:'http://juneau.apache.org'}}],", "externalDocs:{description:'Home page',url:'http://juneau.apache.org'}" }) )

      See Also:
      Returns:
      The annotation value.
      Default:
      @org.apache.juneau.rest.server.Swagger
    • swaggerProvider

      Swagger provider.
      Returns:
      The annotation value.
      Default:
      org.apache.juneau.rest.server.swagger.SwaggerProvider.Void.class
    • openApiProvider

      OpenAPI 3.1 provider.

      Sibling of swaggerProvider() for the OpenAPI 3.1 emission path. Defaults to OpenApiProvider.Void which resolves to BasicOpenApiProvider unless the bean store provides an override.

      Returns:
      The annotation value.
      Default:
      org.apache.juneau.rest.server.openapi.OpenApiProvider.Void.class
    • title

      Optional servlet title.

      It is used to populate the Swagger title field.

      Inheritance Rules
      • Label is searched for in child-to-parent order.
      Notes:
      Returns:
      The annotation value.
      Default:
      {}
    • uriAuthority

      Resource authority path.

      Overrides the authority path value for this resource and any child resources.

      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • uriContext

      Resource context path.

      Overrides the context path value for this resource and any child resources.

      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • uriRelativity

      URI-resolution relativity.

      Specifies how relative URIs should be interpreted by serializers.

      See UriRelativity for possible values.

      Notes:
      Returns:
      The annotation value.
      Default:
      ""
    • uriResolution

      URI-resolution.

      Specifies how relative URIs should be interpreted by serializers.

      See UriResolution for possible values.

      Notes:
      Returns:
      The annotation value.
      Default:
      ""