AWS Lambda Function Tutorial

AWS Lambda Function Tutorial


1. Basic Lambda Function

Example 1: Hello World Lambda

import json

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from AWS Lambda!')
    }

Explanation

  1. Imports the JSON module to format responses.

    • import json
  2. Defines the Lambda function entry point.

    • def lambda_handler(event, context):
  3. Returns an HTTP response with a 200 status.

    • return {'statusCode': 200, 'body': json.dumps('Hello from AWS Lambda!')}
  4. AWS automatically executes this function when triggered.

    • lambda_handler(event, context)

Example 2: Returning Event Data

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': json.dumps(event)
    }

Explanation

  1. Receives an event from AWS services.

    • def lambda_handler(event, context):
  2. Sends the event data back in the response.

    • 'body': json.dumps(event)
  3. Ensures the response is JSON formatted.

    • json.dumps(event)
  4. Useful for debugging event structures.

    • return {...}

Example 3: Returning Custom Headers

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps({'message': 'Custom headers added'})
    }

Explanation

  1. Adds a custom response header.

    • 'headers': {'Content-Type': 'application/json'}
  2. Returns a JSON response with custom data.

    • 'body': json.dumps({'message': 'Custom headers added'})
  3. Ensures proper HTTP status codes.

    • 'statusCode': 200
  4. Useful when integrating with REST APIs.

    • lambda_handler(event, context)

Example 4: Using Query Parameters

def lambda_handler(event, context):
    name = event.get('queryStringParameters', {}).get('name', 'Guest')
    return {
        'statusCode': 200,
        'body': json.dumps(f'Hello, {name}!')
    }

Explanation

  1. Extracts query parameters from the event.

    • name = event.get('queryStringParameters', {}).get('name', 'Guest')
  2. Defaults to ‘Guest’ if no parameter is provided.

    • .get('name', 'Guest')
  3. Returns a dynamic greeting message.

    • 'body': json.dumps(f'Hello, {name}!')
  4. Useful for API Gateway requests.

    • lambda_handler(event, context)

2. AWS Lambda with DynamoDB

Example 1: Insert Data into DynamoDB

import boto3

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

def lambda_handler(event, context):
    table.put_item(Item={'UserID': event['UserID'], 'Name': event['Name']})
    return {'statusCode': 200, 'body': 'User added'}

Explanation

  1. Connects AWS Lambda to DynamoDB.

    • dynamodb = boto3.resource('dynamodb')
  2. Gets reference to the Users table.

    • table = dynamodb.Table('Users')
  3. Inserts user data into the table.

    • table.put_item(Item={'UserID': event['UserID'], 'Name': event['Name']})
  4. Confirms successful insertion.

    • return {'statusCode': 200, 'body': 'User added'}

Example 2: Fetch Data from DynamoDB

def lambda_handler(event, context):
    response = table.get_item(Key={'UserID': event['UserID']})
    return {'statusCode': 200, 'body': json.dumps(response.get('Item', 'User not found'))}

Explanation

  1. Fetches an item from DynamoDB using UserID.

    • response = table.get_item(Key={'UserID': event['UserID']})
  2. Returns the retrieved item if it exists.

    • json.dumps(response.get('Item', 'User not found'))
  3. Handles missing users gracefully.

    • response.get('Item', 'User not found')
  4. Useful for API-based retrieval operations.

    • return {'statusCode': 200, 'body': ...}

Example 3: Update an Item in DynamoDB

def lambda_handler(event, context):
    table.update_item(
        Key={'UserID': event['UserID']},
        UpdateExpression="set Name=:n",
        ExpressionAttributeValues={':n': event['Name']}
    )
    return {'statusCode': 200, 'body': 'User updated'}

Explanation

  1. Updates user data using an expression.

    • UpdateExpression="set Name=:n"
  2. Uses ExpressionAttributeValues to avoid injection.

    • ExpressionAttributeValues={':n': event['Name']}
  3. Ensures atomic updates without overwriting all fields.

    • table.update_item(...)
  4. Confirms the update in response.

    • return {'statusCode': 200, 'body': 'User updated'}

Example 4: Delete a User from DynamoDB

def lambda_handler(event, context):
    table.delete_item(Key={'UserID': event['UserID']})
    return {'statusCode': 200, 'body': 'User deleted'}

Explanation

  1. Deletes a user record from DynamoDB.

    • table.delete_item(Key={'UserID': event['UserID']})
  2. Ensures efficient deletion using the primary key.

    • delete_item(Key={'UserID': event['UserID']})
  3. Reduces storage usage by removing old records.

    • return {'statusCode': 200, 'body': 'User deleted'}
  4. Useful for user account removals.

    • lambda_handler(event, context)

3. AWS Lambda with S3

Example 1: Upload File to S3

import boto3

s3 = boto3.client('s3')

def lambda_handler(event, context):
    s3.upload_file('/tmp/sample.txt', 'my-bucket', 'sample.txt')
    return {'statusCode': 200, 'body': 'File uploaded'}

Explanation

  1. Creates an S3 client for interacting with AWS S3.

    • s3 = boto3.client('s3')
  2. Uploads a file from Lambda to S3.

    • s3.upload_file('/tmp/sample.txt', 'my-bucket', 'sample.txt')
  3. Uses ‘/tmp/’ for temporary Lambda storage.

    • '/tmp/sample.txt'
  4. Returns a success message after upload.

    • return {'statusCode': 200, 'body': 'File uploaded'}

Example 2: Read File from S3

def lambda_handler(event, context):
    obj = s3.get_object(Bucket='my-bucket', Key='sample.txt')
    return {'statusCode': 200, 'body': obj['Body'].read().decode('utf-8')}

Explanation

  1. Fetches a file from S3 storage.

    • s3.get_object(Bucket='my-bucket', Key='sample.txt')
  2. Reads the file content into memory.

    • obj['Body'].read().decode('utf-8')
  3. Decodes UTF-8 to make it human-readable.

    • .decode('utf-8')
  4. Returns the file content as a response.

    • return {'statusCode': 200, 'body': ...}