Serverless Framework v2 API Gateway响应schema配置及旧文档插件替代咨询
Serverless Framework v2 响应Schema配置方案
原生响应Schema支持说明
Serverless Framework v2的AWS provider原生http事件配置,没有提供与请求Schema对称的响应Schema直接配置项,要实现不同状态码的响应Schema绑定,可参考以下两种成熟方案:
方案1:使用serverless-auto-swagger插件
该插件完美适配Serverless v2及以上版本,支持同时定义请求Schema和多状态码响应Schema,部署时会自动为API Gateway绑定对应响应模型,同时自动生成Swagger接口文档,基础配置示例如下:
custom: autoswagger: generateSwaggerOnDeploy: true functions: create: handler: posts.create events: - http: path: posts/create method: post request: schemas: application/json: schema: ${file(create_request.json)} name: PostCreateModel description: 'Validation model for Creating Posts' # 新增响应配置 response: 200: description: '帖子创建成功' bodySchema: ${file(create_200_response.json)} 400: description: '请求参数非法' bodySchema: ${file(create_400_response.json)}
方案2:通过CloudFormation扩展原生配置
如果不想引入第三方插件,可直接在serverless.yml的resources字段中补充API Gateway的响应模型、方法响应配置,会和Serverless自动生成的API资源自动关联生效,示例配置如下:
resources: Resources: # 定义200状态码响应模型 PostCreate200ResponseModel: Type: AWS::ApiGateway::Model Properties: RestApiId: { Ref: ApiGatewayRestApi } ContentType: application/json Name: PostCreate200Response Schema: ${file(create_200_response.json)} # 定义400状态码响应模型 PostCreate400ResponseModel: Type: AWS::ApiGateway::Model Properties: RestApiId: { Ref: ApiGatewayRestApi } ContentType: application/json Name: PostCreate400Response Schema: ${file(create_400_response.json)} # 绑定响应模型到对应接口方法 ApiGatewayMethodPostscreatePost: Type: AWS::ApiGateway::Method Properties: MethodResponses: - StatusCode: 200 ResponseModels: application/json: { Ref: PostCreate200ResponseModel } - StatusCode: 400 ResponseModels: application/json: { Ref: PostCreate400ResponseModel }
注:上述配置中的
ApiGatewayMethodPostscreatePost为Serverless自动生成的接口方法逻辑ID,命名规则为ApiGatewayMethod<驼峰化的接口路径><驼峰化的请求方法>,可在部署后的CloudFormation栈资源列表中确认准确ID。
内容的提问来源于stack exchange,提问作者gdogaru
相关产品推荐
相关产品推荐

