---
title: "AWS: 3 Easy to Write Lambda Functions"
description: "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. Photo by Tara Winstead on Pexels...."
url: https://srinimf.com/2024/09/08/aws-3-easy-to-write-lambda-functions/
date: 2024-09-08
modified: 2026-10-10
author: "Srini"
image: https://i0.wp.com/srinimf.com/wp-content/uploads/2024/09/image-1.png?fit=1024%2C768&ssl=1
categories: ["AWS"]
tags: ["AWS Lambda functions"]
type: post
lang: en
---

# AWS: 3 Easy to Write Lambda Functions

Here are three examples of [AWS Lambda](https://srinimf.com/2024/10/15/aws-lambda-vs-step-functions-key-differences-explained/) 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](https://i0.wp.com/srinimf.com/wp-content/uploads/2024/09/pexels-photo-7663160.jpeg?resize=1880%2C1253&ssl=1)*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

[AWS Lambda Best Practices](https://srinimf.com/2024/09/08/aws-3-easy-to-write-lambda-functions/aws-lambda-best-practices/)[Download](https://srinimf.com/wp-content/uploads/2024/09/aws-lambda-best-practices.pdf)

### Share this:

-
- [Tweet](https://twitter.com/share)
- [![](https://i0.wp.com/assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_20.png)](https://www.pinterest.com/pin/create/link/?url=https%3A%2F%2Fsrinimf.com%2F2024%2F09%2F08%2Faws-3-easy-to-write-lambda-functions%2F&media=https%3A%2F%2Fi0.wp.com%2Fsrinimf.com%2Fwp-content%2Fuploads%2F2024%2F09%2Fimage-1.png%3Ffit%3D1024%252C768%26ssl%3D1&description=AWS%3A%203%20Easy%20to%20Write%20Lambda%20Functions)
-
- [Share on Tumblr](https://www.tumblr.com/share)
- [Share on WhatsApp (Opens in new window) WhatsApp](https://srinimf.com/2024/09/08/aws-3-easy-to-write-lambda-functions/?share=jetpack-whatsapp)
- [More](#)
-

- [Print (Opens in new window) Print](https://srinimf.com/2024/09/08/aws-3-easy-to-write-lambda-functions/?share=print)
- [Share on Reddit (Opens in new window) Reddit](https://srinimf.com/2024/09/08/aws-3-easy-to-write-lambda-functions/?share=reddit)
- [Share on Telegram (Opens in new window) Telegram](https://srinimf.com/2024/09/08/aws-3-easy-to-write-lambda-functions/?share=telegram)
- [Email a link to a friend (Opens in new window) Email](mailto:?subject=%5BShared%20Post%5D%20AWS%3A%203%20Easy%20to%20Write%20Lambda%20Functions&body=https%3A%2F%2Fsrinimf.com%2F2024%2F09%2F08%2Faws-3-easy-to-write-lambda-functions%2F&share=email)
-

### Like this:

Like Loading…
