Skip to main content

DynamoDb CRUD Operation Code using Lambda

Utilizing DynamoDB with AWS Lambda and Boto3

Presentation

DynamoDB is a completely overseen NoSQL information base help given by AWS that supports key-worth and report information structures. AWS Lambda is a serverless process administration that runs your code because of occasions and consequently deals with the fundamental register assets. Boto3 is the Amazon Web Administrations (AWS) SDK for Python, which permits Python designers to compose programming that utilizes administrations like Amazon S3, Amazon EC2, and DynamoDB.


Setting Up

1. Make a DynamoDB Table

To begin with, make a DynamoDB table to store your information. You can do this utilizing the AWS The executives Control center or automatically utilizing Boto3.


Model: Making a Table Utilizing Boto3


python

import boto3


# Make a DynamoDB client

dynamodb = boto3.client('dynamodb')


# Make a table

dynamodb.create_table(

    TableName='Students',

    KeySchema=[

        {

            'AttributeName': 'RollNumber',

            'KeyType': 'HASH' # Segment key

        }

    ],

    AttributeDefinitions=[

        {

            'AttributeName': 'RollNumber',

            'AttributeType': 'N'

        }

    ],

    BillingMode='PAY_PER_REQUEST'

)

2. Make an AWS Lambda Capability

Then, make an AWS Lambda capability that will connect with your DynamoDB table.


Model: Making a Lambda Capability Utilizing Boto3


python

import boto3


# Make a DynamoDB asset

dynamodb = boto3.resource('dynamodb')


def lambda_handler(event, setting):

    # Your code here

    pass

Embedding Records

1. Embed a Record Utilizing PutItem

To embed a record into your DynamoDB table, utilize the PutItem Programming interface.


Model: Embedding a Record


python

def lambda_handler(event, setting):

    table = dynamodb.Table('Students')


    reaction = table.put_item(

        Item={

            'RollNumber': 1,

            'Name': 'John Doe'

        }

    )


    bring reaction back

Refreshing Records

1. Update a Record Utilizing UpdateItem

To refresh a record in your DynamoDB table, utilize the UpdateItem Programming interface.


Model: Refreshing a Record


python

def lambda_handler(event, setting):

    table = dynamodb.Table('Students')


    reaction = table.update_item(

        Key={'RollNumber': 1},

        UpdateExpression='SET Name = :val1',

        ExpressionAttributeValues={

            ':val1': 'Jane Doe'

        }

    )


    bring reaction back

Erasing Records

1. Erase a Record Utilizing DeleteItem

To erase a record from your DynamoDB table, utilize the DeleteItem Programming interface.


Model: Erasing a Record


python

def lambda_handler(event, setting):

    table = dynamodb.Table('Students')


    reaction = table.delete_item(

        Key={'RollNumber': 1}

    )


    return



 1)  Create Table under dynamodb Tablename Employee (EmpId,Empname,Age)


2) Create Lambda Function to Insert and Show Record

import json

import boto3

from botocore.exceptions import ClientError

import showdata

# Create a DynamoDB client

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('Employee')  # Replace with your table name


def lambda_handler(event, context):

    # Data to insert (you can modify this based on the incoming event or hardcode)

    item = {

        'EmpID':'113',  # Partition key, replace as needed

        'Empname': 'Ravi',

        'Age': 30

    }


    try:

        # Insert the item into the DynamoDB table

        table.put_item(Item=item)

        print('Item inserted successfully!')

        showdata.fun()

       

        

    except ClientError as e:

        print(f"Error inserting item: {e}")

        return {

            'statusCode': 500,

            'body': json.dumps('Failed to insert item')

        }



for show:

import boto3
import json
import os
from decimal import Decimal
def decimal_to_float(obj):
    if isinstance(obj, list):
        return [decimal_to_float(i) for i in obj]
    elif isinstance(obj, dict):
        return {k: decimal_to_float(v) for k, v in obj.items()}
    elif isinstance(obj, Decimal):
        return float(obj)
    return obj

def fun():
    # Initialize DynamoDB resource
    dynamodb = boto3.resource('dynamodb')
    
    # Table name (replace with your table name)
    table_name = os.environ.get('DYNAMODB_TABLE', 'Employee')
    
    # Access the table
    table = dynamodb.Table(table_name)
    
    try:
        # Example: Query based on a primary key (adjust the KeyConditionExpression as per your schema)
        response = table.query(
            KeyConditionExpression=boto3.dynamodb.conditions.Key('EmpID').eq('111')
        )
        
        # Retrieve items from the response
        items =decimal_to_float(response.get('Items', []))
        print(items)
        return {
            'statusCode': 200,
            'body': json.dumps(items)
        }
    except Exception as e:
        print(f"Error fetching data from DynamoDB: {str(e)}")
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Failed to fetch data'})
        }




3)  Manage Policy 

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:Query",
"dynamodb:GetItem"
],
"Resource": "arn:aws:dynamodb:ap-south-1:<accountid>:table/Employee"
}
]
}
Code to Select and Insert Record

import json
import boto3
from botocore.exceptions import ClientError
import crudstudents
def lambda_handler(event, context):
     dynamodb = boto3.resource('dynamodb')
     crudstudents.showstudent()
     return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')}


code of crudstudents.py

import boto3
def insertStudent():
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Student')
    item = {

        'rno':'1003',  # Partition key, replace as needed

        'name': 'test',

        'branch': 'CS',
        
         'fees':45000

    }
    table.put_item(Item=item)
    print('Item inserted successfully!')

def showstudent():
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Student')
    response = table.scan() 
    data = response['Items']
    print(data)


Role:
Assign an IAM Role:     Create a new role with AmazonDynamoDBReadOnlyAccess and AWSLambdaBasicExecutionRole permissions, or use an existing role with these permissions.


Dynamodb Another Example:

For Insert, Update and Select Record
import json
import boto3


def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Student')
    #reaction = table.put_item(Item={'Enrollno': 'SCS1007','Name': 'Allon Musk'})
    table.update_item(
        Key={'Enrollno': 'SCS1001','Name':'Trayambak Pandey'},
        UpdateExpression='SET #n = :v',
        ExpressionAttributeNames={'#n': 'Qualification'},
        ExpressionAttributeValues={':v': 'PHD'}
    )
    response = table.scan()
    items = response['Items']

    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps(items)
    }


Code for Permission
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Statement1",
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:GetItem"
],
"Resource": "arn:aws:dynamodb:ap-south-1:288542289586:table/Student"
}
]
}



Comments

Popular posts from this blog

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

Conditional Statement in Python

It is used to solve condition-based problems using if and else block-level statement. it provides a separate block for  if statement, else statement, and elif statement . elif statement is similar to elseif statement of C, C++ and Java languages. Type of Conditional Statement:- 1) Simple if:- We can write a single if statement also in python, it will execute when the condition is true. for example, One real-world problem is here?? we want to display the salary of employees when the salary will be above 10000 otherwise not displayed. Syntax:- if(condition):    statements The solution to the above problem sal = int(input("Enter salary")) if sal>10000:     print("Salary is "+str(sal)) Q)  WAP to increase the salary of employees from 500 if entered salary will be less than 10000 otherwise the same salaries will be displayed. Solution:- x = int(input("enter salary")) if x<10000:     x=x+500 print(x)   Q) WAP to display th...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...