Published: December 15, 2016
This is a step-by-step guide to setting up an AWS Lambda function and attaching it to an API endpoint. The goal of this tutorial is to get you familiar with setting up an AWS Lambda function that you can POST data to and return a response.
This example uses a minimal AWS security configuration, which should not be used for production applications.
If you prefer to watch a walkthrough, here is a recording of the steps below in action. 👀
After clicking Get Started Now, you will be presented with a list of blueprints to select. This is an optional step that we will skip for now. Instead, click Configure triggers in the top left navigation menu.
An AWS Lambda is only a function, so something will have to trigger that function. In our tutorial, we want to POST data to a url and trigger the function. To do this in the AWS world, you will use the API Gateway trigger.
Click the dotted-grey box and select API Gateway in the menu.
Here you will select the API to use and how it will be invoked. If this is your first time using the API Gateway, AWS will setup a gateway titled LambdaMicroservice. AWS will also create a resource named /null which isn't ideal, but I'll show you how to change that later. For now, make sure to update the following:
Here we'll setup the function to run. Most of this should have the correct defaults, but AWS stores your previous settings in local storage, so double check that everything matches below.
Give the function a name and description. We'll use the default function for this example. In case this looks different for you, here is the code:
exports.handler = (event, context, callback) => {
// TODO implement
callback(null, 'Hello from Lambda');
};
Scroll down till you reach the Role* option. This is where we specify the AWS security role to run the function as. If this is your first AWS Lambda function, I'd recommend creating a new role from template and giving it a name. In the example, I used slack-events as the name of my new role. Everything else can remain the same.
The last step is just to confirm the we got everything entered correctly. If everything looks good, click Create function.
If all goes well, you should have a fancy new Lambda function waiting for requests and a URL to send requests to.
AWS has a test console in the Web UI, but I prefer testing it externally. This example shows a sample cURL post.
curl -X POST https://1grvd23rfe.execute-api.us-east-1.amazonaws.com/prod/null
Things are working, but that /null endpoint is bothering you, right? No problem! Now that Lamba did all the heavy lifting of setting up the AWS API Gateway service for us, we can add a new endpoint to listen to easily.
There are a bunch of steps, but it sounds worse than it really is. Here's a recording of the the steps in action.
curl -X POST https://1grvd23rfe.execute-api.us-east-1.amazonaws.com/prod/slack