How to Create and deploy Lambda function on AWS with CDK and API endpoint to Lambda
Tags: aws, typescript, serverless, cloudskills
Published: 2021-11-26 08:10:35

### 1.What is AWS and CDK ?
[Amazon Web Services]('https://aws.amazon.com/what-is-aws/') (AWS) is the world’s most comprehensive and broadly adopted scalable 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]('https://aws.amazon.com/cdk') (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 scalable

### 2.Lambda Function
**[AWS Lambda](https://aws.amazon.com/)**  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]('https://aws.amazon.com/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 environment. I have written step by step guide how to configure AWS profile and deploy simple helloWorld Application. If you are beginner then before writing lambda code [Read basic Guide here ]('https://dev.to/abdulwaqar844/a-beginner-s-guide-to-configure-aws-cdk-and-deploy-hello-world-app-54ll')
##### **Note** :  _In this article 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
```sh
mkdir hello_lambda_with_apigatway
```

### step 2
initialize your cdk project in typescript by running the following command

```
cdk init app --language typescript
```

## 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 separate 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
```

## step 4
Initialize your lambda function 

```typescript
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",
    });
   
  }
}
```
Let me explain this code. we have created a class HelloLamdaStack in which we have initialized our lambda function and API Gateway. In this code we have declared that we will use  Nodejs 10  version and code of our lambda function 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.
```typescript
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");
```typescript
### step 5
add the handler code for your lambda in lambda/hello.ts
```typescript
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`
  };
}
```
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](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) because they require [assets](https://docs.aws.amazon.com/cdk/latest/guide/assets.html) i.e. handler code that will be bundled with the CDK library etc. and stored in S3 bootstrapped bucket:

```
cdk bootstrap
```


## Step 7 (optional)

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

```
cdk synth
```

## 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
```


## Step 9 

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

```
cdk deploy
```

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

```
npm run build && cdk deploy
```

## step 10

Now test the function in AWS Lambda Console (make sure you are in the correct region):
https://console.aws.amazon.com/lambda/home#/functions


## 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,
    });
```


## step 12

deploy again 

```
cdk deploy
```

## step 13

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

curl https://xxxxxx.execute-api.us-east-2.amazonaws.com/prod/
:blush: Congratulation ! You have successfully deployed your first Lambda Function and API Gateway to call Lambda Function on AWS Cloud.