Ulky Igor
Ulky Igor

Reputation: 362

Springfox swagger "try it out" hiting on localhost

I am using spring boot 2.2.4 to build a REST API, and springfow 2.9 for api doc.

I deployed the app in a docker container, and I am able to access the swagger-ui.htmlpage. However, when using "ty it out" feature, the request is fired on the localhost url (https://locahost/api/find), instead of the service url (https://service.acces.url/api/find). How can I fix that ?

swagger configuration:

    @Bean
public Docket api(){
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("fr.test")) // only select API in this package
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo())
            ;
}

// build some user friendly name and description for the API doc UI
private ApiInfo apiInfo(){
    return new ApiInfoBuilder()
            .title("test")
            .description("test.")
            .license("Apache 2.0")
            .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
            .build()
            ;
}

EDIT
I can see that the link to /v2/api-docs si well set, but couldn't find how they did in the source code...

enter image description here

Upvotes: 4

Views: 1504

Answers (1)

Madhu Bhat
Madhu Bhat

Reputation: 15183

By default, when you use the "Try it out" feature on Swagger UI, it would make an HTTP call on localhost itself. In case you want to override that behaviour, you need to set the host property of Docket with the required hostname as below:

@Bean
public Docket api(){
    return new Docket(DocumentationType.SWAGGER_2)
            .host("hostname")
            .select()
            .apis(RequestHandlerSelectors.basePackage("fr.test")) // only select API in this package
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo())
            ;
}

// build some user friendly name and description for the API doc UI
private ApiInfo apiInfo(){
    return new ApiInfoBuilder()
            .title("test")
            .description("test.")
            .license("Apache 2.0")
            .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
            .build()
            ;
}

It would be ideal to get that hostname value from a configuration so that you can modify it when required without changing your code. And when you set it as service.acces.url as you require, the HTTP call on Swagger UI would be made to https://service.acces.url/api/find.

Upvotes: 1

Related Questions