DEV Community

Cover image for How to Create and deploy Lambda function on AWS with CDK and API endpoint to Lambda
Abdul Waqar
Abdul Waqar

Posted on

How to Create and deploy Lambda function on AWS with CDK and API endpoint to Lambda

1.What is AWS and CDK ?

Amazon Web Services (AWS) is the world’s most comprehensive and broadly adopted scaleable cloud platform. AWS offering over 200 fully featured services from data centers globally. Millions of customers—including the fastest-growing startups, largest enterprises, and leading government agencies—are using AWS to lower costs, become more agile, and innovate faster.
The AWS Cloud Development Kit (AWS CDK) is an open source software development framework to define your cloud application resources using familiar programming languages.CDK is used to define structure of our application as Code. We can call it Infrastructure as Code which is best for scaleable

2.Lambda Function

AWS Lambda is a serverless, event-driven compute service that lets you run code for virtually any type of application or backend service without provisioning or managing servers. You can trigger Lambda from over 200 AWS services and software as a service (SaaS) applications, and only pay for what you use.

3.Amazon API Gateway

AWS API Gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale. APIs act as the main communication gateway for applications to access data,apply business logic, or functionality from your backend services. Using API Gateway, you can create RESTful APIs and WebSocket APIs that enable real-time two-way communication applications. API Gateway supports containerized and serverless workloads, as well as web applications.

API Gateway handles all the tasks involved in accepting and processing up to hundreds of thousands of concurrent API calls, including traffic management, CORS support, authorization and access control, throttling, monitoring, and API version management. API Gateway has no minimum fees or startup costs. You pay for the API calls you receive and the amount of data transferred out and, with the API Gateway tiered pricing model, you can reduce your cost as your API usage scales.

Lets write code for Lambda Function

Before deploying code to AWS Clouds we need to configure our AWS profile with our development envoirnment. I have written step by step guide how to configure AWS profile and deploy simple helloWorld Application. If you are begginer then before writing lambda code Read basic Guide here

Note : In this artical we will use Typescript language to write Application Code

Steps to write & compile the code

step 1

make a new folder for your cdk project

mkdir hello_lambda_with_apigatway
Enter fullscreen mode Exit fullscreen mode

step 2

intialize your cdk project in typescript by running the following command

cdk init app --language typescript
Enter fullscreen mode Exit fullscreen mode

step 3

run the following command to build your ts files in real-time. This process needs to keep running in the background so it is best if you run it in a seperate terminal. If you don't want to watch application build process at real time you can skip this step and after writing code make a build before deploying.

npm run watch
Enter fullscreen mode Exit fullscreen mode

step 4

Initialize your lambda function

import * as cdk from "@aws-cdk/core";
import * as lambda from "@aws-cdk/aws-lambda";
import * as apigw from "@aws-cdk/aws-apigateway";

export class HelloLambdaStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    const hello = new lambda.Function(this, "HelloHandler", {
      runtime: lambda.Runtime.NODEJS_10_X,
      code: lambda.Code.fromAsset("lambda"),
      handler: "hello.handler",

Enter fullscreen mode Exit fullscreen mode

Let me explain this code. we have created a class HelloLamdaStack in which we have initialized our lambda funtion and API Gateway. In this code we have declared that we will use Nodejs 10 version and code of our lambda funtion is exist in lambda folder at root directory and name of our lambda function is hello.
Also update code of /bin/ . Code in this file will create a New Stack for lambda function.

import "source-map-support/register";
import * as cdk from "@aws-cdk/core";
import { HelloLambdaStack } from "../lib/step01_hello_lambda-stack";

const app = new cdk.App();
new Step01HelloLambdaStack(app, "HelloLambdaStack");
Enter fullscreen mode Exit fullscreen mode


step 5

add the handler code for your lambda in lambda/hello.ts

import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';

export async function handler(event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> {
  console.log("request:", JSON.stringify(event, undefined, 2));

  return {
    statusCode: 200,
    headers: { "Content-Type": "text/plain" },
    body: `Hello, CDK! You've hit ${event.path}\n`
Enter fullscreen mode Exit fullscreen mode

When we call endpoint to this lambda function our function will return "Hello, CDK! You've hit ${event.path}".

step 6

Installing Bootstrap Stack.
For Lambda functions we will need to do bootstrapping becuase they require assets i.e. handler code that will be bundleded with the CDK library etc. and stored in S3 bootstraped bucket:

cdk bootstrap
Enter fullscreen mode Exit fullscreen mode

Step 7 (optional)

Run the following command to see the cloud formation template of your cdk code.

cdk synth
Enter fullscreen mode Exit fullscreen mode

Step 8 (optional)

Run the following command to see the difference between the new changes that you just made and the code that has already been deployed on the cloud.

cdk diff
Enter fullscreen mode Exit fullscreen mode

Step 9

Run the following command to deploy your code to the cloud.

cdk deploy
Enter fullscreen mode Exit fullscreen mode

if you did not run "npm run watch" in the step 4 then you need to build the project before deployment by running the folliwng command. npm run build will also compile typescript files of the lambda function

npm run build && cdk deploy
Enter fullscreen mode Exit fullscreen mode

step 10

Now test the function in AWS Lambda Console (make sure you are in the correct region):

step 11

Next step is to add an API Gateway in front of our function. Install the dependency: npm install @aws-cdk/aws-apigateway

new apigw.LambdaRestApi(this, "Endpoint", {
      handler: hello,
Enter fullscreen mode Exit fullscreen mode

step 12

deploy again

cdk deploy
Enter fullscreen mode Exit fullscreen mode

step 13

Get the URL from the output and test it using curl or paste the url in browser:

😊 Congratulation ! You have successfully deployed your first Lambda Function and API Gateway to call Lambda Function on AWS Cloud.

Discussion (2)

mxro profile image
Max Rohde

Thanks for this tutorial, looks very useful. Considering to start using CDK myself.

abdulwaqar844 profile image
Abdul Waqar Author

Thank you,It is my pleasure that you have found my artical helpful. Looking to write about other sercives of AWS like DynamoDB , AppSync and Cognito etc