Jakarta EE compatible OpenAPI 3.x annotations for defining REST API specifications
—
Essential annotations for documenting REST operations, parameters, and API structure. These annotations form the foundation of OpenAPI documentation and are used to define operations, parameters, and overall API configuration.
Defines a resource method as an OpenAPI Operation with comprehensive metadata and configuration options.
/**
* Defines a resource method as an OpenAPI Operation
* Applied to: METHOD, ANNOTATION_TYPE
*/
@Operation(
method = "GET", // HTTP method
tags = {"users", "management"}, // Logical grouping tags
summary = "Get user by ID", // Brief description (≤120 chars)
description = "Retrieves user account details", // Verbose description
operationId = "getUserById", // Unique operation identifier
deprecated = false, // Deprecation status
hidden = false, // Hide from documentation
ignoreJsonView = false, // Ignore JsonView annotations
parameters = {@Parameter(...)}, // Operation parameters
responses = {@ApiResponse(...)}, // Possible responses
requestBody = @RequestBody(...), // Associated request body
security = {@SecurityRequirement(...)}, // Security requirements
servers = {@Server(...)}, // Alternative servers
externalDocs = @ExternalDocumentation(...), // External documentation
extensions = {@Extension(...)} // Custom extensions
)Usage Example:
@GET
@Path("/{id}")
@Operation(
summary = "Get user by ID",
description = "Retrieves a user account by their unique identifier",
operationId = "getUserById",
tags = {"users"}
)
@ApiResponse(responseCode = "200", description = "User found")
@ApiResponse(responseCode = "404", description = "User not found")
public Response getUserById(@PathParam("id") Long id) {
// Implementation
}Defines method parameters as operation parameters with location, validation, and schema information.
/**
* Defines operation parameters with comprehensive configuration
* Applied to: METHOD, FIELD, PARAMETER, ANNOTATION_TYPE
* Repeatable: Yes
*/
@Parameter(
name = "userId", // Parameter name (required for non-path params)
in = ParameterIn.PATH, // Parameter location
description = "Unique user identifier", // Parameter description
required = true, // Whether parameter is mandatory
deprecated = false, // Deprecation status
allowEmptyValue = false, // Allow empty values
hidden = false, // Hide from documentation
style = ParameterStyle.SIMPLE, // Serialization style
explode = Explode.DEFAULT, // Explode array/object parameters
allowReserved = false, // Allow reserved characters
schema = @Schema(type = "integer", format = "int64"), // Parameter schema
array = @ArraySchema(...), // Array schema alternative
content = {@Content(...)}, // Complex parameter content
example = "12345", // Example value
examples = {@ExampleObject(...)}, // Multiple examples
extensions = {@Extension(...)}, // Custom extensions
ref = "#/components/parameters/UserIdParam", // Reference to component
validationGroups = {} // Validation groups
)Parameter Location Types:
enum ParameterIn {
DEFAULT(""),
HEADER("header"),
QUERY("query"),
PATH("path"),
COOKIE("cookie")
}Parameter Styles:
enum ParameterStyle {
DEFAULT(""),
MATRIX("matrix"), // ;color=blue,black,brown
LABEL("label"), // .blue.black.brown
FORM("form"), // color=blue,black,brown
SPACEDELIMITED("spaceDelimited"), // blue%20black%20brown
PIPEDELIMITED("pipeDelimited"), // blue|black|brown
DEEPOBJECT("deepObject"), // color[R]=100&color[G]=200
SIMPLE("simple") // blue,black,brown
}Usage Examples:
// Path parameter
@GET
@Path("/{userId}")
public Response getUser(
@Parameter(description = "User ID", required = true)
@PathParam("userId") Long userId
) {}
// Query parameters with validation
@GET
public Response getUsers(
@Parameter(
name = "page",
description = "Page number for pagination",
schema = @Schema(type = "integer", minimum = "1", defaultValue = "1")
)
@QueryParam("page") Integer page,
@Parameter(
name = "size",
description = "Number of items per page",
schema = @Schema(type = "integer", minimum = "1", maximum = "100", defaultValue = "20")
)
@QueryParam("size") Integer size
) {}
// Header parameter
@GET
public Response getData(
@Parameter(
name = "X-Client-Version",
in = ParameterIn.HEADER,
description = "Client version",
schema = @Schema(type = "string", pattern = "^\\d+\\.\\d+\\.\\d+$")
)
@HeaderParam("X-Client-Version") String clientVersion
) {}Container annotation for multiple Parameter annotations on the same element.
/**
* Container for repeatable Parameter annotations
*/
@Parameters({
@Parameter(name = "userId", in = ParameterIn.PATH, required = true),
@Parameter(name = "includeDetails", in = ParameterIn.QUERY, required = false)
})Extends parameter definition with validation group support for conditional validation scenarios.
/**
* Parameter with validation group support
* Applied to: PARAMETER, FIELD, METHOD
*/
@ValidatedParameter(
name = "email", // Parameter name
in = ParameterIn.QUERY, // Parameter location
description = "Email address for validation", // Parameter description
required = true, // Required flag
schema = @Schema(type = "string", format = "email"), // Parameter schema
validationGroups = {Create.class, Update.class} // Validation groups
)Usage Examples:
// Parameter with create-only validation
@POST
@Path("/users")
public Response createUser(
@ValidatedParameter(
name = "email",
description = "User email address",
required = true,
schema = @Schema(type = "string", format = "email"),
validationGroups = {CreateUser.class}
)
@QueryParam("email") String email
) {}
// Parameter with different validation for different operations
@PUT
@Path("/users/{id}")
public Response updateUser(
@PathParam("id") Long id,
@ValidatedParameter(
name = "email",
description = "Updated email address",
required = false, // Optional for updates
schema = @Schema(type = "string", format = "email"),
validationGroups = {UpdateUser.class}
)
@QueryParam("email") String email
) {}
// Multiple validation groups
@Parameter(
name = "password",
description = "User password",
required = true,
schema = @Schema(type = "string", minLength = 8),
validationGroups = {CreateUser.class, ChangePassword.class}
)Populates the root OpenAPI Object with API metadata, security, servers, and global configuration.
/**
* Defines global OpenAPI configuration
* Applied to: TYPE
*/
@OpenAPIDefinition(
info = @Info( // API metadata (required)
title = "User Management API",
version = "2.1.0",
description = "Complete user management system"
),
tags = { // Global tags with metadata
@Tag(name = "users", description = "User operations"),
@Tag(name = "admin", description = "Administrative operations")
},
servers = { // Server configurations
@Server(url = "https://api.example.com", description = "Production"),
@Server(url = "https://staging-api.example.com", description = "Staging")
},
security = { // Global security requirements
@SecurityRequirement(name = "bearerAuth", scopes = {"read", "write"})
},
externalDocs = @ExternalDocumentation( // Additional documentation
description = "API Documentation",
url = "https://docs.example.com"
),
extensions = {@Extension(...)} // Custom extensions
)Usage Example:
@OpenAPIDefinition(
info = @Info(
title = "E-commerce API",
version = "3.0.0",
description = "RESTful API for e-commerce operations",
contact = @Contact(
name = "API Support",
email = "support@example.com",
url = "https://example.com/support"
),
license = @License(
name = "Apache 2.0",
url = "https://www.apache.org/licenses/LICENSE-2.0.html"
)
),
servers = {
@Server(
url = "https://api.{environment}.example.com",
description = "Main API server",
variables = @ServerVariable(
name = "environment",
defaultValue = "prod",
allowableValues = {"dev", "staging", "prod"},
description = "Deployment environment"
)
)
},
security = {
@SecurityRequirement(name = "oauth2", scopes = {"read", "write"}),
@SecurityRequirement(name = "apiKey")
}
)
@ApplicationPath("/api/v3")
public class ECommerceApplication extends Application {}Marks elements as hidden from OpenAPI documentation generation.
/**
* Marks elements as hidden from OpenAPI documentation
* Applied to: METHOD, TYPE, FIELD, ANNOTATION_TYPE
*/
@HiddenUsage Examples:
// Hide entire resource class
@Hidden
@Path("/internal")
public class InternalResource {}
// Hide specific operation
@GET
@Hidden
@Operation(summary = "Internal operation")
public Response internalOperation() {}
// Hide parameter
public Response getUser(
@Hidden @QueryParam("debug") Boolean debug,
@PathParam("id") Long id
) {}Adds references to external documentation for various OpenAPI elements.
/**
* Links to external documentation
* Applied to: various annotation elements
*/
@ExternalDocumentation(
description = "User guide documentation", // Short description
url = "https://docs.example.com/users", // Documentation URL (required)
extensions = {@Extension(...)} // Custom extensions
)Usage Examples:
// On operation
@Operation(
summary = "Complex operation",
externalDocs = @ExternalDocumentation(
description = "Detailed usage guide",
url = "https://docs.example.com/complex-operations"
)
)
// On tag
@Tag(
name = "advanced",
description = "Advanced operations",
externalDocs = @ExternalDocumentation(
description = "Advanced features guide",
url = "https://docs.example.com/advanced"
)
)Custom extensions for adding vendor-specific or additional metadata to OpenAPI elements.
/**
* Custom OpenAPI extension
* Repeatable: Yes
*/
@Extension(
name = "x-custom-property", // Extension name (prefixed with x-)
properties = { // Extension properties
@ExtensionProperty(name = "enabled", value = "true"),
@ExtensionProperty(name = "level", value = "2", parseValue = true)
}
)
/**
* Extension property within an extension
*/
@ExtensionProperty(
name = "propertyName", // Property name
value = "propertyValue", // Property value
parseValue = false // Parse as JSON/YAML
)Usage Examples:
@Operation(
summary = "Custom operation",
extensions = {
@Extension(
name = "x-rate-limit",
properties = {
@ExtensionProperty(name = "requests", value = "100"),
@ExtensionProperty(name = "window", value = "3600")
}
),
@Extension(
name = "x-feature-flags",
properties = @ExtensionProperty(
name = "config",
value = "{\"beta\": true, \"experimental\": false}",
parseValue = true
)
)
}
)Defines webhook operations for event-driven API interactions.
/**
* Defines webhook operation (OpenAPI 3.1)
* Repeatable: Yes
*/
@Webhook(
name = "userCreated", // Webhook name
operation = @Operation( // Webhook operation definition
summary = "User created notification",
requestBody = @RequestBody(
content = @Content(schema = @Schema(implementation = UserEvent.class))
)
)
)
/**
* Container for multiple webhooks
*/
@Webhooks({
@Webhook(name = "userCreated", operation = @Operation(...)),
@Webhook(name = "userUpdated", operation = @Operation(...))
})Maps string identifiers to Java classes for complex schema definitions.
/**
* Maps strings to classes for schema definitions
*/
@StringToClassMapItem(
key = "userType", // String key
value = User.class // Mapped class
)enum Explode {
DEFAULT, // Use parameter style default
FALSE, // Don't explode array/object values
TRUE // Explode array/object values
}/**
* Marker annotation for OpenAPI 3.1 specific features
* Applied to: various elements supporting 3.1 features
*/
@OpenAPI31Install with Tessl CLI
npx tessl i tessl/maven-io-swagger-core-v3--swagger-annotations-jakarta