Build your first serverless API with API Gateway and Lambda function using CDK and TypeScript

Build your first serverless API with API Gateway and Lambda function using CDK and TypeScript

Serverless is one of the most powerful approaches for building fast ,scalable and cost effective applications . In this article, I will walk you through building a simple API with two endpoints in under 10 minutes . We will leverage AWS lambda and Amazon API Gateway, deploying the entire infrastructure using AWS CDK with TypeScript.

This Api serves as a robust foundation for your serverless projects or compelling way to showcase your expertise.

Prerequisites

Before getting started,ensure you to have the following:

BASH
aws configure
Click to expand and view more
BASH
npm install -g aws-cdk
Click to expand and view more

1. Initialize The CDK project

First, create a dedicated directory for your project and navigate into it:

BASH
mkdir serverless-api-demo
cd serverless-api-demo
Click to expand and view more

Then ,initialize a new CDK app using TypeScript:

BASH
cdk init app --language typescript
Click to expand and view more

CDK will generate the following project structure:

2. Create the Lambda Function

Next we need to write the business logic for our API. Create a /lambda directory at root of your project and add the file named hello.ts.

BASH
mkdir lambda
touch lambda/hello.ts
Click to expand and view more

Add the following snippet to your hello.ts file

TYPESCRIPT
//lambda/hello.ts

//hello fonction
export const helloFunction = async()=> {
    return {
        statusCode: 200,
        body: JSON.stringify({message: "hello world from aws lambda "}),
    }
};


// get users fonction
export const getUsersFunction = async()=>{
    const users = [
        {
            id : 1,
            name: "lonfo"
        },
        {
            id : 2,
            name : "ainix"
        },
        {
            id : 3,
            name: "pascal"
        }
    ];

    return {
        statusCode: 200,
        body: JSON.stringify( users),
    };
}
Click to expand and view more

This file contains the logic for our two Lambda handlers : helloFunction and getUsersFunction

3. Define the lambda functions in CDK

Now open the lib/serverless-api-demo-stack.ts file and replace its content with the following code to provision our resources:

TS
import * as cdk from 'aws-cdk-lib/core';
import { Construct } from 'constructs';
import * as nodeJsLambda from 'aws-cdk-lib/aws-lambda-nodejs';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';

export class ServerlessApiDemoStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Hello Lambda Function
    const helloLambda = new nodeJsLambda.NodejsFunction(this, 'HelloHandler', {
      entry: 'lambda/hello.ts',
      handler: 'helloFunction',
      functionName: 'helloFunction',
    });

    // Get Users Lambda Function  
    const getUsersLambda = new nodeJsLambda.NodejsFunction(this, 'GetUsersHandler', {
      entry: 'lambda/hello.ts',
      handler: 'getUsersFunction',
      functionName: 'getUsersFunction',
    });
    
    // create API Gateway and integrate with Lambda functions

    const api = new apigateway.RestApi(this, 'ServerlessApiDemoApi', {
      restApiName: 'Serverless API Demo Service',
    });

    // Hello endpoint
    const helloIntegration = new apigateway.LambdaIntegration(helloLambda);
    api.root.addResource('hello').addMethod('GET', helloIntegration);

    // Get Users endpoint
    const getUsersIntegration = new apigateway.LambdaIntegration(getUsersLambda);
    api.root.addResource('users').addMethod('GET', getUsersIntegration);
  }
}
Click to expand and view more

Summary of the infrastructure:

4. Deploy the infrastructure

Before deploying execute:

SH
cdk bootstrap
cdk synth  

cdk deploy 
Click to expand and view more

5. Testing the API

Once the deployment is complete, the terminal wotll display the output section,containing the API gateway endpoint URL. You can use this base URL to call your lambda function.

résuttal du déployment

SH
// replace  xxxxxxxxxxx with the data contained in your URL

curl https://xxxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/hello |jq
Click to expand and view more

/hello execution

SH
curl https://xxxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/users |jq
Click to expand and view more

/users execution

6. Clean-Up

to avoid any unexpected charges on your aws account, make sure to delete the resources created during this tutorial . You can easily tear down the entire stack using the following command

SH
cdk destroy
Click to expand and view more

Comments

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut