Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to serve swagger-ui.html at more convenient URL? #2250

Closed
citkane opened this issue Feb 12, 2018 · 25 comments
Closed

How to serve swagger-ui.html at more convenient URL? #2250

citkane opened this issue Feb 12, 2018 · 25 comments
Labels

Comments

@citkane
Copy link

citkane commented Feb 12, 2018

I want to be able to browse to http://localhost:8080/swagger instead of http://localhost:8080/swagger-ui.html to access the UI, but I am struggling to find documentation or examples.

Could somebody please confirm if this is possible and help if so?

I am on:

Maven 3.5
Spring-boot 1.5.10
Springfox-swagger2 2.8..0
Springfox-swagger-ui 2.8.0

I have seen these, but remain confused:
#1406
#1263
http://springfox.github.io/springfox/docs/current/#springfox-swagger2-with-spring-mvc-and-spring-boot

The doc say:

Optional swagger-ui ui configuration currently only supports the validation url

But this seems not reasonable for such a basic convenience setting.

@nobe0716
Copy link
Contributor

I didnt changed swagger-ui html configuration but add request mapping for the redirection to swagger-ui.html

//...in controller...
@RequestMapping("/swagger")
public String greeting() {
	return "redirect:/swagger-ui.html";
}

@citkane
Copy link
Author

citkane commented Feb 13, 2018

Perfect! (..well, almost as redirect is a workaround). Thanks @nobe0716 .

For posterity I will expand on your answer to show how to prevent the redirect method from showing up in the UI:

Controller: note the classpath

package io.bisq.engine.app; //classpath outside of the REST controllers
...
@Controller //note - this is a spring-boot controller, not @RestController
public class HomeController {
    @RequestMapping ("/swagger")
    public String home() {
	return "redirect:/swagger-ui.html";
    }
}

Config

package io.bisq.engine.app;
...
@Configuration
@EnableSwagger2
public class SpringConfig {   
    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)  
            .select()                                  
            .apis(RequestHandlerSelectors.basePackage( "io.bisq.engine.app.api" )) //classpath for the REST controllers
            .paths(PathSelectors.any())                          
            .build();     
    }
}

@citkane citkane closed this as completed Feb 13, 2018
@citkane citkane changed the title How to serve swagger-ui.htm at more convenient URL? How to serve swagger-ui.html at more convenient URL? Feb 13, 2018
@dilipkrish
Copy link
Member

dilipkrish commented Feb 14, 2018

@citkane the swagger-ui bundled with the project is only a convenience. It jumpstarts 80% of the use cases. In this instance the customization is simple. For cases where customizations are more involved the prescribed solution is to download swagger-ui into the appropriate folder in your project and configure it as you desire and not use the bundled swagger-ui.

Its not really a work around. The swagger-ui.html in the browser url is an essential anchor, we use that url to figure out the other urls relative (api-docs, ui configuration, security configuration etc.) to it.

@zpf7879
Copy link

zpf7879 commented Sep 6, 2018

I tried the approach by @citkane , but it seems not working in a WebFlux context.

java.lang.IllegalStateException: Could not resolve view with name 'redirect:/swagger-ui.html'.
at org.springframework.web.reactive.result.view.ViewResolutionResultHandler.lambda$resolveViews$3(ViewResolutionResultHandler.java:277)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:107)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1083)
at reactor.core.publisher.MonoCollectList$MonoBufferAllSubscriber.onComplete(MonoCollectList.java:117)
at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:349)
at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onComplete(FluxConcatMap.java:265)

@nobe0716
Copy link
Contributor

nobe0716 commented Sep 7, 2018

Hello @zpf7879

Webflux provides view resolution Ref.
Your swagger configuration may be wrong.

Would you mind if I ask a repo?

@zpf7879
Copy link

zpf7879 commented Sep 7, 2018

Thanks @nobe0716
https://github.com/zpf7879/swaggertest

After running it, you can access http://localhost:8080/swagger-ui.html#/ and see it works. However, if you try access http://localhost:8080/swagger you will see the error callstack I mentioned before.

@dilipkrish
Copy link
Member

Thanks for helping out @nobe0716

@nobe0716
Copy link
Contributor

nobe0716 commented Sep 17, 2018

@zpf7879
Hello, I missed above mention.

I wonder why "redirect:swagger-ui.html" didn't work, but found alternative way.

Try adding RouterFunction bean in your applicationScope.
It works on me.

@SpringBootApplication
public class MyApp {
	public static void main(String[] args) {
		SpringApplication.run(MyApp.class, args);
	}

	@Bean
	RouterFunction<ServerResponse> routerFunction() {
		return route(GET("/swagger"), req ->
			ServerResponse.temporaryRedirect(URI.create("swagger-ui.html")).build());
	}
}

@zpf7879
Copy link

zpf7879 commented Sep 18, 2018

@nobe0716 , thanks for your time and help. I also got it work in a different approach.

@Component
public class SwaggerWebFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().pathWithinApplication().value();
        if (path.startsWith("/api/swagger-ui.html") || path.startsWith("/api/webjars")
                || path.startsWith("/api/api-docs") || path.startsWith("/api/configuration")
                || path.startsWith("/api/swagger-resources") || path.startsWith("/api/v2"))) {
            exchange = exchange.mutate().request(request.mutate().path(path.substring(4)).build()).build();
        }
        return chain.filter(exchange);
    }
}

`

@yernibabk
Copy link

Hi,
I have one scenario, when some body accessing current service swagger-ui, it has to show another consumer service swagger-ui page. Can help me on how to re-direct swagger url?

@ghost
Copy link

ghost commented May 25, 2019

My server does not allow anything to be requested directly under /*. See https://stackoverflow.com/questions/56307892/set-base-path-for-swagger-ui-html.

In short: Any request matchin /* gets redirected to /a/web. This ie because I am hosting two web applications. One is /a/web the other is under /a/admin. Hence none of the above solutions can work for me.

I really need swagger to run under something like /a/swagger/swagger-ui.html

@MugdhaB
Copy link

MugdhaB commented Nov 14, 2019

Is there a sample of bundling customized swagger ui into a springboot project?

@PyMeH
Copy link

PyMeH commented Nov 22, 2019

Redirects are workarounds that only work in certain cases. In micro services architecture chances are redirects won't work.

@prafful13
Copy link

@silentsnooc were you able to achieve your goal?

@dilipkrish
Copy link
Member

dilipkrish commented Jul 17, 2020

With 3.0.0 this becomes a lot simpler... swagger-ui is always served off /<context-path>/<swagger-ui-base-url>/swagger-ui/index.html

where swagger-ui-base-url can be configured via application property springfox.documentation.swagger-ui.baseUrl

@prafful13
Copy link

Hi @dilipkrish , I am new to springfox, can you give me an example which shows how to use property source for changing location of swagger-resources, especially /v3/api-docs? http://springfox.github.io/springfox/docs/current/#customizing-the-swagger-endpoints

@dilipkrish
Copy link
Member

If you're using springfox-boot-starter it should provide auto-complete when you edit your application.properties or application.yml file. If not then just add the properties as described on the link you provided.

@prafful13
Copy link

Screen Shot 2020-07-18 at 11 19 18 AM
I get an error like this, I am using spring-boot-starter and have also added springfox-oas dependencies.
When running with springfox.documentation.swagger.v2.path=/documentation, I still get my v3/api-docs served at /

Any help is appreciated!

@dilipkrish
Copy link
Member

dilipkrish commented Jul 18, 2020

You're clearly don't doing something expected. If you bring in the boot starter you shouldn't have to do anything else like adding additional dependencies.

However thanks for catching the missed property (the error that's shown on your screenshot) that wasn't included in the configuration properties. Trying setting this property springfox.documentation.open-api.v3.path to your desired path if your documentation type is open api and springfox.documentation.swagger.v2.path for swagger 2.0. It should resolve your issue.

You can ignore the error you've seeing above, its because the configuration property is not described. I've added a story 👇 to fix that.

@kronographTL
Copy link

springdoc.swagger-ui.path=/swagger-ui-custom.html

@Quantas
Copy link

Quantas commented Aug 1, 2020

I also get the IDE errors about the missing config properties, however this configuration let me move the Swagger endpoints somewhere else:

springfox:
  documentation:
    swaggerUi:
      baseUrl: /documentation
    openApi:
      v3:
        path: /documentation/v3/api-docs
    swagger:
      v2:
        path: /documentation/v2/api-docs

@prafful13
Copy link

Thanks @dilipkrish @Quantas . Above suggestions helped.
However, will above properties also move /swagger-resources and /web-jars ? Why I ask is because now I have shifted my service behind an API gateway and am facing a new issue #3468. Basically the inferred url is incorrect in the sense it is now using http protocol instead of https which it was using earlier (when not using api gateway). Following this thread - https://stackoverflow.com/questions/49155420/springfox-swagger-ui-html-unable-to-infer-base-url-caused-by-missing-cookies, I believe it could be because I need to permit all paths related to swagger, whereas I am currently only permitting /{baseUrl}/** which has swagger ui and v3/api-docs.

Do you have any idea if that is the reason or is there something else to look for?

@Quantas
Copy link

Quantas commented Aug 3, 2020

@prafful13 Yes this will move all the resources and web-jars below the path you specify for swaggerUi.baseUrl

@dilipkrish
Copy link
Member

API gateways are tricky and depends on how you've configured it, and if you're passing along X-FORWARD headers and if spring is configured to use them or not. In general, @Quantas solution will work of you set it up correctly.

@klerco
Copy link

klerco commented Dec 8, 2020

Hi @dilipkrish , not sure what I'm doing wrong, but I wanted to move the base url of swagger-ui to other location together with api-docs. I'm fine with swagger2, but don't mind OAS3. Looks like swagger-ui is trying to find api-docs on wrong location.

My error (when I access http://localhost:7971/test-app/documentation/swagger-ui/):
Fetch error
undefined http://localhost:7971/test-app/documentation/documentation/v2/api-docs

My setup:
server.servlet.context-path=/test-app
springfox.documentation.swagger.v2.path=/documentation/v2/api-docs
springfox.documentation.open-api.v3.path=/documentation/v3/api-docs
springfox.documentation.swagger-ui.baseUrl=/documentation/

But these are working fine:
http://localhost:7971/test-app/documentation/v3/api-docs
http://localhost:7971/test-app/documentation/v2/api-docs

I have following dependencies:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>

and configuration annotations (no matter if I have them or not, result is the same):
@EnableSwagger2
@EnableOpenApi

Works only if:

  • I omit swagger-ui.baseUrl property and open-api.v3.path property (but then swagger-ui is accessible here: http://localhost:7971/test-app/swagger-ui/)
  • or I omit swagger.v2.path and define open-api.v3.path as /documentation/v2/api-docs (but then I have only OAS3 api docs)

any ideas please? :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests