Create REST API type API Gateway using CFN

TOC

Create REST API type API Gateway using CloudFormation

The following page covers the HTTP API type API Gateway.

あわせて読みたい
Serverless apps using Lambda and API Gateway – HTTP API 【Creating Serverless Application with API Gateway and Lambda】 We will combine two resources to create a simple serverless web application. The first is Lam...

In this article, we will check how to build a REST API type API Gateway.

Environment

Diagram of create REST API type API Gateway.

Create an API Gateway and deploy Lambda on the backend.
When an HTTP request is received from a user, the API Gateway acts as the endpoint, calls a Lambda function instead, and returns the result of the function’s invocation to the user.
The API Gateway is created as a REST API type.

The runtime environment for the Lambda function is Python 3.8.

CloudFormation template files

The above configuration is built using CloudFormation.
The CloudFormation template is located at the following URL

https://github.com/awstut-an-r/awstut-fa/tree/main/052

Explanation of key points of template files

To create an API Gateway with Lambda backend, prepare the following 6 resources.

  1. API Gateway itself
  2. Resource
  3. Method
  4. Integration
  5. Deployment
  6. Stage

The next thing to check is the version of API Gateway.
Broadly speaking, there are two versions of API Gateway.
One is the REST API version and the other is the HTTP or Websocket API version.

In CloudFormation, both versions are separated as resources.
For example, when defining a REST API type API Gateway itself, the Type property is “AWS::ApiGateway::RestApi”.
Next, when defining the REST API type API Gateway itself, the Type property is “AWS::ApiGatewayV2::Api”.

API Gateway itself

Resources:
  RestApi:
    Type: AWS::ApiGateway::RestApi
    Properties:
      EndpointConfiguration:
        Types:
          - EDGE
      Name: !Ref Prefix
Code language: YAML (yaml)

The point is to specify the API endpoint type for the REST API.
The REST API has three API endpoint types.

The API endpoint type can be edge-optimized, regional, or private, depending on where the majority of your API traffic originates from.

Choose an endpoint type to set up for an API Gateway API

By default, the edge-optimized API endpoint is selected, so we’ll specify this one.
Incidentally, this API endpoint type is unique in that it is delivered via CloudFront.

An edge-optimized API endpoint is best for geographically distributed clients. API requests are routed to the nearest CloudFront Point of Presence (POP). This is the default endpoint type for API Gateway REST APIs.

Choose an endpoint type to set up for an API Gateway API

This means that if you choose this API endpoint, it will be delivered via CloudFront by default, without the user having to put CloudFront in front of the API Gateway themselves.

Resource

AWS officially describes resources as follows

Each API resource can expose one or more API methods that have unique HTTP verbs supported by API Gateway.

Amazon API Gateway concepts

In other words, an API Gateway resource is equivalent to a portion of the PATH in the API endpoint URL you create.

Resources:
  Resource:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt RestApi.RootResourceId
      PathPart: !Sub "${Prefix}-resource"
      RestApiId: !Ref RestApi
Code language: YAML (yaml)

There are two key points.

The first is the PathPart property.
As mentioned earlier, an API Gateway resource corresponds to a string that constitutes the URL of an API endpoint.
In this case, the built-in function Fn::Sub is used to specify “fa-052-resource” for this property, and this value is the following part of the URL.

https://[api-endpoint]/[stage-name]/[resource-name]/

The second point is the ParentId property.
This property specifies the parent resource of the API Gateway resource to be created.
This is because API Gateway resources are a tree structure based on a root resource.

API resources are organized in a resource tree according to the application logic.

Amazon API Gateway concepts

In this case, the resources are tied directly under the root resource.
We use the built-in function Fn::GetAtt to get the ID of the root resource from the API Gateway itself and set it to this property.

Method and Integration

The methods are as quoted above.
That is, they correspond to HTTP methods such as GET and POST.

Resources:
  Method:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizationType: NONE
      HttpMethod: GET
      Integration:
        ConnectionType: INTERNET
        Credentials: !GetAtt ApiGatewayRole.Arn
        IntegrationHttpMethod: POST
        Type: AWS_PROXY
        Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${FunctionArn}/invocations"
      ResourceId: !Ref Resource
      RestApiId: !Ref RestApi
Code language: YAML (yaml)

There are two points.

The first is the HttpMethod property.
This property allows you to specify the HTTP method, in this case “GET”.
In this configuration, this property is used in combination with the ResourceId property to define the behavior when the API endpoint /fa-052-resource/ is accessed with the GET method.

The second point is integration.
The AWS official explanation of integration is as follows

After setting up an API method, you must integrate it with an endpoint in the backend. A backend endpoint is also referred to as an integration endpoint and can be a Lambda function, an HTTP webpage, or an AWS service action.

Setting up REST API integrations

Integration is the middleman between the API Gateway and the backend resources.
In this configuration, when a user accesses the API Gateway, it invokes a backend Lambda function and returns the results to the API Gateway.

Integration is set inside the Integration property.

The ConnectionType property sets the network type of the integration endpoint.
Specify “VPC_LINK” if you want to create an API Gateway type (private API endpoint) that can only be accessed from within a specific VPC, or “INTERNET” for other uses.
The latter is used in this case.

The Credentials property specifies the IAM role to be associated with API Gateway.
In this case, the following IAM roles are specified.

Resources:
  ApiGatewayRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service:
                - apigateway.amazonaws.com
      Policies:
        - PolicyName: !Sub "${Prefix}-InvokeFunctionPolicy"
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - lambda:InvokeFunction
                Resource:
                  - !Ref FunctionArn
Code language: YAML (yaml)

The contents authorize API Gateway to invoke a backend Lambda function.

Three properties (IntegrationHttpMethod, Type, and Uri) specify the Lambda function as the backend.
The official AWS description of how to specify a Lambda function as the backend is as follows

You can integrate an API method with a Lambda function using Lambda proxy integration or Lambda non-proxy (custom) integration.

In Lambda proxy integration, the required setup is simple. Set the integration’s HTTP method to POST, the integration endpoint URI to the ARN of the Lambda function invocation action of a specific Lambda function, and grant API Gateway permission to call the Lambda function on your behalf.

Set up Lambda integrations in API Gateway

This time we will follow the quote above and use the Lambda proxy integration.
Set three properties as quoted.
Specify “POST” for the IntegrationHttpMethod property, “AWS_PROXY” meaning Lambda proxy integration for the Type property, and the URL meaning the Lambda function to execute for the Uri property.

Deployment

AWS officially describes deployment as follows

In API Gateway, a REST API deployment is represented by a Deployment resource. It’s similar to an executable of an API that is represented by a RestApi resource.

For the client to call your API, you must create a deployment and associate a stage with it.

Deploy a REST API in API Gateway
Resources:
  Deployment:
    Type: AWS::ApiGateway::Deployment
    DependsOn:
      - Method
    Properties:
      RestApiId: !Ref RestApiCode language: CSS (css)

No special configuration is required.
Simply set the ID of the API Gateway itself in the RestApiId property.

Stage

AWS officially describes stages as follows

A logical reference to a lifecycle state of your API (for example, ‘dev’, ‘prod’, ‘beta’, ‘v2’).

Amazon API Gateway concepts

In other words, the stage corresponds to the part of the PATH in the API endpoint URL you are creating.

Resources:
  Stage:
    Type: AWS::ApiGateway::Stage
    Properties:
      DeploymentId: !Ref Deployment
      RestApiId: !Ref RestApi
      StageName: !Sub "${Prefix}-stage"
Code language: YAML (yaml)

Specify the ID of the deployment in the DeploymentId property.
This associates the deployment with a stage.

The StageName property is the key point.
As mentioned earlier, the stage corresponds to the string that makes up the URL of the API endpoint.
In this case, we will use the built-in function Fn::Sub to specify “fa-052-stage” for this property, which is the following part of the URL.

https://[api-endpoint]/[stage-name]/[resource-name]/

(Reference) Lambda function

Resources:
  Function:
    Type: AWS::Lambda::Function
    Properties:
      Architectures:
        - !Ref Architecture
      Code:
        ZipFile: |
          import json

          def lambda_handler(event, context):
            return {
              'statusCode': 200,
              'body': json.dumps('Hello form Awstut !')
            }
      FunctionName: !Sub "${Prefix}-function"
      Handler: !Ref Handler
      Runtime: !Ref Runtime
      Role: !GetAtt FunctionRole.Arn
Code language: YAML (yaml)

No special configuration is required.
When executed, it simply returns “Hello form Awstut !” when executed.

Architecting

We will use CloudFormation to build this environment and check the actual behavior.

Create CloudFormation stacks and check resources in stacks

Create a CloudFormation stack.
For information on how to create stacks and check each stack, please refer to the following page

あわせて読みたい
CloudFormation’s nested stack 【How to build an environment with a nested CloudFormation stack】 Examine nested stacks in CloudFormation. CloudFormation allows you to nest stacks. Nested ...

After checking the resources in each stack, information on the main resources created this time is as follows

  • API Gateway name: fa-052
  • API Gateway endpoint: https://ee9xq1xttd.execute-api.ap-northeast-1.amazonaws.com/
  • API Gateway stage name: fa-052-stage
  • API Gateway resource name: fa-052-resource
  • Lambda function running on the backend: fa-052-function

Also check the API Gateway from the AWS Management Console.

REST API type API Gateway

An Edge-optimized REST API type has been created.

Check the resource and method contents.

Resources, Method and Integration of REST API.

The newly created “fa-052-resource” is located directly under the root resource (“/”).
GET is provided as a method for this resource.
Looking at the content defined in GET, we can see that the Lambda function “fa-052-function” is related to the Lambda function through the Lambda proxy integration.

Next, we check the stage and deployment.

Stage and Endpoint of REST API.

We can see that a stage named “fa-052-stage” has been created and successfully deployed.

Checking Action

Now that everything is ready, access the API Gateway endpoint.
The URL to be accessed this time is determined by combining the following four types of information.

  • Endpoint: ee9xq1xttd.execute-api.ap-northeast-1.amazonaws.com
  • Stage name: fa-052-stage
  • Resource name: fa-052-resource
  • HTTP method: GET

In other words, the following

GET https://ee9xq1xttd.execute-api.ap-northeast-1.amazonaws.com/fa-052-stage/fa-052-resource

Actually access.

The result of invoking REST API.

The string was returned successfully.
By accessing the API endpoint, the user executes a Lambda function through integration and the result of the execution is returned.

Summary

We have seen how to build a REST API type API Gateway.

TOC