AWS Serverless Application Model (SAM) 是一个用于部署和管理 Serverless 应用程序的开发框架。在 SAM 中,REST API 是通过 AWS API Gateway 和 Lambda 函数来实现的。下面是一个使用 SAM 配置 REST API 的示例:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyRestApi:
Type: AWS::Serverless::Api
Properties:
StageName: prod
DefinitionBody:
swagger: "2.0"
info:
title: "My REST API"
paths:
/hello:
get:
responses:
'200':
description: 'OK'
schema:
type: 'object'
properties:
message:
type: 'string'
x-amazon-apigateway-integration:
type: 'aws_proxy'
uri:
Fn::Sub: "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations"
httpMethod: 'POST'
passthroughBehavior: 'when_no_match'
cacheNamespace: 'hello'
cacheKeyParameters:
- 'method.request.path.proxy'
integrationResponses:
- statusCode: '200'
responseParameters:
method.response.header.Content-Type: "'application/json'"
responseTemplates:
application/json: |
#set($inputRoot = $input.path('$'))
{
"message": "Hello, $inputRoot.name!"
}
x-amazon-apigateway-gateway-responses:
DEFAULT_4XX:
responseTemplates:
application/json: |
#set($errorMessage = $input.path('$.errorMessage'))
{
"error": "$errorMessage"
}
responseParameters:
method.response.header.Content-Type: "'application/json'"
DependsOn: MyLambdaFunction
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: app.lambda_handler
Runtime: python3.9
Events:
HelloWorld:
Type: Api
Properties:
RestApiId: !Ref MyRestApi
Path: /hello
Method: GET
上面的示例使用了 AWS SAM 的模板语法来定义一个 REST API。在 MyRestApi 资源中,我们通过 DefinitionBody 属性来指定了 API 的定义。在这个示例中,我们定义了一个路径 /hello,该路径下的 GET 请求将会触发 MyLambdaFunction Lambda 函数的执行,并返回一个包含问候消息的 JSON 响应。
在 MyLambdaFunction 资源中,我们使用了 AWS::Serverless::Function 类型来定义了一个 Lambda 函数。这个函数的 Events 属性指定了它与 REST API 的关联关系。
以上是一个使用 AWS SAM 配置 REST API 的示例。您可以根据自己的需求进行修改和扩展。要部署这个 SAM 应用程序,请使用 AWS SAM CLI 命令 sam deploy。