Skip to content
Home » Program to Create a Hello World API using AWS Lambda and API Gateway

Program to Create a Hello World API using AWS Lambda and API Gateway

In this blog post, we will learn how to create a simple Hello World API using AWS Lambda and API Gateway. This program will allow you to respond with a JSON message containing a greeting and the event data. Let’s dive into the details!

Code

import { APIGatewayProxyEvent, Context, APIGatewayProxyResult } from "aws-lambda"

export async function hello (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Hello world',
      input: event,
    })
  }
}

Code Explanation

The provided code snippet demonstrates a basic setup for a hello world API using AWS Lambda and API Gateway. Let’s break down the code and understand each part:

The first line imports the necessary dependencies from the “aws-lambda” package. We are importing the APIGatewayProxyEvent, Context, and APIGatewayProxyResult types.

The next line defines an asynchronous function named “hello”, which takes in two parameters – the event and context. The event parameter represents the data received from the API Gateway, while the context parameter provides runtime information.

Inside the “hello” function, we return a Promise. This Promise resolves to an object with a statusCode and body. The statusCode is set to 200, indicating a successful response, and the body is a JSON string containing a message and the event data.

To test this hello world API, we can deploy it using AWS Lambda and API Gateway. Once deployed, you can make a request to the API endpoint and receive a “Hello world” message along with the input data.

Here’s how the code can be executed:

javascript
import { APIGatewayProxyEvent, Context, APIGatewayProxyResult } from "aws-lambda"

export async function hello (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Hello world',
      input: event,
    })
  }
}

Conclusion

In this blog post, we have learned how to create a Hello World API using AWS Lambda and API Gateway. This simple program allows us to respond with a JSON message containing a greeting and the received event data. It can serve as a starting point for building more complex serverless applications using these AWS services. Happy coding!

Also checkout the following codes.


Program to Group Data Based on Property in JavaScript
Program to Create Demand from Idea in ServiceNow