Here are three examples of AWS Lambda functions for different use cases. These include the hello world function, image resizing, and fetching data from DynamoDB.

3 Easy to Write Lambda Functions in AWS
Photo by Tara Winstead on Pexels.com

1. Basic Hello World Function

This is a simple AWS Lambda function that returns a “Hello, World!” message. It’s often used in the AWS Lambda to understand the basics.

def lambda_handler(event, context):
return {
'statusCode': 200,
'body': 'Hello, World!'
}

2. Image Resizing Function

This function resizes an image uploaded to an S3 bucket. When an image is uploaded, the Lambda function is triggered, resizes it, and stores it in a different S3 bucket.

import boto3
from PIL import Image
import io

s3_client = boto3.client('s3')

def lambda_handler(event, context):
source_bucket = event['Records'][0]['s3']['bucket']['name']
source_key = event['Records'][0]['s3']['object']['key']
target_bucket = 'resized-images-bucket'
target_key = 'resized-' + source_key

# Download image from S3
response = s3_client.get_object(Bucket=source_bucket, Key=source_key)
image_content = response['Body'].read()

# Resize image
image = Image.open(io.BytesIO(image_content))
image = image.resize((100, 100)) # Resize to 100x100 pixels

# Convert image to bytes
buffer = io.BytesIO()
image.save(buffer, 'JPEG')
buffer.seek(0)

# Upload the resized image back to S3
s3_client.put_object(Bucket=target_bucket, Key=target_key, Body=buffer)

return {
'statusCode': 200,
'body': f'Resized image saved to {target_bucket}/{target_key}'
}

Explanation: Event JSON

{
"Records": [
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
"awsRegion": "us-west-2",
"eventTime": "2024-09-08T12:34:56.789Z",
"eventName": "ObjectCreated:Put",
"s3": {
"bucket": {
"name": "source-bucket-name"
},

"object": {
"key": "path/to/your/object.jpg",
"size": 12345

}
}
}
]
}

event['Records'][0]: This accesses the first record in the Records array of the event object. If various objects trigger the Lambda function simultaneously, but we are accessing the first one with [0].

event['Records'][0]['s3']['bucket']['name']:

  • event: The event data passed to the Lambda function.
  • [‘Records’]: The list of records contained in the event.
  • [0]: Accesses the first record in the list.
  • [‘s3’]: This part of the event object contains details about the S3 service.
  • [‘bucket’]: This nested JSON object contains bucket information that triggered the event.
  • [‘name’]: The name of the S3 bucket. This is where the object was created or modified.

The line source_bucket = event['Records'][0]['s3']['bucket']['name'] stores the name of the S3 bucket that triggered the event in the variable source_bucket.

event['Records'][0]['s3']['object']['key']:

  • [‘object’]: This nested JSON object contains details about the S3 object that triggered the event.
  • [‘key’]: The key (file path) of the S3 object that was created, modified, or deleted.

The line source_key = event['Records'][0]['s3']['object']['key'] stores the key (file path) of the object in the variable source_key.

{
"Records": [
{
"s3": {
"bucket": {
"name": "my-image-bucket"
},
"object": {
"key": "uploads/new_image.jpg"
}
}
}
]
}

When the Lambda function executes:

  • source_bucket will be "my-image-bucket".
  • source_key will be "uploads/new_image.jpg".

This allows the Lambda function to identify which object triggered it and where it is located within the S3 bucket.

Note: You noticed a way to examine JSON content within the Lambda function. You can find the same way of accessing JSON data in the production projects.

3. API Gateway Integration: Fetching Data from a DynamoDB Table

This function is designed to be triggered by an API Gateway HTTP request to fetch data from a DynamoDB table.

import boto3
import json

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('YourDynamoDBTableName')

def lambda_handler(event, context):
# Fetching all items from DynamoDB table
try:
response = table.scan()
items = response.get('Items', [])

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

except Exception as e:
return {
'statusCode': 500,
'body': json.dumps({'error': str(e)})
}

These lambda functions cover AWS service integration, image processing, and database queries.

Read more