Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Integrating AWS Lambda and DynamoDB for Seamless Data Management

Get data from Dynamo Db
Put Item into DynamoDB

To create a Lambda function that inserts data into Amazon DynamoDB, and receive data from Django, you can follow these steps. We'll use Python for both the Lambda function and the Django application.
Syntax
Put Item into DynamoDB:

import boto3

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    table_name = event['table_name']
    item = event['item']

    table = dynamodb.Table(table_name)
    table.put_item(Item=item)
    return f"Item {item} added to DynamoDB table {table_name}."
Enter fullscreen mode Exit fullscreen mode

Input:

{
    "table_name": "your-dynamodb-table",
    "item": {"id": 1, "name": "John Doe", "age": 30}
}
Enter fullscreen mode Exit fullscreen mode

Output:

"Item {'id': 1, 'name': 'John Doe', 'age': 30} added to DynamoDB table y
Enter fullscreen mode Exit fullscreen mode

Step 1: Set Up DynamoDB Table
Create a DynamoDB table with the desired attributes. For example, let's create a table named UserProfiles with the UserID as the primary key.

Step 2: Set Up Lambda Function
Create a new Lambda function in the AWS Lambda console.

Lambda Function Code:

import json
import boto3

dynamodb = boto3.resource('dynamodb')
table_name = 'UserProfiles'
table = dynamodb.Table(table_name)

def lambda_handler(event, context):
    try:
        # Parse data from the Django request
        data = json.loads(event['body'])

        # Insert data into DynamoDB
        response = table.put_item(
            Item={
                'UserID': data['UserID'],
                'FirstName': data['FirstName'],
                'LastName': data['LastName'],
                'Email': data['Email']
            }
        )

        return {
            'statusCode': 200,
            'body': json.dumps('Data inserted successfully into DynamoDB')
        }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps(f'Error: {str(e)}')
        }
Enter fullscreen mode Exit fullscreen mode

Lambda Function Configuration:

Set the runtime to Python 3.x.
Add an execution role with DynamoDB write permissions.
Set up an API Gateway trigger for the Lambda function.
Step 3: Set Up API Gateway
Create an API Gateway to act as an endpoint for your Django application to send requests to the Lambda function.

Step 4: Django Application
In your Django application, use the requests library to send data to the API Gateway.

Example Django Code:

import requests
import json

def send_data_to_lambda(data):
    api_gateway_url = 'YOUR_API_GATEWAY_URL'
    lambda_endpoint = f'{api_gateway_url}/YOUR_RESOURCE_NAME'

    headers = {'Content-Type': 'application/json'}
    response = requests.post(lambda_endpoint, data=json.dumps(data), headers=headers)

    return response.json()
Enter fullscreen mode Exit fullscreen mode

Replace 'YOUR_API_GATEWAY_URL' with the actual URL of your API Gateway and 'YOUR_RESOURCE_NAME' with the resource name configured in your API Gateway.

Now, when you call send_data_to_lambda(data) from your Django application with the required data, it will trigger the Lambda function to insert data into DynamoDB.

Make sure to handle security aspects such as authentication and authorization based on your specific requirements.

Get data from Dynamo Db

syntax

import boto3

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    table_name = event['table_name']
    key = event['key']

    table = dynamodb.Table(table_name)
    response = table.get_item(Key=key)
    return response.get('Item', {})
Enter fullscreen mode Exit fullscreen mode

Input:

{
    "table_name": "your-dynamodb-table",
    "key": {"id": 1}
}
Enter fullscreen mode Exit fullscreen mode

Output:

{"id": 1, "name": "John Doe", "age": 30}
Enter fullscreen mode Exit fullscreen mode

We'll use Python for both the Lambda function and the Django application.

Step 1: Set Up DynamoDB Table
Create a DynamoDB table with the desired attributes. For example, let's use the UserProfiles table with UserID as the primary key.

Step 2: Set Up Lambda Function
Create a new Lambda function in the AWS Lambda console.

Lambda Function Code:

import json
import boto3

dynamodb = boto3.resource('dynamodb')
table_name = 'UserProfiles'
table = dynamodb.Table(table_name)

def lambda_handler(event, context):
    try:
        # Retrieve data from DynamoDB
        response = table.scan()

        # Extract relevant data
        items = response.get('Items', [])

        # Transform DynamoDB items to a standard Python list
        data = [dict(item) for item in items]

        return {
            'statusCode': 200,
            'body': json.dumps(data)
        }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps(f'Error: {str(e)}')
        }
Enter fullscreen mode Exit fullscreen mode

Lambda Function Configuration:

Set the runtime to Python 3.x.
Add an execution role with DynamoDB read permissions.
Set up an API Gateway trigger for the Lambda function.
Step 3: Set Up API Gateway
Create an API Gateway to act as an endpoint for your Django application to send requests to the Lambda function.

Step 4: Django Application
In your Django application, use the requests library to retrieve data from the API Gateway.

Example Django Code:

import requests

def get_data_from_lambda():
    api_gateway_url = 'YOUR_API_GATEWAY_URL'
    lambda_endpoint = f'{api_gateway_url}/YOUR_RESOURCE_NAME'

    response = requests.get(lambda_endpoint)

    if response.status_code == 200:
        data = response.json()
        return data
    else:
        return None
Enter fullscreen mode Exit fullscreen mode

Replace 'YOUR_API_GATEWAY_URL' with the actual URL of your API Gateway and 'YOUR_RESOURCE_NAME' with the resource name configured in your API Gateway.

Now, when you call get_data_from_lambda() from your Django application, it will trigger the Lambda function to retrieve data from DynamoDB.

Top comments (0)