如何为Lambda代理集成的API Gateway补充元数据以生成可用API文档?
给API Gateway代理资源补全文档信息的实用方案
我最近用SAM搭了一套API Gateway+Lambda的服务,配置了Lambda授权器,还有个用{proxy+}的代理资源,但自动生成的Swagger文档里,代理路径的请求模型、响应模型甚至参数描述都空空如也,完全没法用来生成客户端代码或者做集成测试。折腾了一番后,总结出几个可行的补全方法:
方法1:在SAM模板里嵌入完整的OpenAPI定义
这是最灵活、最靠谱的方式——直接在AWS::Serverless::Api的DefinitionBody里写完整的OpenAPI规范,把代理资源的所有细节都定义清楚,不用依赖SAM自动生成的简陋文档。
比如修改后的SAM模板片段:
MyApi: Type: AWS::Serverless::Api Properties: StageName: !Ref EnvType Auth: DefaultAuthorizer: LambdaTokenAuthorizer Authorizers: LambdaTokenAuthorizer: FunctionArn: !GetAtt AuthorizerLambda.Arn DefinitionBody: swagger: "2.0" info: version: "1.0" title: !Sub "${AWS::StackName}-${EnvType}" host: !Sub "${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com" basePath: !Ref EnvType schemes: - https paths: /MyResource/{proxy+}: post: parameters: - name: proxy in: path required: true type: string description: 代理路径的具体子资源(比如/MyResource/user/123里的user/123) - name: Authorization in: header required: true type: string requestBody: required: true content: application/json: schema: type: object properties: userId: type: string data: type: object required: [userId] responses: '200': description: 请求成功的响应 content: application/json: schema: type: object properties: status: type: string result: type: object security: - LambdaTokenAuthorizer: [] securityDefinitions: LambdaTokenAuthorizer: type: "apiKey" name: "Authorization" in: "header" x-amazon-apigateway-authtype: "custom"
这样部署后,API Gateway生成的文档就会包含完整的代理路径说明、请求/响应模型,完全满足生成客户端代码或集成测试的需求。
方法2:通过SAM的API事件配置补充基础信息
如果不想写完整的OpenAPI,也可以在Lambda的Events配置里添加部分细节,比如请求模型、参数要求和资源描述:
MyFunction: Type: 'AWS::Serverless::Function' # 其他函数配置... Events: MyEvent: Type: Api Properties: RestApiId: !Ref MyApi Path: "/MyResource/{proxy+}" Method: post RequestModels: application/json: MyRequestModel RequestParameters: method.request.path.proxy: true OperationName: MyProxyResourcePost Description: 处理/MyResource下所有POST类型的代理请求,proxy参数为具体子路径
同时还要在API的Models里定义对应的请求/响应模型:
MyApi: Type: AWS::Serverless::Api Properties: StageName: !Ref EnvType Auth: DefaultAuthorizer: LambdaTokenAuthorizer Authorizers: LambdaTokenAuthorizer: FunctionArn: !GetAtt AuthorizerLambda.Arn Models: MyRequestModel: type: object properties: userId: type: string data: type: object required: [userId] MyResponseModel: type: object properties: status: type: string result: type: object
不过这种方式的局限性比较大,没法完整定义响应模型的细节,适合只需要补充基础信息的场景。
方法3:部署后手动在控制台编辑(不推荐)
如果临时需要补全文档,也可以部署后登录API Gateway控制台,找到对应的代理资源,手动编辑请求参数、请求/响应模型和描述,然后导出更新后的Swagger文档。但这种方式完全脱离了代码管理,下次用SAM部署时会被覆盖,只适合临时应急。
总的来说,嵌入完整OpenAPI定义是最优解,既能保证文档的完整性,又能通过代码版本控制,方便后续维护和迭代。
内容的提问来源于stack exchange,提问作者grzegorz_p
相关产品推荐
相关产品推荐

