REST API openapi 规范 AWS API Gateway 与 serverless.com 框架的集成
Posted
技术标签:
【中文标题】REST API openapi 规范 AWS API Gateway 与 serverless.com 框架的集成【英文标题】:REST API openapi spec AWS API Gateway integration with the serverless.com framework 【发布时间】:2020-04-17 06:48:27 【问题描述】:我正在使用 AWS 作为提供商试用 serverless.com
。我想用 API Gateway 和 Lambda 做一个简单的 hello world 应用程序,我从 openapi 规范发布 API。
我在forum post 中看到我需要在 serverless.yml 文件中将规范声明为资源,但是这样做时我在执行sls deploy
时收到以下错误:
我认为我基本上是正确的,除了在 openapi 规范文件中我不知道如何正确引用我正在创建的 API 的 URI。这是我收到错误的原因吗?
Serverless Error ---------------------------------------
An error occurred: ApiGatewayRestApi - Errors found during import:
Unable to put integration on 'GET' for resource at path '/hello': Invalid function ARN or invalid uri (Service: AmazonApiGateway; Status Code: 400; Error Code: BadRequestException; Request ID: ...).
Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues
Issues: forum.serverless.com
Your Environment Information ---------------------------
Operating System: darwin
Node Version: 12.16.2
Framework Version: 1.67.3
Plugin Version: 3.6.6
SDK Version: 2.3.0
Components Version: 2.29.3
我正在尝试我能想到的最简单的例子:
# serverless.yml
service: accounts-api
provider:
name: aws
apiName: accounts
runtime: nodejs12.x
stage: dev
region: ap-southeast-2
functions:
hello:
handler: functions/handler.hello
events:
- http:
path: /accounts
method: GET
# The resources attribute will be sent directly to CloudFormation in raw format
resources:
Resources:
ApiGatewayRestApi:
Type: 'AWS::ApiGateway::RestApi'
Properties:
Name: $self:provider.apiName-$self:provider.stage
Body:
$file(specs/simple-spec.yml)
ApiGatewayDeployment:
Type: AWS::ApiGateway::Deployment
Properties:
RestApiId:
Ref: ApiGatewayRestApi
StageName: $self:provider.stage
以及 openapi 规范:
openapi: 3.0.0
info:
version: 1.0.0
title: Hello API
description: Returns a hello world message
paths:
/hello:
get:
description: Returns a hello world message
responses:
'200':
description: Successful response
security:
- api_key: []
x-amazon-apigateway-auth:
type: none
x-amazon-apigateway-integration:
x-amazon-apigateway-integration:
type: aws_proxy
uri: arn:aws:apigateway:ap-southeast-2:lambda:path/2015-03-31/functions/arn:aws:lambda:ap-southeast-2:idAccount:function:hello/invocations
httpMethod: GET
passthroughBehavior: when_no_templates
payloadFormatVersion: 1.0
【问题讨论】:
似乎问题在于将 OpenAPI 规范中的 URI 属性中的idAccount
替换为刚刚创建的 Lambda 函数 ARN。现在,我如何动态获取该 ARN?
【参考方案1】:
在您的 serverless.yml 文件中,您在 region: ap-southeast-2
中创建 lambda,但在 openapi 定义 (uri: arn:aws:apigateway:ap-northeast-1:lambda...
) 中,您引用的是不同的区域:ap-northeast-1
【讨论】:
谢谢。我注意到我的帖子中有错字,但不幸的是,这还没有解决我的问题。 :(以上是关于REST API openapi 规范 AWS API Gateway 与 serverless.com 框架的集成的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 OpenAPI 为 AWS API Gateway 配置 CORS?
API 入门 (27) 使用 OpenAPI 描述 REST API——资源和操作