如何用Swagger基于自定义API类生成OpenAPI文档?
问题与解答
问题描述
我有一个代表API的类,代码如下:
[ApiEndpoint( Name, SignatureBase )] [Title] [Description] abstract public class ReportsAPI { public const string Name = "reports"; public const string SignatureBase = "/system/report"; static public readonly EndpointSignature Signature = SignatureBase; public class TitleAttribute : TitleLocalizedAttribute { public TitleAttribute() : base(typeof(Resources.ReportsAPITitle)) { } } public class DescriptionAttribute : DescriptionLocalizedAttribute { public DescriptionAttribute() : base(typeof(Resources.ReportsAPIDescription)) { } } [ApiCommands] abstract public class Commands { [ApiArgument(typeof(ReportTemplatesListArguments), isOptional: true)] [ApiReturn(typeof(ReportTemplatesListResponse))] [Title] [Description] public const string ReportTemplatesList = "report_templates_list"; [ApiArgument(typeof(ReportTemplatesGetArguments))] [ApiReturn(typeof(ReportTemplatesGetResponse))] [Title] [Description] public const string ReportTemplatesGet = "report_templates_get"; [ApiArgument(typeof(ReportsGenerateArguments))] [ApiReturn(typeof(ReportsGenerateResponse))] [Title] [Description] public const string ReportsGenerate = "reports_generate"; } [ApiEvents] abstract public class Events { [ApiReturn(typeof(ReportGenerateStartedEvent))] [Title] [Description] [EventCategory(EventCategoryType.Audit)] [EventIsVerbalized] public const string ReportGenerateStarted = "report_generate_started"; } }
该类定义了API的命令、参数及返回值信息,我希望生成类似Swagger Editor样式的OpenAPI文档供他人使用,请问Swagger能否基于该类为我生成此类文档?
解答
Swagger本身无法直接识别你自定义的这些特性(比如[ApiEndpoint]、[ApiCommands]这类自定义标记),但可以通过自定义逻辑实现文档生成,具体步骤如下:
- 解析API类:利用反射遍历
ReportsAPI及其内部的Commands、Events类,提取特性中包含的所有信息,包括命令名称、参数类型、返回值类型、标题和描述等。 - 映射到OpenAPI规范:将提取到的信息转换为OpenAPI规范对应的结构,比如把每个命令对应成OpenAPI的
paths节点下的接口定义,参数对应parameters或requestBody,返回值对应responses,标题和描述对应summary和description字段。 - 生成OpenAPI文档:把映射好的结构序列化为JSON或YAML格式的文档,即可直接在Swagger Editor中打开使用。
如果你的项目基于.NET环境,还可以借助Swashbuckle.AspNetCore这类库的扩展能力,自定义文档过滤器来识别你的自定义特性,无需从零编写完整的解析逻辑,就能自动生成符合要求的OpenAPI文档。
内容的提问来源于stack exchange,提问作者Anthony
相关产品推荐
相关产品推荐

