How do I hide endpoints only for a specific profile in spring boot?

Viewed 459

I am using open api 3 and want to hide some endpoints in swagger ui. In swagger2 I found what can be done in this way by creating my own annotation, but I don't understand how I can do it in openapi3.

@Bean
public Docket postsApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .groupName("public-api")
            .apiInfo(apiInfo())
            .select()
                 // This is the part that will ignore the method
                .apis((handler) -> !handler.isAnnotatedWith(IgnoreForProd.class))
            .build();
}
1 Answers

I've solved this issue like this:

1st - I have removed the springfox and springfox-swagger-ui dependencies from pom.xml and replaced it with springdoc-openapi-ui like this:

<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.6</version>

2nd - created the Bean below:

@Configuration
public class OpenAPIConfig {

    @Value("${version:unknown}")
    private String version;

    @Bean
    public OpenAPI springShopOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("Title API")
                        .description("Description API")
                        .version(version)
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("SpringShop Wiki Documentation")
                        .url("https://springshop.wiki.github.org/docs"));
    }

}

3rd - then on application.yml you can filter by package and/or path:

springdoc:
  packages-to-scan: com.company.projectxyz.controller
  pathsToMatch: /api/whatever/public/**

4th - and if you need to filter different paths/packages per profile, also on application.yml you can do the 3rd step inside of: spring.config.activate.on-profile: dev/qa/prod...

and access your swagger at /swagger-ui/index.html

I hope it helps =)

Related