Implementing AWS Lambda in  TypeScript  behind an API gateway using AWS CDK

Implementing AWS Lambda in TypeScript behind an API gateway using AWS CDK

ยท

4 min read

Table of contents

No heading

No headings in the article.

Greetings, In this blog, we will learn how to implement AWS Lambda in typescript and deploy it behind API gateway using AWS CDK.

Complete Code for this Project: github.com/proton0210/LamdaRest-API

Few prerequisites,

  1. Have an AWS Account
  2. AWS credentials set up on your device
  3. Node installed
  4. CDK installed globally

To get up to speed in no time with these prerequisites follow this part of this amazing workshop:here

So let's get started by reviewing our architecture LamdaAPI.jpg

Representing a Simple hello world API

Let's start developing this architecture.

In your terminal execute the following command

mkdir lambda-api && cd lambda-api

Now, let's initialize a starter CDK project using CDK CLI.

cdk init --language typescript

Now open the project in your fav code editor,

Before we start developing, we first need to fix a bug which will hopefully soon be resolved by the CDK team

In your cdk.json file remove the following line and save your file Screenshot 2021-11-27 at 1.06.10 PM.png

Run npm watch command to catch any errors while coding from your root directory

npm run watch

Let's now bootstrap and deploy our initial setup to make sure everything is in sync

cdk bootstrap
cdk deploy

If everything works smoothly you will have a bucket in your console with cloud formation templates deployed by the CDK in your account.

Now let's create a package .json file in root directory

npm init --y

We will install esbuild (Package our Typescript Code) and types for AWS lambda(For type assistance using typescript)

npm i esbuild
npm i @types/aws-lambda

Now let's create a folder in our root directory name functions and inside it create Hello.ts file

Screenshot 2021-11-27 at 5.23.54 PM.png

Our Hello.ts exports a handler that simply returns "Hello From Lambda" in its body

We can see the power of TypeScript here by providing us the assistance using the right which helps us to code functions confidently

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


export const handler = async  (event:APIGatewayProxyEvent,context:Context):Promise<APIGatewayProxyResult> =>{
    const result: APIGatewayProxyResult = {
        statusCode: 200,
        body: 'Hello ๐Ÿ‘‹๐Ÿป from Lambda '
    }
    return result;
}

Now let's deploy this function behind an API Gateway

move to the lambda -api.ts file in the lib folder

In this file, we will integrate the rest API with the lambda

First, we will need to import the constructs for the following

import {LambdaIntegration, RestApi} from "aws-cdk-lib/lib/aws-apigateway";

We will initialize an instance of the RestAPI in the stack

  private api = new RestApi(this, 'HelloApi');

Now, we will import the Lamda function and bind it with our API Let's import the necessary constructs for the same

import {NodejsFunction} from "aws-cdk-lib/aws-lambda-nodejs";
import {join} from "path";

In the Constructor, we will integrate our lambda function with our API

   const namasteLambda =  new NodejsFunction(this, "HelloLambdaInTS", {
      entry: (join(__dirname, '..', 'functions', 'Hello.ts')),
      handler: 'handler',
      functionName: "HelloLambdaInTS",
    })
    const api = this.api.root.addResource('hello');
    api.addMethod('GET', new LambdaIntegration(namasteLambda))

keep on checking your npm run watch terminal for any possible errors

Complete file code :

import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';

import {NodejsFunction} from "aws-cdk-lib/aws-lambda-nodejs";
import {join} from "path";

import {LambdaIntegration, RestApi} from "aws-cdk-lib/lib/aws-apigateway";


export class LambdaRestApiStack extends Stack {
  private api = new RestApi(this, 'HelloApi');

  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here

    const namasteLambda =  new NodejsFunction(this, "HelloLambdaInTS", {
      entry: (join(__dirname, '..', 'functions', 'Hello.ts')),
      handler: 'handler',
      functionName: "HelloLambdaInTS",
    })
    const api = this.api.root.addResource('hello');
    api.addMethod('GET', new LambdaIntegration(namasteLambda))

  }
}

To deploy this code :

cdk diif
cdk deploy

After successful deployment you will get the following link:

  https://7ixxxx6c.execute-api.us-east-1.amazonaws.com/prod/

Your's will be different

append hello at the end to make sure you get the desired results.

https://7ixxxx6c.execute-api.us-east-1.amazonaws.com/prod/**hello**

Screenshot 2021-11-27 at 5.41.01 PM.png

Well we're done ๐Ÿป

To clear your account now :

cdk destroy

this will tear down your complete infrastructure

Complete Code for this Project: github.com/proton0210/LamdaRest-API

Connect with me on Twitter: twitter.com/Vidit_210