ProgramMatek: CDK API Gateway

Next step: Adding an API Gateway in front of our function. The API Gateway will expose a public HTTP endpoint that anyone on the internet can access using an HTTP client like curl or a web browser.

Adding a LambdaRestApi construct to your stack

To define an API endpoint and associate it with our Lambda function, we need to add the following code to (which should still be open from the previous step):

# Code snippet

That’s all it takes to define an API Gateway that proxies all requests to an AWS Lambda function.

Previewing Changes

Let’s see what will happen when we deploy this:

cdk diff

The output should resemble this:

Output of cdk diff

Please note that the cdk-workshop stack uses assets, which are not currently accounted for in the diff output. You can find more information about this here.

IAM Statement Changes

Here are the changes made to the IAM statements:

Summary of IAM Statement Changes

IAM Policy Changes

Here are the changes made to the IAM policies:

Summary of IAM Policy Changes

(NOTE: There may be security-related changes not listed here. You can find more details here.)

Resources Created

The deployment of the API Gateway has added 12 new resources to our stack.

Deploying the Stack

Are you ready to deploy? Run the following command:

cdk deploy

Stack Outputs

Once the deployment is complete, you’ll notice the following line:

CdkWorkshopStack.Endpoint8024A810 =

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

See also  API The Box 2: The Evolution of a Classic Console

Testing Your App

Let’s hit the endpoint using curl. Copy the URL and execute the following command (please note that your prefix and region may be different):


The output should resemble this:

Hello, CDK! You've hit /

Alternatively, you can also use your web browser to access the same endpoint.

If you see the expected output, congratulations, your app is working!


If you receive a 5xx error from the API Gateway, it is likely due to one of the following issues:

  1. The response returned by your function is not what API Gateway expects. Make sure your handler returns a response that includes statusCode, body, and header fields (see Write handler runtime code).
  2. Your function encountered an error. To debug this, refer to the section on how to view your Lambda logs.

Great job! In the next chapter, we will write our own reusable construct. Stay tuned!