[AWS] Lambda with Python

This post shows variable small examples of Lambda functions to demonstrate how you can do with Lambda. The choice of language is Python but it is easy to migrate to other programming languages.


Accessing Path & Query Strings

When you integrate your Lambda function with a Gateway API endpoint, you can access query strings in Lambda like this.

import json

def lambda_handler(event, context):
    print("event: ", event)
    
    name = event["pathParameters"]["name"]
    timeOfDay = event["queryStringParameters"]["time"].lower()

    greeting = f"Hello, {name}. Good {timeOfDay}."
    
    return {
        'statusCode': 200,
        'body': json.dumps(greeting)
    }


Using S3 Trigger

The following example shows how to handle the S3 event when an object is uploaded.

import json
import urllib.parse
import boto3

s3 = boto3.client('s3')

def lambda_handler(event, context):
    # print("Received event: " + json.dumps(event, indent=2))
    
    # bucket
    bucketName = event['Records'][0]['s3']['bucket']['name']
    bucketArn = event['Records'][0]['s3']['bucket']['arn']
    print('bucket:', bucketName + ', ' + bucketArn)
    
    # object
    objectKey = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
    objectSize = event['Records'][0]['s3']['object']['size']
    print('object:', objectKey + ', ' + str(objectSize) + ' bytes')
 

Leave a Comment