### Documenting Router Functions with @RouterOperation in Java Source: https://context7.com/springdoc/springdoc-openapi/llms.txt This snippet demonstrates how to document Spring WebFlux functional endpoints using the @RouterOperation and @RouterOperations annotations. It defines GET and POST operations for user-related endpoints, specifying paths, methods, handler beans, and detailed OpenAPI operation information including parameters and responses. Dependencies include springdoc-openapi annotations and Spring WebFlux. ```java import org.springdoc.core.annotations.RouterOperation; import org.springdoc.core.annotations.RouterOperations; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.reactive.function.server.*; @Configuration public class RouterConfig { @Bean @RouterOperations({ @RouterOperation( path = "/api/users/{id}", method = RequestMethod.GET, beanClass = UserHandler.class, beanMethod = "getUser", operation = @Operation( operationId = "getUserById", summary = "Get user by ID", parameters = { @Parameter(in = ParameterIn.PATH, name = "id", description = "User ID", required = true) }, responses = { @ApiResponse(responseCode = "200", description = "User found", content = @Content(schema = @Schema(implementation = User.class))), @ApiResponse(responseCode = "404", description = "User not found") } ) ), @RouterOperation( path = "/api/users", method = RequestMethod.POST, beanClass = UserHandler.class, beanMethod = "createUser", operation = @Operation( operationId = "createUser", summary = "Create a new user", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody( content = @Content(schema = @Schema(implementation = User.class)) ), responses = { @ApiResponse(responseCode = "201", description = "User created", content = @Content(schema = @Schema(implementation = User.class))) } ) ) }) public RouterFunction userRoutes(UserHandler userHandler) { return RouterFunctions.route() .GET("/api/users/{id}", userHandler::getUser) .POST("/api/users", userHandler::createUser) .build(); } } ``` -------------------------------- ### Add springdoc-openapi dependency Source: https://github.com/springdoc/springdoc-openapi/blob/main/README.md Include the springdoc-openapi-starter-webflux-ui library in your project to enable OpenAPI support for Spring WebFlux applications. ```xml org.springdoc springdoc-openapi-starter-webflux-ui last-release-version ``` ```groovy implementation 'org.springdoc:springdoc-openapi-starter-webflux-ui:latest' ``` -------------------------------- ### Configure API Groups with GroupedOpenApi Source: https://context7.com/springdoc/springdoc-openapi/llms.txt Demonstrates how to create multiple API groups using the GroupedOpenApi builder. This allows developers to separate documentation based on paths, packages, or specific security requirements. ```java import org.springdoc.core.models.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiConfig { @Bean public GroupedOpenApi publicApi() { return GroupedOpenApi.builder() .group("public-api") .displayName("Public API") .pathsToMatch("/api/public/**") .packagesToScan("com.example.controllers.public") .build(); } @Bean public GroupedOpenApi adminApi() { return GroupedOpenApi.builder() .group("admin-api") .displayName("Admin API") .pathsToMatch("/api/admin/**") .pathsToExclude("/api/admin/internal/**") .packagesToScan("com.example.controllers.admin") .addOpenApiCustomizer(openApi -> { openApi.getInfo().setTitle("Admin API Documentation"); }) .addOperationCustomizer((operation, handlerMethod) -> { operation.addTagsItem("admin"); return operation; }) .build(); } @Bean public GroupedOpenApi internalApi() { return GroupedOpenApi.builder() .group("internal-api") .pathsToMatch("/api/internal/**") .producesToMatch("application/json") .consumesToMatch("application/json") .headersToMatch("X-Internal-Token") .build(); } } ``` -------------------------------- ### Add Springdoc OpenAPI UI Dependency (Gradle) Source: https://github.com/springdoc/springdoc-openapi/blob/main/README.md This Gradle dependency integrates springdoc-openapi with Swagger UI into a Spring Boot 3.x application, making documentation available at /swagger-ui.html. ```groovy implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:latest' ``` -------------------------------- ### Apply Global OpenAPI Customizations Source: https://context7.com/springdoc/springdoc-openapi/llms.txt Shows how to implement GlobalOpenApiCustomizer to modify OpenAPI metadata, sort schemas, and inject common response headers across all API groups. ```java import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.media.Schema; import org.springdoc.core.customizers.GlobalOpenApiCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Map; import java.util.TreeMap; @Configuration public class GlobalCustomizerConfig { @Bean public GlobalOpenApiCustomizer globalOpenApiCustomizer() { return openApi -> { Info info = openApi.getInfo(); if (info != null) { info.setTitle(info.getTitle() + " - v" + info.getVersion()); } if (openApi.getComponents() != null && openApi.getComponents().getSchemas() != null) { Map sortedSchemas = new TreeMap<>(openApi.getComponents().getSchemas()); openApi.getComponents().setSchemas(sortedSchemas); } if (openApi.getPaths() != null) { openApi.getPaths().values().forEach(pathItem -> { pathItem.readOperations().forEach(operation -> { if (operation.getResponses() != null) { operation.getResponses().values().forEach(response -> { response.addHeaderObject("X-Request-ID", new io.swagger.v3.oas.models.headers.Header() .description("Unique request identifier") .schema(new io.swagger.v3.oas.models.media.StringSchema())); }); } }); }); } }; } } ``` -------------------------------- ### Customize OpenAPI Specification with OpenApiCustomizer Source: https://context7.com/springdoc/springdoc-openapi/llms.txt Shows how to implement OpenApiCustomizer to globally modify the OpenAPI object. This includes setting API info, adding server URLs, and defining security schemes. ```java import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.Contact; import io.swagger.v3.oas.models.info.License; import io.swagger.v3.oas.models.servers.Server; import io.swagger.v3.oas.models.security.SecurityScheme; import io.swagger.v3.oas.models.security.SecurityRequirement; import io.swagger.v3.oas.models.Components; import org.springdoc.core.customizers.OpenApiCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiCustomizerConfig { @Bean public OpenApiCustomizer customOpenApi() { return openApi -> { openApi.setInfo(new Info() .title("My Application API") .version("2.0.0") .description("REST API for My Application") .contact(new Contact() .name("API Support") .email("support@example.com") .url("https://example.com/support")) .license(new License() .name("Apache 2.0") .url("https://www.apache.org/licenses/LICENSE-2.0"))); openApi.addServersItem(new Server() .url("https://api.example.com") .description("Production server")); openApi.addServersItem(new Server() .url("https://staging-api.example.com") .description("Staging server")); openApi.setComponents(new Components() .addSecuritySchemes("bearerAuth", new SecurityScheme() .type(SecurityScheme.Type.HTTP) .scheme("bearer") .bearerFormat("JWT") .description("JWT Authorization header"))); openApi.addSecurityItem(new SecurityRequirement().addList("bearerAuth")); }; } } ``` -------------------------------- ### Implement Security Schemes for OpenAPI in Java Source: https://context7.com/springdoc/springdoc-openapi/llms.txt Demonstrates how to define reusable security schemes (Bearer, OAuth2, API Key) using annotations and apply them to specific REST controllers for granular access control. ```java @Configuration @SecurityScheme( name = "bearerAuth", type = SecuritySchemeType.HTTP, scheme = "bearer", bearerFormat = "JWT" ) public class SecurityConfig { @Bean public OpenAPI customOpenAPI() { return new OpenAPI().components(new Components()); } } @RestController public class SecureController { @Operation(security = @SecurityRequirement(name = "bearerAuth")) @GetMapping("/resource") public Resource getResource() { return resourceService.get(); } } ``` -------------------------------- ### Document REST Controllers with Spring and OpenAPI Annotations (Java) Source: https://context7.com/springdoc/springdoc-openapi/llms.txt This snippet demonstrates how to document REST endpoints using standard Spring annotations along with OpenAPI annotations for detailed API descriptions. It includes operations for creating and retrieving organizations, specifying request/response schemas, and handling different status codes. Dependencies include Spring Boot, Swagger annotations, and standard Java libraries. ```java import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; @RestController @Tag(name = "Organizations", description = "Organization management API") public class OrganizationController { @Operation(summary = "Create organization", description = "Create a new organization in the system") @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "Organization created successfully", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Organization.class))), @ApiResponse(responseCode = "400", description = "Invalid input", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))), @ApiResponse(responseCode = "409", description = "Organization already exists", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))) }) @PostMapping(value = "/organizations", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public Organization createOrganization( @Parameter(description = "Organization details", required = true) @RequestBody Organization organization) { return organizationService.create(organization); } @GetMapping(value = "/organizations/{id}", produces = {"application/json", "application/xml"}) public Organization getOrganization( @Parameter(description = "Organization ID", required = true) @PathVariable("id") Long id) { return organizationService.findById(id); } } ``` -------------------------------- ### Configure Custom OpenAPI Docs Path Source: https://github.com/springdoc/springdoc-openapi/blob/main/README.md This property allows customization of the URL path for the OpenAPI documentation (JSON format) in a Spring Boot application. ```properties # /api-docs endpoint custom path springdoc.api-docs.path=/api-docs ``` -------------------------------- ### Add Springdoc OpenAPI UI Dependency (Maven) Source: https://github.com/springdoc/springdoc-openapi/blob/main/README.md This Maven dependency integrates springdoc-openapi with Swagger UI into a Spring Boot 3.x application, making documentation available at /swagger-ui.html. ```xml org.springdoc springdoc-openapi-starter-webmvc-ui last-release-version ``` -------------------------------- ### Programmatic Springdoc Configuration with SpringDocUtils in Java Source: https://context7.com/springdoc/springdoc-openapi/llms.txt This Java snippet shows how to use SpringDocUtils for programmatic configuration of springdoc-openapi. It covers hiding controllers, replacing types with simpler schemas, adding custom file types, ignoring wrapper types, and configuring simple types for @ParameterObject. This configuration is applied using the @PostConstruct annotation in a Spring @Configuration class. ```java import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import org.springdoc.core.utils.SpringDocUtils; import org.springframework.context.annotation.Configuration; import jakarta.annotation.PostConstruct; import java.time.Instant; import java.util.UUID; @Configuration public class SpringDocConfiguration { @PostConstruct public void configureSpringDoc() { SpringDocUtils config = SpringDocUtils.getConfig(); // Hide specific controller classes from documentation config.addHiddenRestControllers(InternalController.class); config.addHiddenRestControllers("com.example.internal.HealthCheckController"); // Replace complex types with simpler schema representations config.replaceWithClass(Instant.class, String.class); config.replaceWithSchema(UUID.class, new StringSchema().format("uuid")); // Add custom file types for multipart handling config.addFileType(CustomFileWrapper.class); // Ignore wrapper types in request/response config.addRequestWrapperToIgnore(AsyncResult.class); config.addResponseWrapperToIgnore(ResponseEntity.class); config.addResponseTypeToIgnore(Void.class); // Add simple types for @ParameterObject handling config.addSimpleTypesForParameterObject(Money.class, Currency.class); // Configure types to ignore in schema generation config.addJavaTypeToIgnore(HttpServletRequest.class); config.addJavaTypeToIgnore(HttpServletResponse.class); // Add custom deprecation annotation support config.addDeprecatedType(ObsoleteApi.class); // Initialize extra schema type mappings config.initExtraSchemas(); } } ``` -------------------------------- ### Add Springdoc OpenAPI API Dependency (Gradle) Source: https://github.com/springdoc/springdoc-openapi/blob/main/README.md This Gradle dependency integrates springdoc-openapi into a Spring Boot 3.x application for generating OpenAPI documentation (JSON/YAML) without Swagger UI. ```groovy implementation 'org.springdoc:springdoc-openapi-starter-webmvc-api:latest' ``` -------------------------------- ### Configure SpringDoc OpenAPI via application.yml Source: https://context7.com/springdoc/springdoc-openapi/llms.txt Defines the global configuration for SpringDoc, including API documentation paths, Swagger UI appearance, package scanning, and integration flags for Spring Security and HATEOAS. ```yaml springdoc: api-docs: enabled: true path: /v3/api-docs version: openapi_3_1 swagger-ui: enabled: true path: /swagger-ui.html syntax-highlight: theme: monokai packages-to-scan: com.example.api group-configs: - group: users-api paths-to-match: /api/users/** ``` -------------------------------- ### Permit documentation paths in Spring Security Source: https://github.com/springdoc/springdoc-openapi/blob/main/README.md Configure the SecurityFilterChain to allow public access to OpenAPI documentation and Swagger UI endpoints when Spring Security is enabled. ```java @Bean SecurityFilterChain api(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers( "/v3/api-docs/**", "/v3/api-docs.yaml", "/swagger-ui/**", "/swagger-ui.html" ).permitAll() .anyRequest().authenticated() ); return http.build(); } ``` -------------------------------- ### Add Springdoc OpenAPI API Dependency (Maven) Source: https://github.com/springdoc/springdoc-openapi/blob/main/README.md This Maven dependency integrates springdoc-openapi into a Spring Boot 3.x application for generating OpenAPI documentation (JSON/YAML) without Swagger UI. ```xml org.springdoc springdoc-openapi-starter-webmvc-api last-release-version ``` -------------------------------- ### SpringDocUtils Configuration Source: https://context7.com/springdoc/springdoc-openapi/llms.txt Programmatic configuration for springdoc-openapi using SpringDocUtils. ```APIDOC ## Programmatic Configuration with SpringDocUtils ### Description Configure springdoc-openapi programmatically to ignore types, replace schemas, and add custom type handling. ### Usage Use the `SpringDocUtils.getConfig()` to access the configuration and apply various settings like: - Hiding specific controllers. - Replacing complex types with simpler schema representations (e.g., `Instant` with `String`). - Replacing types with custom schema definitions (e.g., `UUID` with `StringSchema`). - Adding custom file types for multipart handling. - Ignoring wrapper types in request/response. - Adding simple types for `@ParameterObject` handling. - Configuring types to ignore in schema generation. - Adding custom deprecation annotation support. - Initializing extra schema type mappings. ### Example Configuration Snippet ```java import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import org.springdoc.core.utils.SpringDocUtils; import org.springframework.context.annotation.Configuration; import jakarta.annotation.PostConstruct; import java.time.Instant; import java.util.UUID; @Configuration public class SpringDocConfiguration { @PostConstruct public void configureSpringDoc() { SpringDocUtils config = SpringDocUtils.getConfig(); // Hide specific controller classes from documentation config.addHiddenRestControllers(InternalController.class); config.addHiddenRestControllers("com.example.internal.HealthCheckController"); // Replace complex types with simpler schema representations config.replaceWithClass(Instant.class, String.class); config.replaceWithSchema(UUID.class, new StringSchema().format("uuid")); // Add custom file types for multipart handling config.addFileType(CustomFileWrapper.class); // Ignore wrapper types in request/response config.addRequestWrapperToIgnore(AsyncResult.class); config.addResponseWrapperToIgnore(ResponseEntity.class); config.addResponseTypeToIgnore(Void.class); // Add simple types for @ParameterObject handling config.addSimpleTypesForParameterObject(Money.class, Currency.class); // Configure types to ignore in schema generation config.addJavaTypeToIgnore(HttpServletRequest.class); config.addJavaTypeToIgnore(HttpServletResponse.class); // Add custom deprecation annotation support config.addDeprecatedType(ObsoleteApi.class); // Initialize extra schema type mappings config.initExtraSchemas(); } } ``` ``` -------------------------------- ### User API Endpoints Source: https://context7.com/springdoc/springdoc-openapi/llms.txt Documentation for user-related API endpoints using @RouterOperation. ```APIDOC ## GET /api/users/{id} ### Description Retrieves a user by their unique identifier. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **User** (User) - The user object if found. #### Error Response (404) - Description: User not found. ``` ```APIDOC ## POST /api/users ### Description Creates a new user. ### Method POST ### Endpoint /api/users ### Request Body - **User** (User) - The user object to be created. ### Response #### Success Response (201) - **User** (User) - The newly created user object. ``` -------------------------------- ### Customize OpenAPI Operations with OperationCustomizer Source: https://context7.com/springdoc/springdoc-openapi/llms.txt Implements the OperationCustomizer interface to dynamically modify OpenAPI operations. This allows for the global addition of headers, conditional documentation updates based on annotations, and custom operation ID generation. ```java import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.media.StringSchema; import org.springdoc.core.customizers.OperationCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.method.HandlerMethod; @Configuration public class OperationCustomizerConfig { @Bean public OperationCustomizer globalHeaderCustomizer() { return (Operation operation, HandlerMethod handlerMethod) -> { // Add correlation ID header to all operations Parameter correlationIdParam = new Parameter() .in("header") .name("X-Correlation-ID") .description("Unique request correlation ID for tracing") .required(false) .schema(new StringSchema().format("uuid")); operation.addParametersItem(correlationIdParam); // Add deprecated notice based on annotation if (handlerMethod.hasMethodAnnotation(Deprecated.class)) { operation.setDeprecated(true); String existingDesc = operation.getDescription() != null ? operation.getDescription() : ""; operation.setDescription(existingDesc + "\n\n**Warning:** This endpoint is deprecated."); } // Customize operation ID String className = handlerMethod.getBeanType().getSimpleName(); String methodName = handlerMethod.getMethod().getName(); operation.setOperationId(className + "_" + methodName); return operation; }; } } ``` -------------------------------- ### Configure Custom Swagger UI Path Source: https://github.com/springdoc/springdoc-openapi/blob/main/README.md This property allows customization of the URL path for the Swagger UI documentation in a Spring Boot application. ```properties # swagger-ui custom path springdoc.swagger-ui.path=/swagger-ui.html ``` -------------------------------- ### Configure separate management port Source: https://github.com/springdoc/springdoc-openapi/blob/main/README.md Define application and management ports in application.yml to separate standard application traffic from Actuator endpoints. ```yaml server: port: 8080 management: server: port: 9090 endpoints: web: exposure: include: health,info ``` -------------------------------- ### Filter API Endpoints with OpenApiMethodFilter Source: https://context7.com/springdoc/springdoc-openapi/llms.txt Demonstrates how to selectively include or exclude controller methods from OpenAPI documentation. It uses custom annotations and class-name checks to filter methods dynamically. ```java import org.springdoc.core.filters.OpenApiMethodFilter; import org.springdoc.core.models.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.lang.reflect.Method; @Configuration public class MethodFilterConfig { @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @java.lang.annotation.Target(java.lang.annotation.ElementType.METHOD) public @interface InternalApi {} @Bean public OpenApiMethodFilter publicApiFilter() { return (Method method) -> { if (method.isAnnotationPresent(InternalApi.class)) { return false; } String className = method.getDeclaringClass().getSimpleName(); if (className.endsWith("InternalController")) { return false; } return true; }; } @Bean public GroupedOpenApi filteredApi() { return GroupedOpenApi.builder() .group("public") .pathsToMatch("/api/**") .addOpenApiMethodFilter(method -> { return method.getName().startsWith("get") || method.getName().startsWith("create") || method.getName().startsWith("find"); }) .build(); } } ``` -------------------------------- ### Flatten Request Parameters with @ParameterObject Source: https://context7.com/springdoc/springdoc-openapi/llms.txt Uses the @ParameterObject annotation to automatically expand complex POJOs into individual query parameters in the OpenAPI documentation. This simplifies API definitions for search criteria and filter objects. ```java import org.springdoc.core.annotations.ParameterObject; import io.swagger.v3.oas.annotations.Parameter; import org.springframework.web.bind.annotation.*; import jakarta.validation.constraints.*; // Define a parameter object class public class SearchCriteria { @Parameter(description = "Search query string") private String query; @Parameter(description = "Page number (0-indexed)") @Min(0) private int page = 0; @Parameter(description = "Page size") @Min(1) @Max(100) private int size = 20; @Parameter(description = "Sort field") private String sortBy; @Parameter(description = "Sort direction") private SortDirection sortDirection = SortDirection.ASC; public enum SortDirection { ASC, DESC } // Getters and setters omitted for brevity } @RestController @RequestMapping("/api/products") public class ProductController { // @ParameterObject flattens SearchCriteria into individual query params @GetMapping("/search") public Page searchProducts(@ParameterObject SearchCriteria criteria) { return productService.search(criteria); } } ``` -------------------------------- ### Disable Springdoc OpenAPI Endpoints Source: https://github.com/springdoc/springdoc-openapi/blob/main/README.md This property disables all springdoc-openapi generated endpoints, including API documentation and Swagger UI, in a Spring Boot application. ```properties # disable api-docs springdoc.api-docs.enabled=false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.