DEV Community

Niran
Niran

Posted on

Unlocking Serverless: Build Your First Python AWS Lambda Function

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.
    Image description

  • On the AWS Lambda dashboard, click “Create a function”.

  • Choose the “Author from scratch” option.

Image description

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).
    Image description

  • Locate the Execution Role and choose “Create a new role with basic Lambda permissions” option.
    Image description

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.

Image description

  • Click “Create Function”. AWS will create the Lambda function and take you to the function’s configuration page. Image description

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 .
Enter fullscreen mode Exit fullscreen mode

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)
        }
Enter fullscreen mode Exit fullscreen mode

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.

Image description

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/
Enter fullscreen mode Exit fullscreen mode

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.)
Enter fullscreen mode Exit fullscreen mode

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!

Image description

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
Enter fullscreen mode Exit fullscreen mode

If it’s not set correctly, click Edit(if available), enter lambda_function.lambda_handler, and then click Save.

Image description

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"
}
Enter fullscreen mode Exit fullscreen mode

Image description

Click Save changes to save the test event.

Click Test to execute the Lambda function with the test event.

Review the execution results.

Image description

Manage Environment Variables ⚙️
Scroll down to the Environment variables section on the Lambda function configuration page.

Image description

Click on Edit to modify the environment variables.

Add a new environment variable:

Key: DEFAULT_MODE
Value: RGB

Image description

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)
        }
Enter fullscreen mode Exit fullscreen mode

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! 😊

Top comments (0)