NodeJs : How to trigger AWS Lambda functions -NodeJs with API Gateway: A Step-by-Step Guide

Introduction:

AWS Lambda functions provide serverless compute capabilities, while API Gateway allows you to create RESTful APIs to interact with those functions. In this guide, we’ll walk through the process of triggering an AWS Lambda function when an HTTP POST request is made through API Gateway. We’ll also provide a sample Lambda function code to illustrate the process.

Prerequisites:

Before getting started, make sure you have the following:

An AWS account.

AWS CLI and AWS SDKs (if needed).

Basic knowledge of AWS Lambda and API Gateway.

Step 1: Create an AWS Lambda Function

Go to the AWS Lambda Console.

Click “Create function.”

Choose “Author from scratch” and provide a function name, runtime (e.g., Node.js), and an execution role with appropriate permissions.

Write your Lambda function code (e.g., Node.js code that handles the form data processing).

Sample Lambda Function Code (Node.js):

exports.handler = async (event) => {
  try {
    const requestBody = JSON.parse(event.body);
    // Process the data as needed
    // ...
    const response = {
      statusCode: 200,
      body: JSON.stringify({ message: 'Data received and processed successfully' }),
    };
    return response;
  } catch (error) {
    console.error('Error:', error);
    return {
      statusCode: 500,
      body: JSON.stringify({ message: 'Internal server error' }),
    };
  }
};

Step 2: Create an API in API Gateway

Go to the API Gateway Console.

Click “Create API” and choose “HTTP API” or “REST API,” depending on your needs.

Configure your API settings, including the API name and security settings.

Step 3: Create an API Gateway Resource and Method

In the API Gateway Console, select your API and create a resource (e.g., /submit) under the “Resources” section.

Under the resource, create a new HTTP POST method.

Configure the integration type to Lambda Function and select your Lambda function.

Step 4: Deploy Your API

Deploy your API to create a public endpoint.

Note the endpoint URL, as this is where your HTML form will send requests.

Step 5: Set Up CORS (Cross-Origin Resource Sharing)

To allow your HTML form to make requests to the API, configure CORS settings in your API Gateway.

Step 6: Update Your HTML Form

In your HTML form, set the form’s action attribute to the API Gateway endpoint URL.

<form action="https://your-api-id.execute-api.your-region.amazonaws.com/your-stage/submit" method="POST">
  <!-- Form inputs here -->
  <input type="text" name="data" id="data">
  <input type="submit" value="Submit">
</form>

Step 7: Test Your Setup

Open your HTML form hosted on your preferred platform (e.g., S3) and submit some data. It should now trigger the Lambda function via the API Gateway.

Refer more on python here :

Author: user

Leave a Reply