简体   繁体   English

如何为 swagger 2.8.0 建立友好基地 url

[英]how to do friendly base url for swagger 2.8.0

I'm trying to change base access url for API documentation.我正在尝试更改 API 文档的基本访问权限 url。 The url is " http://localhost:8080/swagger-ui.html ". url 是“ http://localhost:8080/swagger-ui.html ”。 I want to get something like " http://localhost:8080/myapi/swagger-ui.html ".我想得到类似“ http://localhost:8080/myapi/swagger-ui.html ”的东西。

I use Springfox 2.8.0 Swagger, Java 8, Spring Boot 2.0 The swagger configuration is:我用Springfox 2.8.0 Swagger, Java 8, Spring Boot 2.0 swagger配置为:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket api(ServletContext servletContext) {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathProvider(new RelativePathProvider(servletContext) {
                    @Override
                    public String getApplicationBasePath() {
                        return "/myapi";
                    }
                })
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(Predicates.not(PathSelectors.regex("/error")))
                .build()
                .useDefaultResponseMessages(false);
    }
}

Custom path provider had to help, but I still get access to api documentation by using url " http://localhost:8080/swagger-ui.html ".自定义路径提供程序必须提供帮助,但我仍然可以使用 url“ http://localhost:8080/swagger-ui.html ”访问 api 文档。 If I use url " http://localhost:8080/myapi/swagger-ui.html ", I get 404 error .如果我使用 url“ http://localhost:8080/myapi/swagger-ui.html ”,我会收到404 错误 Look at the screenshot below.请看下面的屏幕截图。

在此处输入图像描述

For those who use Springfox Swagger 3.0.0对于那些使用 Springfox Swagger 3.0.0 的人

Here's the working configuration for changing base url for docs: 这是更改文档的基本 url 的工作配置:

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

https://github.com/springfox/springfox/issues/2250 - 正如他们所说,您可以配置重定向到您自己的路径

You can edit your SwaggerConfiguration like that:您可以像这样编辑SwaggerConfiguration

Take care to replace the package (which need to be the one containing your REST controllers), the host , and the PATH you need注意替换package (必须是包含 REST 控制器的包)、 host和所需的PATH

@Configuration
@EnableSwagger2
public class SwaggerConfiguration implements WebMvcConfigurer {

    public static final String PATH = "/myapi";

    @Bean
    public Docket api() {
        final var package = "com.julia.rest";
        final var host = "localhost:8080";

        return new Docket(DocumentationType.SWAGGER_2)
                .host(host)
                .select()
                .apis(RequestHandlerSelectors.basePackage(package))
                .paths(PathSelectors.any())
                .build();
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        final var apiDocs = "/v2/api-docs";
        final var configUi = "/swagger-resources/configuration/ui";
        final var configSecurity = "/swagger-resources/configuration/security";
        final var resources = "/swagger-resources";

        registry.addRedirectViewController(PATH + apiDocs, apiDocs).setKeepQueryParams(true);
        registry.addRedirectViewController(PATH + resources, resources);
        registry.addRedirectViewController(PATH + configUi, configUi);
        registry.addRedirectViewController(PATH + configSecurity, configSecurity);
        registry.addRedirectViewController(PATH, "/");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(PATH + "/**").addResourceLocations("classpath:/META-INF/resources/");
    }
}

Another solution is by changing the spring-boot URL context-path :另一种解决方案是更改 spring-boot URL context-path

Edit pour application.properties file:编辑浇注application.properties文件:

server.servlet.context-path=/myapi

Or if you have an application.yml file:或者,如果您有application.yml文件:

server:
  servlet:
    context-path: /myapi

Warning: It will change the base path of all your web services, not only Swagger警告:它会改变所有 Web 服务的基本路径,而不仅仅是 Swagger

I also have faced this problem and tried many possible resolutions, and nothings didn't help really.我也遇到过这个问题并尝试了许多可能的解决方案,但没有任何帮助。 In my case, I can't use any resource redirect as swagger must be accessible as locally as on google cloud by match path /api-docs/**.就我而言,我不能使用任何资源重定向,因为 swagger 必须可以像在谷歌云上一样通过匹配路径 /api-docs/** 在本地访问。 and on google cloud any resource redirection will be denied in my case.在我的情况下,在谷歌云上任何资源重定向都将被拒绝。 All resources must be loading also from this path所有资源也必须从此路径加载

here is my solution:这是我的解决方案:
springfox-swagger2 and springfox-swagger-ui of version 2.9.2 2.9.2 版本的 springfox-swagger2 和 springfox-swagger-ui

@EnableSwagger2
@Configuration
public class SwaggerCommonConfig implements WebMvcConfigurer {
    public static final String PATH = "/api-docs";

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController(PATH, "/");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(PATH + "/**").addResourceLocations("classpath:/META-INF/resources/");
    }
}

and as springfox don't have any possibilities to do it by another way, in my case, we just will create simple controller that will be translating resource requests from our custom path to standard springfox.并且由于 springfox 没有任何可能通过其他方式做到这一点,在我的情况下,我们将创建简单的控制器,将资源请求从我们的自定义路径转换为标准 springfox。 (it's not very elegant part but as it is :)) (这不是很优雅的部分,但确实如此:))

@RestController
@RequestMapping(SwaggerGatewayCommonConfig.PATH)
@RequiredArgsConstructor
public class SwaggerController {
    private final RestTemplate restTemplate;
    private final static String V2_API_DOCS = "/v2/api-docs";
    private final static String SWAGGER_RESOURCES_CONFIGURATION_UI = "/swagger-resources/configuration/ui";
    private final static String SWAGGER_RESOURCES_CONFIGURATION_SECURITY = "/swagger-resources/configuration/security";
    private final static String SWAGGER_RESOURCES = "/swagger-resources";
    private final static Pattern pattern = Pattern.compile("http[s]*://([^/]+)", Pattern.CASE_INSENSITIVE);

    @Value("${server.port}")
    private String port;

    @GetMapping(V2_API_DOCS)
    @SuppressWarnings("unchecked")
    public Map<String, Object> getV2ApiDocs(HttpServletRequest request) {
        Matcher matcher = pattern.matcher(request.getRequestURL().toString());
        matcher.find();

        Map<String, Object> resp = (Map<String, Object>) restTemplate.getForObject(toLocalSwaggerUrl(V2_API_DOCS), Map.class);
        //we have to replace standard host, to requested host. as swagger UI make api requests from this host
        resp.put("host", matcher.group(1));

        return resp;
    }

    @GetMapping(SWAGGER_RESOURCES_CONFIGURATION_UI)
    public Object getSwaggerResourcesConfigurationUi() {
        return restTemplate.getForObject(toLocalSwaggerUrl(SWAGGER_RESOURCES_CONFIGURATION_UI), Object.class);
    }

    @GetMapping(SWAGGER_RESOURCES_CONFIGURATION_SECURITY)
    public Object getSwaggerResourcesConfigurationSecurity() {
        return restTemplate.getForObject(toLocalSwaggerUrl(SWAGGER_RESOURCES_CONFIGURATION_SECURITY), Object.class);
    }

    @GetMapping(SWAGGER_RESOURCES)
    public Object getSwaggerResources() {
        return restTemplate.getForObject(toLocalSwaggerUrl(SWAGGER_RESOURCES), Object.class);
    }

    private String toLocalSwaggerUrl(String path) {
        return "http://localhost:" + port + path;
    }
}

I hope it will save time to somebody faced it also =) Good luck我希望它也能为遇到它的人节省时间 =) 祝你好运

Swagger base access url is constructed from your base application path.So if you change your base application path , you will get the desired behavior.But also all your apis will be changed to that path. Swagger 基本访问 url 是根据您的基本应用程序路径构造的。因此,如果您更改基本应用程序路径,您将获得所需的行为。但您的所有 api 也将更改为该路径。 You can find how to change it here How to set base url for rest in spring boot?您可以在此处找到如何更改它如何在 Spring Boot 中设置用于休息的基本 url? . .

What you did was too change how swagger call other apis from your application, not to change his base url.您所做的太改变了招摇从您的应用程序调用其他 api 的方式,而不是更改他的基本 url。 There are some tricks to change the swagger base url without changing application base path (moving manually all swagger resources), but i do not recommend that.有一些技巧可以在不更改应用程序基本路径的情况下更改 swagger 基本 url(手动移动所有 swagger 资源),但我不建议这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM