DynamoDb CRUD Operation Code using Lambda

0

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.





Tags

Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)