How To Create Item In Amazon DynamoDB Using AWS Lambda With Python

Introduction

In this article, you will learn how to create items in Amazon DynamoDB using AWS Lambda with Python. For this article, I have created a simple Amazon DynamoDB named Projects with a partition key as Project_ID (S).

Input request (JSON)

{
 "Project_ID": "XXX1009897",
 "Customer_Name": "ABCD",
 "Project_Name": "XYZ",
 "Technology": "Java"
}

API Endpoint (POST method): https://1xxxxx2xx3.execute-api.us-east-1.amazonaws.com/poc/projects

Output Response: A new item is created in DynamoDB table.

Prerequisites

  1. Lambda function created. Refer to Building Lambda functions with Python
  2. API Endpoint created. Refer to Build an API Gateway REST API with Lambda integration
  3. Required permissions and role created to access Amazon DynamoDB. Refer to Lambda execution role
  4. Amazon DynamoDB table is created. Refer to this documentation to create a table in DynamoDB.
  5. Add the below environment variable in the Lambda function.

TABLE_NAME = Projects

Code Snippet

Update the code in lambda_function.py with the following.

import os
import boto3

def lambda_handler(event, context):
    dynamodb_client = boto3.client('dynamodb')
table_name = os.environ['TABLE_NAME']
dynamodb_client.put_item(TableName = table_name,
    Item = {
        'Project_ID': {
            'S': event.get('body-json').get('Project_ID')
        },
        'Customer_Name': {
            'S': event.get('body-json').get('Customer_Name')
        },
        'Project_Name': {
            'S': event.get('body-json').get('Project_Name')
        },
        'Technology': {
            'S': event.get('body-json').get('Technology')
        }
    })
return {
    'statusCode': 200,
    'body': 'Successfully inserted data!'
}

Click Deploy to update the changes in the Lambda function.

Test the API

Open Postman and execute the following API to get the results as shown below.

How to create item in Amazon DynamoDB using AWS Lambda with Python

Summary

This article describes how to create items in Amazon DynamoDB using AWS Lambda with Python.


Similar Articles