Serverless API CRUD with lambda and DynamoDB
Published: 2023-04-26 01:54:46

In this blog post, I will show you how to build a serverless CRUD API with AWS Lambda and Amazon DynamoDB using the AWS Console. This is a great way to build APIs quickly and easily without having to worry about managing servers or infrastructure.

An Amazon API Gateway is a collection of resources and methods. For this tutorial, you create one resource (DynamoDBManager) and define one method (POST) on it. The method is backed by a Lambda function (LambdaFunctionOverHttps). That is, when you call the API through an HTTPS endpoint, Amazon API Gateway invokes the Lambda function.

The POST method on the DynamoDBManager resource supports the following DynamoDB operations:

Create, update, and delete an item.
Read an item.
Scan an item.
Other operations (echo, ping), not related to DynamoDB, that you can use for testing.

Prerequisites
An AWS account
The AWS Console

Step 1: Create Lambda IAM Role
Create the execution role that gives your function permission to access AWS resources.

To create an execution role : Open the roles page in the IAM console, Choose Create role. Create a role with the following properties. Trusted entity – Lambda. Role name –lambda-apigateway-role.
Create a Permissions – Custom policy with permission to DynamoDB and CloudWatch Logs. This custom policy has the permissions that the function needs to write data to DynamoDB and upload logs.

```
{
"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"
}
]
}
```

Step 2: Create a DynamoDB table
First, we need to create a DynamoDB table to store our data. We can do this using the AWS Console:

Go to the DynamoDB console. To create a DynamoDB table
Open the DynamoDB console.
Choose Create table.
Create a table with the following settings.
Table name – lambda-apigateway
Primary key – id (string)
Click on "Create".


Step 3: Create a Lambda function
Next, we need to create a Lambda function to handle our API requests. We can do this using the AWS Console:

Go to the Lambda console.
Click on "Create Function".
In the "Function name" field, enter a name for your function.
In the "Runtime" drop-down, select "Phyton 3.7".
Add the script with python code.

```
from __future__ import print_function

import boto3
import json

print('Loading function')


def lambda_handler(event, context):
    '''Provide an event that contains the following keys:

      - operation: one of the operations in the operations dict below
      - tableName: required for operations that interact with DynamoDB
      - payload: a parameter to pass to the operation being performed
    '''
    #print("Received event: " + json.dumps(event, indent=2))

    operation = event['operation']

    if 'tableName' in event:
        dynamo = boto3.resource('dynamodb').Table(event['tableName'])

    operations = {
        'create': lambda x: dynamo.put_item(**x),
        'read': lambda x: dynamo.get_item(**x),
        'update': lambda x: dynamo.update_item(**x),
        'delete': lambda x: dynamo.delete_item(**x),
        'list': lambda x: dynamo.scan(**x),
        'echo': lambda x: x,
        'ping': lambda x: 'pong'
    }

    if operation in operations:
        return operations[operation](event.get('payload'))
    else:
        raise ValueError('Unrecognized operation "{}"'.format(operation))
```
Add the existing script ambda-apigateway-role wich allow to create, update and delete objects in the DynamoDB table.
Click on "Create".

Test Lambda Function
Let's test our newly created function. We haven't created DynamoDB and the API yet, so we'll do a sample echo operation. The function should output whatever input we pass.

Paste the following JSON into the event. The field "operation" dictates what the lambda function will perform. In this case, it'd simply return the payload from input event as output. Click "Create" to save.

```
{
    "operation": "echo",
    "payload": {
        "somekey1": "somevalue1",
        "somekey2": "somevalue2"
    }
}
```



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/12tbewmst1tfgd93csrr.png)



Step 4: Create an API Gateway API
Finally, we need to create an API Gateway API to expose our Lambda function to the internet. We can do this using the AWS Console:

Go to the API Gateway console.
Click on "Create API".
In the "API Name" field, enter a name for your API.
In the "API Type" drop-down, select "REST API".
Click on "Create".
Step 4: Create a method
Now that we have created an API, we need to create a method to handle our API requests. We can do this using the AWS Console:

In the "Methods" tab, click on "Create Method".
In the "Method Type" drop-down, select "POST".
In the "Path" field, enter the path for your method.
Click on "Create".

Step 5: Integrate the method with Lambda
Now that we have created a method, we need to integrate it with our Lambda function. We can do this using the AWS Console:

In the "Integrations" tab, click on "Create Integration".
In the "Integration Type" drop-down, select "Lambda Function".
In the "Lambda Function" field, select the name of your Lambda function.
Click on "Create".

Step 6: Deploy the API
Now that we have configured our API, we need to deploy it. We can do this using the AWS Console:

In the "Actions" menu, click on "Deploy API".
In the "Deployment stage" drop-down, select a stage.
Click on "Deploy".

Testing the API
Running our solution
The Lambda function supports using the create operation to create an item in your DynamoDB table. To request this operation, use the following JSON:

```
{
    "operation": "create",
    "tableName": "lambda-apigateway",
    "payload": {
        "Item": {
            "id": "1234ABCD",
            "number": 5
        }
    }
}
```
T o test the solution I used a VS Code extension call Thunder client, is a lightweight Rest API Client Extension for Visual Studio Code, hand-crafted by Ranga Vadhineni with simple and clean design.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rg8ecnntns3cncb019oi.png)
Or also can use the Code snippet
curl -X GET https://{API_GATEWAY_ENDPOINT}/{PATH}
Use code with caution.
This will return the response from our Lambda function.

To validate that the item is indeed inserted into DynamoDB table, go to Dynamo console, select "lambda-apigateway" table, select "Items" tab, and the newly inserted item should be displayed.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zdp31poyo82khliwkar2.png)

Cleanup
Let's clean up the resources we have created for this lab.

Cleaning up DynamoDB
To delete the table, from DynamoDB console, select the table "lambda-apigateway", and click "Delete table"

To delete the Lambda, from the Lambda console, select lambda "LambdaFunctionOverHttps", click "Actions", then click Delete

To delete the API we created, in API gateway console, under APIs, select "DynamoDBOperations" API, click "Actions", then "Delete"

Conclusion
In this blog post, we showed you how to build a serverless CRUD API with AWS Lambda and Amazon DynamoDB using the AWS Console. This is a great way to build APIs quickly and easily without having to worry about managing servers or infrastructure.