In this second part on Amazon’s API Gateway, we walk through step by step, how to create a simple API Gateway endpoint using Amazon Lambda via Node.js to return simple JSON data.
The first part of the tutorial covers ideal features for building an API on top of.
What is Lambda?
In Computer Science or Mathematics, a Lambda function is simply an anonymous method. In Amazon AWS, Lambda relates to running small chunks of code without needing to have Servers, Web Containers such as IIS or Apache running. It lets you focus on defining a method in a language and it handles the rest.
Currently Lambda supports:
Create a Lambda function
Start by creating a lambda function by navigating to Lamda Services in the AWS Console.
Do not select a trigger for the Lambda function. This is handled in the second step where we wire the API Gateway to the lambda function.
Choose a language in the Runtime dropdown. Node.js 4.3 is used in this simple example as it does not require compilation.
When I created my first Lambda function, Amazon asked for an existing role. One was not defined and Amazon suggested creating lambda_basic_execution which is fine for our purposes.
Once the Lambda function has been created, the Lambda service provides the ability to Save and Test. In the example below you can see that the callback has been updated to return some fake data.
As the test Lambda function is read only, the input can be ignored and ran anyway.
The results can be observed:
Creating an API Gateway
An API Gateway allows the Lambda to be consumed. Create a New API and call it something meaningful.
From the / node choose Actions > Create Resource. This simple tutorial models a list of schools, so a school resource is created.
A GET method is added to the schools resource, which expose the Lambda function.
Set the Integration Type to Lambda Function and select the region that the Lambda is hosted in.
A successfully mounted Lambda function creates an interface similar to the one below. The test icon on the far left provides testing for the endpoint. Following the diagram, the information flows from the left to the right, and from right to left across the bottom.
The left 2 columns, Method Request and Method Response provide the ability to modify the input and output parameters.
Note: The Models menu option in the API Gateway allows a user to provide JSON Schema to define a valid JSON input format.