Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 745
Ulky Igor Avatar asked Feb 09 '26 23:02

Ulky Igor


1 Answers

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.

like image 181
Madhu Bhat Avatar answered Feb 13 '26 09:02

Madhu Bhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!