要将API网关直接连接到SNS并使用SAM(Serverless Application Model),您可以按照以下步骤进行操作:
Resources:
MyApiGateway:
Type: AWS::Serverless::Api
Properties:
StageName: prod
DefinitionBody:
swagger: "2.0"
info:
title: "My API"
paths:
/my-endpoint:
post:
x-amazon-apigateway-integration:
type: aws
uri: "arn:aws:apigateway:us-east-1:sns:path//"
httpMethod: POST
credentials: !GetAtt MyApiGatewayRole.Arn
requestParameters:
integration.request.header.Content-Type: "'application/json'"
passthroughBehavior: "when_no_match"
responses:
default:
statusCode: "200"
x-amazon-apigateway-binary-media-types:
- "multipart/form-data"
x-amazon-apigateway-request-validators:
all:
validateRequestBody: true
validateRequestParameters: true
MyApiGatewayRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- apigateway.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: APIGatewayLambdaInvokePolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- lambda:InvokeFunction
Resource: "*"
MySNSTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: "My SNS Topic"
MySNSSubscription:
Type: AWS::SNS::Subscription
Properties:
Endpoint: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations"
Protocol: "lambda"
TopicArn: !Ref MySNSTopic
在模板中,我们定义了一个API网关(MyApiGateway)并将其与SNS主题(MySNSTopic)关联。此外,我们还定义了一个IAM角色(MyApiGatewayRole),用于授权API网关调用Lambda函数。我们还定义了一个SNS订阅(MySNSSubscription),将API网关的请求转发到Lambda函数。
接下来,您需要在SAM模板中定义一个Lambda函数,用于处理API网关的请求。以下是一个示例:
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: my-lambda-function/
Handler: app.lambda_handler
Runtime: python3.8
Events:
MyApiGatewayEvent:
Type: Api
Properties:
RestApiId: !Ref MyApiGateway
Path: /my-endpoint
Method: post
在此示例中,我们定义了一个Lambda函数(MyLambdaFunction),该函数位于my-lambda-function/
目录下,并使用Python 3.8运行时。我们还将该函数与API网关的/my-endpoint
路径和POST方法关联起来。
最后,您可以使用AWS CLI命令部署SAM应用程序:
$ aws cloudformation package --template-file template.yaml --s3-bucket my-bucket --output-template-file packaged-template.yaml
$ aws cloudformation deploy --template-file packaged-template.yaml --stack-name my-stack --capabilities CAPABILITY_IAM
在此示例中,我们将模板打包并上传到名为my-bucket
的S3存储桶中。然后,我们使用CloudFormation部署应用程序,并为其提供一个名称(my-stack
)。请确保将--s3-bucket
参数替换为您自己的存储桶名称。
通过按照上述步骤操作,您就可以将API网关直接连接到SNS并使用
上一篇:API网关支持泛域名绑定
下一篇:API网关只允许内网访问