Lambda integrations in API Gateway

Lambda functions can be invoked on an HTTPS URL using methods GET, PUT, and POST. The data passed to the URL can be made available inside the lambda function too. You can integrate an API method with a Lambda function using Lambda proxy integration or non-proxy (custom) integration.

Amazon API Gateway Lambda proxy integration is a simple, powerful, and nimble mechanism to build an API with a setup of a single API method.

We will look at building an API gateway using the Lambda proxy integration. So when a client sends an API request, we can use the request data (headers, query string parameters, URL path variables, and payload) in the backend Lambda function.

Set up Lambda proxy integration in API Gateway

We will deploy a simple CDK application to show how to set up the integration. It consists of a Lambda function that returns a response, fronted by an API Gateway so you can access it from the internet.

Create the starter application and install the necessary dependencies by running the following commands:

mkdir lambda-custom-integration && cd lambda-custom-integration
cdk init --language=typescript
Initialize CDK application

Change lib/lambda-custom-integration-stack.ts which defines the application's infrastructure to look like the following:

import { Stack, StackProps, CfnOutput, Duration } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as gateway from 'aws-cdk-lib/aws-apigateway';
import * as path from 'path';

/**
 * A stack for our simple Lambda-powered web service
 */
export class LambdaCustomIntegrationStack extends Stack {
    constructor(scope: Construct, id: string, props?: StackProps) {
        super(scope, id, props);

        // The Lambda function that contains the functionality
        const backend = new lambda.Function(this, 'Lambda', {
            runtime: lambda.Runtime.NODEJS_14_X,
            handler: 'index.handler',
            code: lambda.Code.fromAsset(path.join(__dirname, '/../src/')),
        });

        // An API Gateway to make the Lambda web-accessible
        const api = new gateway.LambdaRestApi(this, 'Gateway', {
            description: 'Endpoint for a simple Lambda-powered web service',
            handler: backend,
            deployOptions: {
                stageName: "dev"
            },
        });

    }
}
Creating the API Gateway

Lets go over what the code will provision:

  1. A Lambda function called backend to parse any request data sent by a client. The handler property indicates the entry file, then the function to run inside this file (exported function).
  2. An API Gateway so we can invoke the function from the internet. We updated the stage name of the API to dev. By default the stageName is set to prod. The name of the stage is used in the API url.

Create the Lambda function backend

We referenced the function in our stack using the handler attribute. The value index.handler can be broken down to:

  • index: the file called index.js inside the src directory.
  • handler: the function inside the index.js to execute.

We need to define a Lambda handler we referenced in our stack. Create a src/index.js file and add the following code:

exports.handler = async (event) => {
    var name = event.path.slice(1);
    var response = {
        "statusCode": 200,
    };

    if (name == null || name === '') {
        response.body = "Hello 👋, you invoked a Lambda function using an API Gateway 👌🏽";
    } else {
        name =  name[0].toUpperCase() + name.slice(1)
        response.body = "Hello " + name + " 🙂. You invoked a Lambda function using an API Gateway 👌🏽"
    }
    return response;
};
Lambda backend logic with Node.js

We created an API Gateway to expose GET /{name} method to invoke a Lamda function. The function simply responds with a welcome message to the passed username on the URL path.

Deploy API and test integration

We can check if our infrastructure as code (IaC) is valid by issuing the cdk synth command. Finally to deploy the stack just run cdk deploy command, the URL for the API Gateway endpoint should be output on the terminal:

To test the API using a browser, simply paste the URL to the browser with a name appended as a path or no name appended.

Summary

The source code for the starter application cab be found on the lambda-custom-integration repo on my GitHub. This was just a small starter application to guide you on using an API Gateway with Lambda.