How to use Amplify to Leverage AWS CDK with Cognito, Lambda, and API Gateway — Part 4

Amchelle C.
2 min readJun 28, 2021

This article is part of a series, checkout Part 1 , Part 2 and Part 3 to set up your environment for CDK.

We have our CDK project all set up, our Cognito User Pool ready to authenticate as well as a basic Lambda function that we can now integrate with our API Gateway REST API. We are officially past the baby pool and into the deep end.

First, go to the main file in your project. For me it is, “lib/example-app.ts”. Run npm install and add an import statement for the aws-apigateway module.

npm install @aws-cdk/aws-apigateway

Next, add the following code to create a REST API in the CDK. We will be creating an API Gateway REST API resource that also includes the default CORS preflight options, you can customize these to your choosing.

import * as apigateway from '@aws-cdk/aws-apigateway'// PREVIOUS CODEconst api = new apigateway.RestApi(this, 'exampleapi', {  
defaultCorsPreflightOptions: {
allowOrigins: apigateway.Cors.ALL_ORIGINS,
allowMethods: apigateway.Cors.ALL_METHODS,
allowCredentials: true,
},
restApiName: 'exampleApi',
description: 'Example endpoint'
});

Now add our specified resource to the root of the API. You can create multiple nested resources that have their own methods for each (POST, GET, PUT).

const exampleResource = api.root.addResource('example')

Add a Lambda integration to link our “exampleLambda” function to our method that we will create in later steps.

const exampleIntegration = new apigateway.LambdaIntegration(
exampleLambda, \\ Lambda function created in Part 3
)

Create an authorizer with our Cognito User Pool implemented in Part 2.

const exampleAuth = new apigateway.CognitoUserPoolsAuthorizer(this, 'exampleAuth', {
cognitoUserPools: [userPool]
});

Next, we will create a method with our previously created integration and add our Cognito as an authorizer. This will only allow users in the Cognito User Pool to call the API endpoint.

exampleResource.addMethod('GET', exampleIntegration, {
authorizationType: apigateway.AuthorizationType.COGNITO,
authorizer: exampleAuth
});

You can find more information about creating REST APIs on the AWS CDK README. APIs can also be created that include a lambda-backed API, where all calls to the API are routed to a specific AWS Lambda function.

We are now ready to run cdk diff and then cdk deploy if we are happy with the changes.

After the deploy is complete, the CDK will display your newly created REST API endpoint. You can also view your API in the AWS Management Console by searching for “API Gateway”.

In part 5, the final of the series, we will add Amplify to our frontend code to see how all of this comes together!

--

--