Unlocking Serverless: Build Your First Python AWS Lambda Function
Niran
Posted on September 20, 2024
Setting Up Your AWS Lambda Function đ
Letâs build something awesome!
Log in to AWS Management Console.
Just type âLambdaâ in the AWS search bar and click on the Lambda service.
On the AWS Lambda dashboard, click âCreate a functionâ.
Choose the âAuthor from scratchâ option.
Why Choose âAuthor from Scratchâ for Your AWS Lambda Function? đ¤
Build it Your Way!: Authoring from scratch gives you complete control over your Lambda functionâs code, settings, and environment. Customize everything to fit your exact needs, from the code itself to how it works with other AWS services and handles different inputs.
Pick Your Language: When you author from scratch, you can choose the runtime that best suits your programming language preference, such as Python, Node.js, or Java. This gives you the power to write code exactly how you like it!
Full Control Over Permissions: Starting from scratch allows you to define or attach IAM roles and policies according to the functionâs needs. AWS provides basic Lambda execution roles by default, but you can customize them for more specific permissions as your function evolves.
No Unnecessary Overhead: Unlike pre-built templates or blueprints, authoring from scratch ensures that no unnecessary code, libraries, or configurationsď¸ are included in your function. This helps keep the function lightweight and optimized for your specific task.
Deep Dive into Serverless: Authoring from scratch is an excellent way to deepen your understanding of AWS Lambda and serverless architecture. By setting up everything manually, you gain insights into how different components interact and how to optimize them for performance and cost.
Give your function a name (e.g., ImageMetadataExtractor, as this is the function we are creating).
Select Python 3.9 (or the latest supported version) as the runtime.
Select the architecture for your Lambda function. Choose** x86_64 **(widely compatible with existing libraries and binaries).
Locate the Execution Role and choose âCreate a new role with basic Lambda permissionsâ option.
Why Choose âCreate a new role with basic Lambda permissionsâ ? đ¤
Choosing the âCreate a new role with basic Lambda permissionsâ option simplifies the setup process for your AWS Lambda function by automatically granting the essential permissions needed for effective operation. This option is ideal for beginners or for those who need a quick setup without complex permission configurations. It allows your Lambda function to log execution results to Amazon CloudWatch, facilitating easy monitoring and troubleshooting. This approach minimizes overhead and lets developers focus on coding, with the flexibility to update permissions later as the applicationâs requirements evolve.
- Advanced Settings: Optional Tweaks for Your Function You can see the Advanced Settings option when creating your Lambda function. While these settings provide valuable features, they are not mandatory for the basic operation of your function. You can choose to enable them based on your specific needs:
Enable Code Signing: Optional, but recommended for enhancing security and code integrity.
Enable Function URL: Useful if you want to expose your function as an HTTP endpoint, but not required if external access is unnecessary.
Enable Tags: While not required, using tags is a best practice for resource management and cost tracking.
Enable VPC: Necessary only if your function needs to access resources within a VPC; otherwise, it can be skipped.
- Click âCreate Functionâ. AWS will create the Lambda function and take you to the functionâs configuration page.
Time to Code! đť
Writing the Python Code
Scroll Down to the Code Source Section:
Youâll see a basic code editor where you can modify the Lambda function code.
AWS Lambda doesnât come pre-equipped with all the tools you might need. Itâs like trying to build a house without a toolbox. Similarly, Lambda requires you to bring along specialized equipment, like the Pillow library, for the function weâre creating.
On your local computer, create a new folder to hold your Lambda function code and dependencies. This will be your project directory. For example, you can create a folder named âlambda_functionâ.
Open your terminal or command prompt and navigate to your project directory. Use the following command to install the Pillow library into your project:
pip install Pillow -t .
Create a new Python file named lambda_function.py in your project directory and also in the Lambda function editor, replace the default code with the following metadata extraction function(lambda_function.py):
from PIL import Image
import json
import io
import base64
def lambda_handler(event, context):
try:
# Decode the base64 image data from the event
image_data = base64.b64decode(event['image_data'])
image = Image.open(io.BytesIO(image_data))
# Extract image metadata
metadata = {
"format": image.format,
"size": image.size,
"mode": image.mode,
"info": image.info
}
return {
'statusCode': 200,
'body': json.dumps(metadata)
}
except Exception as e:
return {
'statusCode': 500,
'body': str(e)
}
This function expertly handles base64-encoded image data. It seamlessly decodes the image, leverages Pillowâs capabilities to extract crucial metadata like format, size, and mode, and returns a JSON response for easy consumption.
After editing the code, click the Deploy button to save and deploy the function.
Ensure your working directory has these essential files and folders:
PIL/
lambda_function.py
pillow-10.4.0.dist-info/
pillow.libs/
Navigate to the directory containing these essential files and folders. Run the following command to create a deployment package:
zip -r9 lambda_function.zip PIL lambda_function.py pillow-10.4.0.dist-info pillow.libs
(This will create a lambda_function.zip file that includes all necessary files and directories.)
In the Code source section, navigate to the Upload from option.
Select the .zip file you carefully created earlier (likely named lambda_function.zip).
Click the Upload from(.zip files) button and browse to select the lambda_function.zip file.
Finally, click Save to update your Lambda function with this powerful new deployment package!
Configuring and Testing a Lambda Function đ
Letâs get your Lambda function up and running!
Verify the Runtime Settings.
Check the Handler setting. It should be set to:
lambda_function.lambda_handler
If itâs not set correctly, click Edit(if available), enter lambda_function.lambda_handler, and then click Save.
Click on the Test button at the function editor.
Create a new test event with a name (e.g., TestImageMetadata).
Select Private to keep the test event available only to you. This ensures that only you can access and use this test event.
Use this sample JSON data to simulate an image:
{
"image_data": "base64-encoded-image-string"
}
Click Save changes to save the test event.
Click Test to execute the Lambda function with the test event.
Review the execution results.
Manage Environment Variables âď¸
Scroll down to the Environment variables section on the Lambda function configuration page.
Click on Edit to modify the environment variables.
Add a new environment variable:
Key: DEFAULT_MODE
Value: RGB
Click Save to apply the changes.
Modify your lambda_function.py code to use the environment variable for the default mode if not specified.
Ensure your code includes error handling with a try-except block:
import os
from PIL import Image
import json
import io
import base64
def lambda_handler(event, context):
try:
# Decode the base64 image data from the event
image_data = base64.b64decode(event['image_data'])
image = Image.open(io.BytesIO(image_data))
# Use environment variable for default mode if not specified
mode = os.getenv('DEFAULT_MODE', image.mode)
# Extract image metadata
metadata = {
"format": image.format,
"size": image.size,
"mode": mode,
"info": image.info
}
return {
'statusCode': 200,
'body': json.dumps(metadata)
}
except Exception as e:
return {
'statusCode': 500,
'body': str(e)
}
This code will flexibly use the value of the DEFAULT_MODE environment variable if a specific mode isn't provided in the input data.
Go to the Test tab of the Lambda function.
Click Test to invoke your Lambda function with the new code.
Ensure that the test event is set up correctly and reflects the changes made.
View Logs in CloudWatch đ
Click on the Monitor tab. Click on View logs in CloudWatch to see the execution logs. Review the logs for any errors or successful executions.
Note: For example, Iâve used an image metadata extractor code, but you can easily replace it with any Python code you need. Whether youâre building AI models, automating tasks, or creating custom tools, this setup with AWS Lambda and S3 is incredibly flexible.
Enjoy the process! đ
Posted on September 20, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.