API Gateway

Next step is to add an API Gateway in front of our function. API Gateway will expose a public HTTP endpoint that anyone on the internet can hit with an HTTP client such as curl or a web browser.

We will use Lambda proxy integration mounted to the root of the API. This means that any request to any URL path will be proxied directly to our Lambda function, and the response from the function will be returned back to the user.

Add a LambdaRestApi construct to your stack

Let’s define an API endpoint and associate it with our Lambda function. Add this code to cdk_app_stack.py (which you should still have open from the last step):

from aws_cdk import (
    core,
    aws_dynamodb,
    aws_lambda,
    aws_apigateway
)


class SlsAppStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        ## 1. Define the table that count number of times the path is hitted.
        table = aws_dynamodb.Table(
            self, 
            "counter-table",
            partition_key={
                'name': 'path',
                'type': aws_dynamodb.AttributeType.STRING
            }
        )
        
        ## 2.1. Defines Lambda resource & API-Gateway request handler
        ## All API requests will go to the same function.
        handler = aws_lambda.Function(self, "CounterFunction",
            code=aws_lambda.Code.asset("./lambda"),
            handler="index.handler",
            timeout=core.Duration.seconds(5),
            runtime=aws_lambda.Runtime.PYTHON_3_8
        )
        ## 2.2. Pass the table name to the handler through an env variable 
        ## and grant the handler read/write permissions on the table.
        table.grant_read_write_data(handler)
        handler.add_environment('TABLE_NAME', table.table_name)
        
        ## 3. Define the API endpoint and associate the handler
        api = aws_apigateway.LambdaRestApi(self, "CounterAPI",
                                           handler=handler)

CDK diff

Let’s see what’s going to happen when we deploy this:

cdk diff sls-app

CDK deploy

Okay, ready to deploy?

cdk deploy sls-app

Stack outputs

When deployment is complete, you’ll notice this line:

sls-app.CounterAPIEndpoint7CF77D5B = https://9v0c13ssy7.execute-api.ap-southeast-1.amazonaws.com/prod/

This is a stack output that’s automatically added by the API Gateway construct and includes the URL of the API Gateway endpoint.

Testing your app

Let’s try to hit this endpoint with curl. Copy the URL and execute (your prefix and region will likely be different).

If you don’t have curl installed, you can always use your favorite web browser to hit this URL.

curl https://9v0c13ssy7.execute-api.ap-southeast-1.amazonaws.com/prod/

Output should look like this:

You've hit /: 1 time(s)