Sitemap
Cloudnloud Tech Community

cloud training

Integrating API Gateway, Lambda and DynamoDB.

7 min readJul 30, 2023

--

Press enter or click to view image in full size
Press enter or click to view image in full size

In this tutorial, I am creating a demo application to explain serverless microservices.

Serverless is an approach that facilitates running an application without a need to manage underlying infrastructure. It eliminates the need for provisioning, scaling, and maintaining any servers to run applications and databases. AWS Lambda is a serverless compute platform designed to run functions and is an example of “Function As A Service”. The Cost is calculated based on the amount of time the code runs on the server.

I will create a REST API through which I will invoke a Lambda function using an HTTP request. This Lambda function used is performing create, read, update, and delete (CRUD) operations on a DynamoDB table.

API Gateway provides a secure HTTP endpoint to invoke Lambda function. To complete this tutorial, I will create a Lambda function, a REST API in API Gateway and a DynamoDB table to test Lambda functions. Then I will deploy the API and use the curl command in the terminal to test.

In this architecture, Amazon API Gateway acts as a front door for microservices, allowing clients to make HTTP API calls. The API gateway is tightly integrated with Lambda and can make synchronous calls to Lambda functions. The API call from the client triggers the corresponding Lambda function that processes the API request. For persistent storage, DynamoDB is leveraged by Lambda.

With these hands on you will learn:

  1. How to use an API gateway to create an HTTP endpoint that invokes a Lambda Function?
  2. How to Deploy an API?
  3. How to test an API using curl command?

Create a permission policy.

To give the lambda function permission to access the required AWS resources I created a permissions policy. This policy allows Lambda functions to perform CRUD operations on a DynamoDB table.

To create the policy

  1. Go to IAM console and open the policies page.
  2. Click Create Policy.
  3. Click the JSON tab, and then paste the following custom policy.
{ “Version”: “2012–10–17”,
“Statement”: [
{
“Sid”: “Stmt1428341300017”,
“Action”: [
“dynamodb:DeleteItem”,
“dynamodb:GetItem”,
“dynamodb:PutItem”,
“dynamodb:Query”,
“dynamodb:Scan”,
“dynamodb:UpdateItem”
],
“Effect”: “Allow”,
“Resource”: “*”
},
{
“Sid”: “”,
“Resource”: “*”,
“Action”: [
“logs:CreateLogGroup”,
“logs:CreateLogStream”,
“logs:PutLogEvents”
],
“Effect”: “Allow”
}
]
}

For the policy Name, enter any name of your choice and click Create policy.

Create an execution role.

I will create an execution role and attach the policy created in the previous step to enable Lambda function to perform operations on a DynamoDB table.

To create an execution role and attach your custom permissions policy:

  1. In IAM console Open the policies page and click on choose Create role.
  2. For trusted entity, choose AWS service, then for the use case, choose Lambda and then click Next.
  3. In the policy search box, enter the name of the policy that you created in the previous step.
  4. Enter the Role name, then click create role.

Create the function.

This code receives an event input from API Gateway specifying an operation to perform on the DynamoDB table. I got this code from AWS Tutorials.

import boto3
import json
# define the DynamoDB table that Lambda will connect to
tableName = "lambda-apigateway"
# create the DynamoDB resource
dynamo = boto3.resource('dynamodb').Table(tableName)
print('Loading function')
def lambda_handler(event, context):

# define the functions used to perform the CRUD operations
def ddb_create(x):
dynamo.put_item(**x)
def ddb_read(x):
dynamo.get_item(**x)
def ddb_update(x):
dynamo.update_item(**x)
def ddb_delete(x):
dynamo.delete_item(**x)
def echo(x):
return x
operation = event['operation']
operations = {
'create': ddb_create,
'read': ddb_read,
'update': ddb_update,
'delete': ddb_delete,
'echo': echo,
}
if operation in operations:
return operations[operation](event.get('payload'))
else:
raise ValueError('Unrecognized operation "{}"'.format(operation))

Make sure you configure the runtime settings of the Lambda Function by specifying the correct handler.

And configure permissions by assigning the execution role created in the earlier steps to the Lambda function.

Press enter or click to view image in full size

Create a Test Event

To confirm that I have deployed the function correctly I Created a test event containing the parameters that API Gateway API will send to Lambda.

{
"operation": "echo",
"payload": {
"key1": "value1",
"key2": "value2"
}

Create a REST API using API Gateway

In this step, I created the API Gateway REST API you will use to invoke the Lambda function.

To create the API

  1. In API gateway, Click Create API.
  2. In the REST API box, choose Build.
  3. Under Settings, for API Name enter any name, click Create API.
Press enter or click to view image in full size

Create a resource on REST API

First step is to create a resource and create a method to operate on that resource. In this I will create a resource to manage DynamoDB table.

  1. In the Resources tree of the API, make sure that the root (/) level is highlighted. Then, choose Actions, Create Resource.
  2. Under New child resource enter the resource name and keep the default resource path that it automatically creates.
  3. Click Create Resource.
Press enter or click to view image in full size

Create an HTTP POST method.

Now I will create a POST method for the resource and will link this POST method to the Lambda function. On receiving an HTTP request, API Gateway will invoke the linked Lambda function.

Get Reeti’s stories in your inbox

Join Medium for free to get updates from this writer.

To create the POST method

  1. In the console in the Resources tree of your API, select the resource you created, click Actions and create method.
  2. Choose POST and choose the check mark icon.
  3. In the method’s Setup pane, For Integration type, choose Lambda Function and For Region, choose the same AWS Region as your Lambda function.
  4. Enter the name of your function and Click Save.
Press enter or click to view image in full size

Create a DynamoDB table.

  1. Go to DynamoDB console and click Create table.
  2. Enter the table name and For Partition key, enter id, and keep the data type set as String.
  3. Under Table settings, keep the Default settings.
  4. Choose Create table.

Test the integration of API Gateway, Lambda, and DynamoDB

Use the console’s test function from the API Gateway console, to test the integration of API Gateway API method with the Lambda function and the DynamoDB table. To send a request directly to the POST method use a create operation to add a new item to the DynamoDB table.

To create a new item in your DynamoDB table

  1. Go to API console and click the API, click the resource and then click the POST method.
  2. In the Method Execution pane, in the Client box, choose Test.
  3. In the Method Test pane, keep Query Strings and Headers empty. For Request Body, paste the following JSON:
{
"operation": "create",
"payload": {
"Item": {
"id": "1234",
"number": 6
}
}
}

Click Test.
The status code 200 will indicate that the create operation was successful.
Check the DynamoDB table now contains the new item.

In the DynamoDB console, click tables and click table name.

Click Explore table items and found the item with the id 1234 and the number 6 exists.

Press enter or click to view image in full size

Deploy the API

Create a deployment and an associated stage. A stage represents a snapshot of the API including its methods and integrations.

  1. Go to API Gateway Console, Open the APIs page and choose the API that I created.
  2. Click Actions and select Deploy API.
  3. In the Deployment stage, I choose [New Stage] and entered test for Stage name. And then click Deploy.
  4. Invoke URL will be generated. Copy this invoke url.

Use curl to invoke your function using HTTP requests.

To invoke the Lambda function using curl

  1. Run the following curl command using the invoke URL you copied in the previous step. When you use curl with the -d (data) option, it automatically uses the HTTP POST method.
curl https://<invoke url> -d '{"operation": "create", "payload": {"Item": {"id": "5678", "number": 5}}}'

To verify that the create operation was successful, click Table in the DynamoDB console and then Click Explore table items. I can see an item with the id 5678 and the number 5.

Press enter or click to view image in full size

Run the following curl command to delete the item. Use your own invoke URL.

curl https://<invoke url> -d '{"operation": "delete", "payload": {"Key": {"id": "1234"}}}'

Confirm that the delete operation was successful. In the Items returned pane of the DynamoDB console Explore items page, verify that the item with id 1234 is no longer in the table.

Press enter or click to view image in full size

Thank you!

--