Swagger-UI 和 Ktor 如何导入 swagger.json 或 .yaml 文件并启动 Swagger-UI?

Art*_*dov 3 kotlin swagger projekktor swagger-ui ktor

我有一个问题,我已经生成了 OpenApi Swagger 文件(swagger.json 和 swagger.yaml) 是否有可能在 Ktor(kotlin)中以某种方式导入这些文件并在特定路由上启动 swagger-ui 服务器?我访问了ktor-swagger 项目,但可以了解如何添加 json 文件以显示 swagger-ui。有什么建议 ?

Cub*_*ube 5

使您可以从静态路由访问 json 文件

  1. 在资源目录中创建“文件”目录

  2. 使用下一个代码从“文件”目录路由静态文件

    routing {
        static("/static") {
            resources("files")
        }
        //...
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 让我们将 json 文件命名为"test.json",然后将它放在 "files" 文件夹中

所以现在你运行应用程序并通过 http://localhost:8080/static/test.json 查看这个文件

然后我们需要安装和配置OpenApiGen

  1. 添加 OpenApiGen 依赖项,您可以在此处找到如何执行此操作https://github.com/papsign/Ktor-OpenAPI-Generator

  2. 然后使用下面的代码

    install(OpenAPIGen) {
        serveSwaggerUi = true
        swaggerUiPath = "/swagger-ui"
    }
    
    Run Code Online (Sandbox Code Playgroud)

现在您可以使用 http://localhost:8080/swagger-ui/index.html?url=/static/test.json URL 通过 swagger UI 查看您的文件

此外,您可以提供自己的使用重定向的路线

get("/api") {
   call.respondRedirect("/swagger-ui/index.html?url=/static/test.json", true)
}
Run Code Online (Sandbox Code Playgroud)

这将允许您只使用 http://localhost:8080/api