التخطي إلى المحتوى الرئيسي

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



تعليقات

المشاركات الشائعة من هذه المدونة

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...

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...

Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025

 Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025 Now a days most of the IT Company asked NODE JS Question mostly in interview. I am creating this article to provide help to all MERN Stack developer , who is in doubt that which type of question can be asked in MERN Stack  then they can learn from this article. I am Shiva Gautam,  I have 15 Years of experience in Multiple IT Technology, I am Founder of Shiva Concept Solution Best Programming Institute with 100% Job placement guarantee. for more information visit  Shiva Concept Solution 1. What is the MERN Stack? Answer : MERN Stack is a full-stack JavaScript framework using MongoDB (database), Express.js (backend framework), React (frontend library), and Node.js (server runtime). It’s popular for building fast, scalable web apps with one language—JavaScript. 2. What is MongoDB, and why use it in MERN? Answer : MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. It...