Lambda integrations in API Gateway
Lambda functions can be invoked on an HTTPS URL using methods GET, PUT, and POST. The data passed to the URL can be made available inside the lambda function too. You can integrate an API method with a Lambda function using Lambda proxy integration or non-proxy (custom) integration.
Amazon API Gateway Lambda proxy integration is a simple, powerful, and nimble mechanism to build an API with a setup of a single API method.
We will look at building an API gateway using the Lambda proxy integration. So when a client sends an API request, we can use the request data (headers, query string parameters, URL path variables, and payload) in the backend Lambda function.
Set up Lambda proxy integration in API Gateway
We will deploy a simple CDK application to show how to set up the integration. It consists of a Lambda function that returns a response, fronted by an API Gateway so you can access it from the internet.
Create the starter application and install the necessary dependencies by running the following commands:
Change lib/lambda-custom-integration-stack.ts
which defines the application's infrastructure to look like the following:
Lets go over what the code will provision:
- A Lambda function called
backend
to parse any request data sent by a client. The handler property indicates the entry file, then the function to run inside this file (exported function). - An API Gateway so we can invoke the function from the internet. We updated the stage name of the API to
dev
. By default thestageName
is set toprod
. The name of the stage is used in the API url.
Create the Lambda function backend
We referenced the function in our stack using the handler attribute. The value index.handler
can be broken down to:
- index: the file called
index.js
inside thesrc
directory. - handler: the function inside the
index.js
to execute.
We need to define a Lambda handler we referenced in our stack. Create a src/index.js
file and add the following code:
We created an API Gateway to expose GET /{name}
method to invoke a Lamda function. The function simply responds with a welcome message to the passed username on the URL path.
Deploy API and test integration
We can check if our infrastructure as code (IaC) is valid by issuing the cdk synth
command. Finally to deploy the stack just run cdk deploy
command, the URL for the API Gateway endpoint should be output on the terminal:
To test the API using a browser, simply paste the URL to the browser with a name appended as a path or no name appended.
Summary
The source code for the starter application cab be found on the lambda-custom-integration repo on my GitHub. This was just a small starter application to guide you on using an API Gateway with Lambda.