How to Integrate Lambda Function with AWS API Gateway using AWS CDK

Introduction

In the previous post, we detailed the process of creating a Lambda function using AWS CDK. In this follow-up post, we take the next step by providing a comprehensive guide on integrating the Lambda function with AWS API Gateway. Before delving into the steps of this integration, it’s crucial to address the following questions:

  • What is API Gateway?
  • Why is it necessary to integrate Lambda with API Gateway?
  • How we can integrate Lambda with API Gateway?

After getting the answer to these questions we will move further to explain the steps of integrating AWS API Gateway with the Lambda function. So let’s start with our first question.

What is API Gateway?

According to aws official documentation

API Gateway provides tools for creating and documenting web APIs that route HTTP requests to Lambda functions. You can secure access to your API with authentication and authorization controls. Your APIs can serve traffic over the internet or can be accessible only within your VPC.

Amazon API Gateway is a fully managed service in AWS that enables easy creation, publication, maintenance, monitoring, and securing of APIs at any scale. It serves as a “front door” for our applications, enabling them to access data, business logic, and functionality from our backend services, such as:

  • AWS Lambda: Serverless functions triggered by events.
  • Elastic Compute Cloud (EC2) instances: Virtual servers running in the cloud.
  • Amazon S3: Storage service for object storage.
  • DynamoDB: NoSQL database service.
  • Other AWS services or external web services: API Gateway can be connected to a wide range of other resources.

Why is it necessary to integrate Lambda with API Gateway?

Integrating Lambda with API Gateway is for several reasons. Here are a few key points that are mentioned below.

  1. Seamless Serverless Architecture:
    • AWS Lambda allows us to run code without managing servers and handling infrastructure concerns like CPU, memory, and networking. This serverless approach simplifies development and ensures that you can focus on your code’s logic.
  2. Efficient API Management:
    • AWS API Gateway provides tools for creating, documenting, and managing APIs. It acts as a central entry point for API calls, offering features like request routing, security controls, and traffic management. This simplifies API management tasks and enhances overall efficiency.
  3. Scalability and Flexibility:
    • When API Gateway is integrated with Lambda, the combination provides automatic scaling. Lambda functions scale based on demand, and API Gateway automatically handles the increased traffic, ensuring our application remains responsive and cost-effective.
  4. Authentication and Authorization:
    • API Gateway offers robust authentication and authorization controls. By integrating with Lambda, we can secure access to our APIs, ensuring that only authorized users or applications can invoke our Lambda functions. This enhances the security of our serverless architecture.
  5. Event-Driven Architecture:
    • AWS Lambda is event-driven, and API Gateway can trigger Lambda functions based on HTTP requests. This enables us to build event-driven architectures where API calls automatically trigger specific Lambda functions, allowing for a dynamic and responsive system.
  6. Simplified Development Workflow:
    • The integration of API Gateway and Lambda streamlines the development workflow. Developers can focus on writing business logic in Lambda functions without worrying about the complexities of API management. This separation of concerns leads to a more modular and maintainable codebase.
  7. Cost-Efficiency:
    • With Lambda’s pay-as-you-go pricing model and API Gateway’s cost structure, we only pay for the actual resources consumed. This cost-efficiency is realized by the seamless integration of these services, allowing us to scale resources based on demand without incurring unnecessary expenses during idle periods.
  8. Enhanced Monitoring and Logging:
    • AWS provides monitoring and logging features for both API Gateway and Lambda. By integrating these services, you gain comprehensive insights into the performance and behavior of your serverless applications. This facilitates troubleshooting, performance optimization, and compliance monitoring.
  9. Versatility in Application Architecture:
    • The integration allows you to build versatile application architectures. Lambda functions can be orchestrated to work together, leveraging other AWS services, and API Gateway acts as the front door for these functions, making the system more modular and extensible.

How can we integrate Lambda with API Gateway?

There are several ways to integrate Lambda with API Gateway in AWS, providing flexibility and options based on our specific use case and requirements. Here are the primary integration methods:

  • Lambda Proxy Integration
  • Lambda Function Integration
  • HTTP Integration
  • Lambda Authorizer Integration

Integrate Lambda with API Gateway

In the preceding post, we comprehensively addressed the steps involved in creating a Lambda function using AWS CDK with TypeScript. If there are any lingering doubts, then anyone can refer to the previous post by clicking here. Continuing from where we left off, this post delves further into the same stack. We will once again navigate to the stack file in the ‘lib’ folder, opening it to implement necessary modifications.
Up to this point, our code development progress is illustrated below:


import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';

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

    // The code that defines your stack goes here

    const lambdaFunction =new lambda.Function(this,'lambdaFunction',{
      handler:'index.handler',
      functionName:'demoLambdaFunction',
      runtime:lambda.Runtime.NODEJS_16_X,
      code: lambda.Code.fromInline(`
      exports.handler = async (event) => {
        return {
          statusCode: 200,
          body: JSON.stringify({ message: 'Hello, World!' }),
        };
      };
      `)
    })

    const fnUrl= lambdaFunction.addFunctionUrl({
      authType:lambda.FunctionUrlAuthType.NONE
    })

    new cdk.CfnOutput(this,'lambda-fun-url',{
      value:fnUrl.url
    })
  }
}

In this section, our primary objective is to write the code for integrating Lambda with API Gateway. As our Lambda function has already been created in a previous post, our current focus is on establishing the API Gateway. To facilitate understanding, we will present the upcoming code in a step-by-step format, streamlining the integration process.

Step 1: import API Gateway package

import * as apigateway from '@aws-cdk/aws-apigateway';

The code begins with importing the necessary modules from the @aws-cdk/aws-apigateway library, which provides constructs for defining API Gateway resources.

Step 2: Create API Gateway

const demoAPI = new apigateway.RestApi(this, 'MydemoApi', {
      restApiName: 'MydemoApi',
    });

An instance of the RestApi class is created, representing an Amazon API Gateway. It is named ‘MydemoApi’ and configured with the name ‘MydemoApi’. This is the main entry point for defining the API and its resources.

Step 3: Lambda Integration

const integration = new apigateway.LambdaIntegration(lambdaFunction);

An instance of the LambdaIntegration class is created, specifying the Lambda function (lambdaFunction) that will handle requests from the API. This integration establishes a connection between the API Gateway and the Lambda function.

Step 4: Define API resource

const resource = demoAPI.root.addResource('myresource');

A new resource named ‘myresource’ is added to the root of the API. This represents a path in the API’s URL structure.

Step 5: Add Method to Resource

resource.addMethod('GET', integration);

A ‘GET’ method is added to the ‘myresource’ resource, and it is configured to use the previously defined Lambda integration (integration). This means that when a ‘GET’ request is made to the ‘myresource’ path, it will trigger the associated Lambda function to handle the request.

Now, combining the code and providing a concluding statement:


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

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

    // The code that defines your stack goes here
 
    const lambdaFunction =new lambda.Function(this,'lambdaFunction',{
      handler:'index.handler',
      functionName:'demoLambdaFunction',
      runtime:lambda.Runtime.NODEJS_16_X,
      code: lambda.Code.fromInline(`
      exports.handler = async (event) => {
        return {
          statusCode: 200,
          body: JSON.stringify({ message: 'Hello, World!' }),
        };
      };
      `)
    })
    const fnUrl= lambdaFunction.addFunctionUrl({
      authType:lambda.FunctionUrlAuthType.NONE
    })
    // Create API Gateway
    
    const demoAPI = new apigateway.RestApi(this, 'MydemoApi', {
      restApiName: 'MydemoApi',
    });
    // Lambda Integration
    
    const integration = new apigateway.LambdaIntegration(lambdaFunction);
    
     // Define API resource 
    
    const resource = demoAPI.root.addResource('myresource');
     // Add method to resource 
    
    resource.addMethod('GET', integration);

    

    new cdk.CfnOutput(this,'lambda-fun-url',{
      value:fnUrl.url
    })
  }
}
Step 5: Synthesize an AWS CloudFormation template for the app

   cdk synth
    
Step 8: Deploying the Stack (Deploy the stack using AWS CloudFromation)

   cdk deploy
    

Following deployment, we will access the AWS console to verify the creation of the API Gateway.

Subsequently, we will test the response of our API Gateway after its integration with Lambda directly from the console.

To examine the response of the Lambda function, we will copy the function URL from the command line, as demonstrated earlier, and initiate a request using Postman.

Conclusion

In conclusion, this post provided an in-depth exploration of integrating AWS Lambda with API Gateway. We delved into the importance of this integration, showcasing how API Gateway acts as the front door for applications, connecting them with backend services like Lambda, EC2 instances, S3, DynamoDB, and more. The benefits of a seamless serverless architecture, efficient API management, scalability, authentication, and event-driven architecture were discussed.

The post also outlined the steps to integrate Lambda with API Gateway, emphasizing the versatility it brings to application architecture. By presenting a consolidated code snippet and highlighting the various integration methods, readers gained practical insights into implementing this crucial connection.

As a next step, readers were guided through the process of writing the integration code in a step-by-step manner. The provided code, combining Lambda and API Gateway, showcased the power of AWS CDK and TypeScript in creating a scalable and secure serverless application.

Leave a comment