In this tutorial, you will learn how to connect a Lambda function to AWS API Gateway, and also how to call this from a static website. If you have not set up a static website I have a tutorial on how to set up a static website using AWS S3 here. If you prefer video tutorials be sure to check out my tutorial on YouTube.

How to Create a Lambda Function

From your AWS Console navigate to the Lamba services (either search for Lambda or under Compute click Lambda). On the AWS Lamba dashboard click “Create function”.

Click "Create function" on AWS Lambda Dashboard
AWS Lambda Dashboard

We are going to create a Lambda function from scratch so make sure the “Author from scratch” is selected. For this tutorial, let’s name the function “AWSTutorialAPI”, and have Node.js be selected for the runtime, keep the permissions as the default values. Click the “Create Function” button.

Lambda Function Settings
Lambda Function Settings

You will be brought into your newly created AWS Lambda Function. It will already have a prefilled out Node.js function that returns back “Hello from Lamba!” Congratulations you’ve made your first AWS Lamba function. Lets now connect this function to the AWS Gateway API.

How to set up AWS API Gateway

Go back to your AWS Console and navigate to API Gateway (either search for “API Gateway” or under “Networking & Content Delivery ” click “API Gateway”). On your API Gateway dashboard click “Create API”.

Click "Create API" on AWS API Gateway Dashboard
API Gateway Dashboard

In this tutorial we are going to make a REST API, so click “Build” to develop a REST API.

Click Build on REST API
Build REST API

On the next screen keep make sure the protocol selected is REST, chose New API and for this tutorial, our API’s name will be AWSTutorialAPI, and then click the “Create API” button.

REST API Setup
REST API Setup

You know will be brought to your new REST API, which is empty with no methods. So let’s make our first method. Click on the Actions dropdown and click “Create Method”

Click on the Actions dropdown and click "Create Method"
Click “Create Method”

When this is created select “GET” from the dropdown. We chose a GET call because we are just retrieving information, without making any modifications.

Select “GET” from the dropdown

Now our GET method has been created and you will be in the GET – Setup screen. In GET – Setup screen select your integration type to be a Lambda Function, your Lambda region should be where you created your Lambda functions, and then type in the Lambda function name (it will match to your Lambda function), then click the “Save” button.

Modify GET - Setup to connect to Lambda
Modify GET – Setup to connect to Lambda

You will be alerted that you are adding permissions to your Lambda function. You can now test the GET method to see your response from Lamba.

So now we have successfully connected our AWS API Gateway to our Lambda function, but we are not done yet. We need to deploy our AWS API Gateway in order to use this API with our static website.

Deploying AWS API Gateway

Inside your AWS API click the “Action” dropdown and click “Deploy API”.

Click "Deploy API"
Click “Deploy API”

We have no deployment stage at the moment, so select “[New Stage]” and name the Stage “Prod” and click “Deploy”.

Deploy API
Deploy API

You now have successfully deployed your API, and you are provided an invoke URL, where you can call your API (which then calls your Lambda function).

So if we want our static website to be able to call this API function and return a successful result we have one more set, and that’s enabling CORs on both or AWS API Gateway and Lambda function. This is because our S3 Bucket has a different domain than our AWS API endpoint.

Enable CORS on Lambda

Go back to the AWS Lambda function we created early and update the code to be the following (and click save):

exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
        headers:  {
            "Access-Control-Allow-Orgin" : "*"
        },
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

What was added was the Access-Control-Allow-Origin response header. This header indicates whether the response can be shared with requesting code from the given origin. You can specify an origin instead of allowing all, but in this tutorial, we are allowing all.

Enable CORS on AWS API Gateway

Go back to the AWS API Gateway your greater in your tutorial and click the “Actions” dropdown and select “Enable CORS”. By default it already has the Access-Control-Allow-Origin set to all, specify a domain otherwise click “Enabled CORS and replace existing CORS headers”.

Enable CORS on your AWS API
Enable CORS

It will give you a summation of all the changes click “Yes, replace existing values”. So we have enabled CORS for our API, now we need to redeploy our API. Inside your AWS API click the “Action” dropdown and click “Deploy API”, and select the “Prod” stage we created.

Test the Setup

So let’s make sure or set up works. The following is some simple HTML that calls the AWS API Gateway from a Static Website, you can either test this locally on your computer or upload it to your AWS S3 bucket.

<html>
    <head>
	<script>
		async function callAwsLambdaFunction() {
			fetch( 'ADD API URL HERE',  {
				method: 'GET'
			  })
			.then(response => response.json())
			.then((response) => {
				console.log(response);
				document.getElementById("myDiv").innerHTML = response.body;
			});
        }
    </script>   
        <title>Test</title>
    </head>
    <body>
		<p>This is only a test, nothing else.</p>
        <p>Click below button to call API gateway and display result below!</p>
        <p><div id="myDiv"></div></p>
        <button onclick="callAwsLambdaFunction()">Click me!</button>
	</body>
</html>

Update the API URL to be the invoke URL of your deployed AWS API Gateway. If you receive a CORS error, make sure your Lambda function was updated and you redeployed your AWS API Gateway after enabling CORS.

Congratulations you just learned how to connect a Lambda function to AWS API Gateway, and also how to call this from a static website!