如何为ZIO ZServerEndpoints使用OpenAPIDocsInterpreter生成Tapir文档?
如何为ZIO ZServerEndpoints使用OpenAPIDocsInterpreter生成Tapir文档?
我之前也踩过这个坑!你遇到的问题核心在于ZServerEndpoint和Endpoint根本不是同一个类型——前者是绑定了ZIO服务端处理逻辑的完整端点实例,后者只是纯API结构的定义,直接强行类型转换肯定会抛出类转换异常,完全合情合理。
解决方法其实很简单:每个ZServerEndpoint都自带一个endpoint属性,这正是OpenAPIDocsInterpreter需要的纯API定义部分。你只需要把你的ZServerEndpoints列表转换成纯Endpoint的集合就行,不需要任何黑魔法。
给你一个完整的工作示例参考:
import sttp.tapir._ import sttp.tapir.server.zio.ZServerEndpoint import sttp.tapir.docs.openapi.OpenAPIDocsInterpreter import sttp.tapir.openapi.circe.yaml._ import zio._ // 先定义几个示例ZServerEndpoint val helloEndpoint: ZServerEndpoint[Any, Any] = endpoint.get .in("hello") .in(query[String]("name")) .out(stringBody) .zServerLogic(name => ZIO.succeed(s"Hello, $name!")) val healthEndpoint: ZServerEndpoint[Any, Any] = endpoint.get .in("health") .out(stringBody) .zServerLogic(_ => ZIO.succeed("OK")) // 把所有ZServerEndpoint放到列表里 val serverEndpoints: List[ZServerEndpoint[Any, Any]] = List(helloEndpoint, healthEndpoint) // 关键步骤:提取每个端点的纯API定义 val pureEndpoints: List[Endpoint[_, _, _, _, _]] = serverEndpoints.map(_.endpoint) // 生成OpenAPI文档 val openApi = OpenAPIDocsInterpreter().toOpenAPI( pureEndpoints, title = "我的ZIO Tapir API", version = "1.0.0" ) // 如果需要转换成YAML格式(常见的API文档格式) val openApiYaml: String = openApi.toYaml
这样处理后,OpenAPIDocsInterpreter就能正常处理这些纯端点定义,再也不会出现类转换的错误了。本质上就是把带有服务端逻辑的端点剥离成纯API描述,这也是Tapir设计时的分层思路——API定义和服务端实现是分开的,文档生成只需要前者。
备注:内容来源于stack exchange,提问作者Bender Rodriguez
相关产品推荐
相关产品推荐

