AWS API Gateway與AWS Lambda代理集成構建REST API

項目地址

https://github.com/JessicaWin/aws

創建Lambda Handler

創建父模塊

使用idea創建一個maven工程: File->New->Project

在左側菜單欄中選擇Maven,點擊Next:

輸入groupId和artifactId,點擊Next:

最終點擊finish創建完成.

修改父模塊的pom文件,引入aws lambda, log, json相關的jar包管理:

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.amazonaws</groupId>
                <artifactId>aws-lambda-java-core</artifactId>
                <version>1.2.0</version>
            </dependency>
            <dependency>
                <groupId>com.amazonaws</groupId>
                <artifactId>aws-lambda-java-events</artifactId>
                <version>3.1.0</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.7.26</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.7.26</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.11.0</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.11.0</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

創建子模塊

首先選中aws project,然後Intellij -> File -> New Module,在彈出的對話框中選擇Maven, 使用默認配置,然後Next進入下一步配置。

配置項目的group和artifact等信息(可以根據自己需要進行配置),點擊Next進入下一步配置。

  • Grouop: com.jessica
  • Artifact:aws-lambda

設置module name爲aws-lambda,點擊finish完成創建.

修改子模塊的pom文件,引入aws lambda, log, json相關的jar包:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>aws</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>aws-lambda</artifactId>
    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-lambda-java-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-lambda-java-events</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <configuration>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <!-- remove version from package name -->
                            <finalName>${project.artifactId}</finalName>
                            <createDependencyReducedPom>false</createDependencyReducedPom>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

在子模塊的src/main/resources目錄下添加日誌配置文件log4j.properties

log4j.rootLogger=DEBUG,system.out
log4j.appender.system.out=org.apache.log4j.ConsoleAppender
log4j.appender.system.out.layout=org.apache.log4j.PatternLayout
log4j.appender.system.out.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

在子模塊中創建lambda函數的request和response

GreetingRequestVo.java

package com.jessica.aws.lambda;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GreetingRequestVo {
    private String name;
    private String time;
    private String city;
    private String day;
}

GreetingResponseVo.java

package com.jessica.aws.lambda;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GreetingResponseVo {
    private String greeting;
}

在子模塊中創建一個Lambda Handler

LambdaProxyHandler.java

package com.jessica.aws.lambda;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LambdaProxyHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(LambdaProxyHandler.class);
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {
        GreetingRequestVo greetingRequestVo = null;
        try {
            LOGGER.info("api gateway event is: " + event);
            String requestBody = event.getBody();
            LOGGER.info("api requestBody: " + event);
            greetingRequestVo = mapper.readValue(requestBody, GreetingRequestVo.class);
            String greeting = String.format("Good %s, %s of %s.[ Happy %s!]",
                    greetingRequestVo.getTime(), greetingRequestVo.getName(), greetingRequestVo.getCity(), greetingRequestVo.getDay());
            LOGGER.info("name is " + greetingRequestVo.getName());
            GreetingResponseVo response = GreetingResponseVo.builder().greeting(greeting).build();
            String responseBody = mapper.writeValueAsString(response);
            APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
            responseEvent.setBody(responseBody);
            responseEvent.setStatusCode(200);
            return responseEvent;
        } catch (JsonProcessingException e) {
            APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
            responseEvent.setStatusCode(500);
            return responseEvent;
        }
    }
}

創建config.yml文件

在aws-lambda子模塊中創建config.yml文件,該文件主要用於配置當前service的通用參數設置,同時用於作爲lambda函數的環境變量

# Variant of each developer
variant: jessica

stage: develop

# The region you will deploy your lambda to
region: ap-southeast-1

# The bucket your upload your lambda resource(Including jar) to
deploymentBucket: ${self:provider.stage}-social-network-deploy

# AWS Account ID
ACCOUNT_ID:
  Ref: 'AWS::AccountId'

versionFunctions: false

創建serverless.yml部署文件

serverless.yml文件用於創建lambda函數, apigateway的相關資源(AWS::ApiGateway::RestApi, AWS::ApiGateway::Resource,  AWS::ApiGateway::Method),lambda函數的調用條件,權限等.

自動創建API Gateway REST API資源

在serverless.yml中配置lambda函數,在函數部署時會自動爲該函數創建LogGroup,如果指定了http類型的event,則在部署時會自動爲該函數創建event對應的apigateway的相關資源(AWS::ApiGateway::RestApi, AWS::ApiGateway::Resource,  AWS::ApiGateway::Method),以及apigateway event調用lambda函數的權限.

部署文件

service: aws-lambda
frameworkVersion: ">=1.2.0 <2.0.0"
plugins:
  - serverless-pseudo-parameters

custom:
  configFile: ${file(config.yml)}

provider:
  name: aws
  stage: ${self:custom.configFile.stage}
  variant: ${self:custom.configFile.variant}
  runtime: java8
  region: ${self:custom.configFile.region}
  timeout: 30 # The default is 6 seconds. Note: API Gateway current maximum is 30 seconds
  memorySize: 1024 # Overwrite the default memory size. Default is 1024. Increase by 64.
  deploymentBucket: ${self:custom.configFile.deploymentBucket}
  environment: ${file(config.yml)}
  stackName: ${self:provider.stage}-${self:provider.variant}-${self:service}
  versionFunctions: ${self:custom.configFile.versionFunctions}

package:
  artifact: target/aws-lambda.jar

functions:
  LambdaProxyHandler:
    # name must have length less than or equal to 64
    name: ${self:provider.stage}-${self:provider.variant}-LambdaProxyHandler
    handler: com.jessica.aws.lambda.LambdaProxyHandler
    role: arn:aws:iam::#{AWS::AccountId}:role/AdminRole
    events:
      - http:
          path: /hello
          method: POST

部署

$ sls deploy -v
Serverless: Packaging service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (4.7 MB)...
Serverless: Validating template...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
CloudFormation - CREATE_IN_PROGRESS - AWS::CloudFormation::Stack - develop-jessica-aws-lambda
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - LambdaProxyHandlerLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::RestApi - ApiGatewayRestApi
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - LambdaProxyHandlerLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::RestApi - ApiGatewayRestApi
CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::RestApi - ApiGatewayRestApi
CloudFormation - CREATE_COMPLETE - AWS::Logs::LogGroup - LambdaProxyHandlerLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Resource - ApiGatewayResourceHello
CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Function - LambdaProxyHandlerLambdaFunction
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Resource - ApiGatewayResourceHello
CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Resource - ApiGatewayResourceHello
CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Function - LambdaProxyHandlerLambdaFunction
CloudFormation - CREATE_COMPLETE - AWS::Lambda::Function - LambdaProxyHandlerLambdaFunction
CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Permission - LambdaProxyHandlerLambdaPermissionApiGateway
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Method - ApiGatewayMethodHelloPost
CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Permission - LambdaProxyHandlerLambdaPermissionApiGateway
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Method - ApiGatewayMethodHelloPost
CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Method - ApiGatewayMethodHelloPost
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Deployment - ApiGatewayDeployment1592312567124
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Deployment - ApiGatewayDeployment1592312567124
CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Deployment - ApiGatewayDeployment1592312567124
CloudFormation - CREATE_COMPLETE - AWS::Lambda::Permission - LambdaProxyHandlerLambdaPermissionApiGateway
CloudFormation - CREATE_COMPLETE - AWS::CloudFormation::Stack - develop-jessica-aws-lambda
Serverless: Stack create finished...
Service Information
service: aws-lambda
stage: develop
region: ap-southeast-1
stack: develop-jessica-aws-lambda
api keys:
  None
endpoints:
  POST - https://********.execute-api.ap-southeast-1.amazonaws.com/develop/hello
functions:
  LambdaProxyHandler: aws-lambda-develop-LambdaProxyHandler
layers:
  None

Stack Outputs
ServiceEndpoint: https://********.execute-api.ap-southeast-1.amazonaws.com/develop
ServerlessDeploymentBucketName: develop-social-network-deploy

通過log可以看出,lambda函數部署時一共創建了7個資源:

  • AWS::ApiGateway::RestApi
  • AWS::Logs::LogGroup
  • AWS::ApiGateway::Resource
  • AWS::Lambda::Function
  • AWS::ApiGateway::Method
  • AWS::Lambda::Permission
  • AWS::ApiGateway::Deployment

測試

打開apigateway的頁面:https://ap-southeast-1.console.aws.amazon.com/apigateway/main/apis?region=ap-southeast-1

在api列表中可以找到剛部署的名爲 develop-aws-lambda的api:

打開api頁面,可以看到api相關信息,點擊/hello下面的POST方法,可以看到hello api的完整信息:

擊點TEST可以進行測試,測試時輸入如下的request body:

{
    "name":"jesscia",
    "time":"21:00",
    "city":"shanghai",
    "day":"2020/06/10"
}

自定義API Gateway REST API資源

在aws-lambda的serverless.yml中只配置lambda函數,不指定event.

在aws-lambda的根目錄下創建一個api目錄,並在其中創建一個serverless.yml用於對apigateway的相關資源(AWS::ApiGateway::RestApi, AWS::ApiGateway::Resource,  AWS::ApiGateway::Method)以及調用lambda函數的權限進行配置.

lambda配置文件aws-lambda/serverless.yml

service: aws-apigateway-lambda
frameworkVersion: ">=1.2.0 <2.0.0"
plugins:
  - serverless-pseudo-parameters

custom:
  configFile: ${file(config.yml)}

provider:
  name: aws
  stage: ${self:custom.configFile.stage}
  variant: ${self:custom.configFile.variant}
  runtime: java8
  region: ${self:custom.configFile.region}
  timeout: 30 # The default is 6 seconds. Note: API Gateway current maximum is 30 seconds
  memorySize: 1024 # Overwrite the default memory size. Default is 1024. Increase by 64.
  deploymentBucket: ${self:custom.configFile.deploymentBucket}
  environment: ${file(config.yml)}
  stackName: ${self:provider.stage}-${self:provider.variant}-${self:service}
  versionFunctions: ${self:custom.configFile.versionFunctions}

package:
  artifact: target/aws-lambda.jar

functions:
  LambdaProxyHelloHandler:
    # name must have length less than or equal to 64
    name: ${self:provider.stage}-${self:provider.variant}-LambdaProxyHelloHandler
    handler: com.jessica.aws.lambda.LambdaProxyHandler
    role: arn:aws:iam::#{AWS::AccountId}:role/AdminRole

resources:
  Outputs:
    LambdaProxyHelloHandlerArn:
      Description: The ARN for the hello function
      Value:
        # the first param must be:  string.contact(functionId, LambdaFunction)
        Fn::GetAtt:
          - LambdaProxyHelloHandlerLambdaFunction
          - Arn
      Export:
        Name: ${self:provider.stage}-${self:provider.variant}-LambdaProxyHelloHandlerArn

apigateway配置文件aws-lambda/api/serverless.yml

service: aws-apigateway-api
frameworkVersion: ">=1.2.0 <2.0.0"
plugins:
  - serverless-pseudo-parameters

custom:
  configFile: ${file(../config.yml)}

provider:
  name: aws
  stage: ${self:custom.configFile.stage}
  variant: ${self:custom.configFile.variant}
  region: ${self:custom.configFile.region}
  deploymentBucket: ${self:custom.configFile.deploymentBucket}
  stackName: ${self:provider.stage}-${self:provider.variant}-${self:service}
  helloFunctionArn:
    Fn::ImportValue: ${self:provider.stage}-${self:provider.variant}-LambdaProxyHelloHandlerArn

resources:
  Resources:
    # api gateway root
    ApiGatewayRestApi:
      Type: AWS::ApiGateway::RestApi
      Properties:
        Name: ${self:provider.stage}_${self:provider.variant}_ApiGatewayRootRestApi
        EndpointConfiguration:
          Types:
            - REGIONAL

    # /hello
    ApiGatewayResourceHello:
      Type: AWS::ApiGateway::Resource
      Properties:
        RestApiId:
          Ref: ApiGatewayRestApi
        ParentId:
          Fn::GetAtt:
            - ApiGatewayRestApi
            - RootResourceId
        PathPart: hello

    RootMethod:
      Type: AWS::ApiGateway::Method
      Properties:
        ResourceId:
          Fn::GetAtt:
            - ApiGatewayRestApi
            - RootResourceId
        RestApiId:
          Ref: ApiGatewayRestApi
        HttpMethod: GET
        AuthorizationType: NONE
        MethodResponses:
          - StatusCode: 302
            ResponseParameters:
              method.response.header.Location: true
        Integration:
          Type: MOCK
          RequestTemplates:
            'application/json': '{"statusCode":200}'
          IntegrationResponses:
            - StatusCode: 302

    ApiGatewayMethodHelloPost:
      Type: AWS::ApiGateway::Method
      Properties:
        HttpMethod: POST
        RequestParameters: {}
        ResourceId:
          Ref: ApiGatewayResourceHello
        RestApiId:
          Ref: ApiGatewayRestApi
        ApiKeyRequired: false
        AuthorizationType: NONE
        Integration:
          IntegrationHttpMethod: POST
          Type: AWS_PROXY
          Uri:
            # Fn::Join object requires two parameters, (1) a string delimiter and (2) a list of strings to be joined
            Fn::Join:
              - ''
              - - 'arn:'
                - Ref: 'AWS::Partition'
                - ':apigateway:'
                - Ref: 'AWS::Region'
                - ':lambda:path/2015-03-31/functions/'
                - ${self:provider.helloFunctionArn}
                - /invocations
        MethodResponses: []
    LambdaProxyHandlerLambdaPermissionApiGateway:
      Type: AWS::Lambda::Permission
      Properties:
        FunctionName: ${self:provider.helloFunctionArn}
        Action: lambda:InvokeFunction
        Principal: apigateway.amazonaws.com
        SourceArn:
          Fn::Join:
            - ''
            - - 'arn:'
              - Ref: 'AWS::Partition'
              - ':execute-api:'
              - Ref: 'AWS::Region'
              - ':'
              - Ref: 'AWS::AccountId'
              - ':'
              - Ref: ApiGatewayRestApi
              - /*/*
  Outputs:
    ApiGatewayRestApiId:
      Value:
        Ref: ApiGatewayRestApi
      Export:
        Name: ${self:provider.stage}-${self:provider.variant}-ApiGatewayRootRestApiId
    ApiGatewayRootResourceId:
      Value:
        Fn::GetAtt:
          - ApiGatewayRestApi
          - RootResourceId
      Export:
        Name: ${self:provider.stage}-${self:provider.variant}-ApiGatewayRootResourceId
    ApiGatewayResourceIdHello:
      Value:
        Ref: ApiGatewayResourceHello
      Export:
        Name: ${self:provider.stage}-${self:provider.variant}-ApiGatewayResourceId-hello
    ServiceEndpoint:
      Description: 'URL of the service endpoint'
      Value:
        Fn::Join:
          - ''
          - - 'https://'
            - Ref: ApiGatewayRestApi
            - '.execute-api.'
            - Ref: 'AWS::Region'
            - '.'
            - Ref: 'AWS::URLSuffix'
            - '/'
            - ${self:provider.stage}

部署lambda函數

$ $ sls deploy -v
Serverless: Packaging service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (4.7 MB)...
Serverless: Validating template...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
CloudFormation - CREATE_IN_PROGRESS - AWS::CloudFormation::Stack - develop-jessica-aws-apigateway-lambda
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - LambdaProxyHelloHandlerLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - LambdaProxyHelloHandlerLogGroup
CloudFormation - CREATE_COMPLETE - AWS::Logs::LogGroup - LambdaProxyHelloHandlerLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Function - LambdaProxyHelloHandlerLambdaFunction
CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Function - LambdaProxyHelloHandlerLambdaFunction
CloudFormation - CREATE_COMPLETE - AWS::Lambda::Function - LambdaProxyHelloHandlerLambdaFunction
CloudFormation - CREATE_COMPLETE - AWS::CloudFormation::Stack - develop-jessica-aws-apigateway-lambda
Serverless: Stack create finished...
Service Information
service: aws-apigateway-lambda
stage: develop
region: ap-southeast-1
stack: develop-jessica-aws-apigateway-lambda
api keys:
  None
endpoints:
  None
functions:
  LambdaProxyHelloHandler: aws-apigateway-lambda-develop-LambdaProxyHelloHandler
layers:
  None

Stack Outputs
LambdaProxyHelloHandlerArn: arn:aws:lambda:ap-southeast-1:*********:function:develop-jessica-LambdaProxyHelloHandler
ServerlessDeploymentBucketName: develop-social-network-deploy

通過log可以看出,lambda函數部署時一共創建了2個資源:

  • AWS::Logs::LogGroup
  • AWS::Lambda::Function

部署apigateway

$  sls deploy -v
Serverless: Packaging service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Validating template...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
CloudFormation - CREATE_IN_PROGRESS - AWS::CloudFormation::Stack - develop-jessica-aws-apigateway-api
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::RestApi - ApiGatewayRestApi
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::RestApi - ApiGatewayRestApi
CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::RestApi - ApiGatewayRestApi
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Resource - ApiGatewayResourceHello
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Method - RootMethod
CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Permission - LambdaProxyHandlerLambdaPermissionApiGateway
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Resource - ApiGatewayResourceHello
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Method - RootMethod
CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Permission - LambdaProxyHandlerLambdaPermissionApiGateway
CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Resource - ApiGatewayResourceHello
CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Method - RootMethod
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Method - ApiGatewayMethodHelloPost
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::Method - ApiGatewayMethodHelloPost
CloudFormation - CREATE_COMPLETE - AWS::ApiGateway::Method - ApiGatewayMethodHelloPost
CloudFormation - CREATE_COMPLETE - AWS::Lambda::Permission - LambdaProxyHandlerLambdaPermissionApiGateway
CloudFormation - CREATE_COMPLETE - AWS::CloudFormation::Stack - develop-jessica-aws-apigateway-api
Serverless: Stack create finished...
Service Information
service: aws-apigateway-api
stage: develop
region: ap-southeast-1
stack: develop-jessica-aws-apigateway-api
api keys:
  None
endpoints:
functions:
  None
layers:
  None

Stack Outputs
ApiGatewayRestApiId: ******
ApiGatewayRootResourceId: ******
ApiGatewayResourceIdHello: ******
ServiceEndpoint: https://******.execute-api.ap-southeast-1.amazonaws.com/develop
ServerlessDeploymentBucketName: develop-social-network-deploy

通過log可以看出,lambda函數部署時一共創建了5個資源:

  • AWS::ApiGateway::RestApi
  • AWS::ApiGateway::Resource
  • AWS::ApiGateway::Method - RootMethod
  • AWS::ApiGateway::Method - ApiGatewayMethodHelloPost
  • AWS::Lambda::Permission

測試

打開apigateway的頁面:https://ap-southeast-1.console.aws.amazon.com/apigateway/main/apis?region=ap-southeast-1

在api列表中可以找到剛部署的名爲 develop_jessica_ApiGatewayRootRestApi的api:

打開api頁面,可以看到api相關信息,點擊/hello下面的POST方法,可以看到hello api的完整信息:

 

點擊 TEST可以對api進行測試,輸入圖示的request body進行測試,可以得到正確的返回結果:

{
    "name":"jesscia",
    "time":"21:00",
    "city":"shanghai",
    "day":"2020/06/10"
}

 

參考

https://www.serverless.com/framework/docs/providers/aws/guide/functions/

https://www.serverless.com/framework/docs/providers/aws/events/apigateway/#lambda-integration

https://www.gorillastack.com/news/splitting-your-serverless-framework-api-on-aws/

https://docs.aws.amazon.com/zh_cn/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-join.html

https://docs.aws.amazon.com/zh_cn/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html

https://docs.aws.amazon.com/zh_cn/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章