AWS Lambda Tutorial: Mastering Serverless with Python & Boto3 - Complete Guide to Building and Managing Lambda Functions
AWS Lambda is one of the easiest ways to build serverless applications on AWS. You don’t need to set up or maintain servers — AWS does it for you. In this tutorial, we’ll start simple and build our way up. This tutorial walks you through everything — writing your first Lambda function, deploying it, automating it with Boto3, and working with advanced features like environment variables and triggers. Let’s get started.
Normally, you rent or own a server. That server stays on all the time, even if nobody is using it.
With AWS Lambda, there’s no always-on server.
A trigger is simply an event that tells AWS Lambda: “run this code now.”
You don’t have to:
No server management
You don’t need to think about servers at all. AWS gives you an empty space where your code runs.
Pay per execution
Instead of paying for a server that sits idle, you only pay when your code actually runs.
Example:
Automatic scaling
If one user runs your code, AWS runs one instance.
If 10,000 users run it at the same time, AWS automatically runs thousands of instances in parallel — no setup needed from you.
Before writing any Python code or using Boto3, you need to prepare your system with the right tools.
Open your terminal or command prompt and run:
pip install awscli
After installation, configure your credentials:
aws configure
You’ll be prompted to enter:
us-east-1)json)This securely saves your credentials on your system so Boto3 and AWS CLI can use them.
Run:
pip install boto3
Boto3 is the official Python SDK for AWS services, including Lambda.
aws --versionpython --versionimport boto3 print("Boto3 is ready!")At this point, your environment is fully prepared to start creating and managing AWS Lambda functions with Python and Boto3.
You’re going to create a small program on AWS called a Lambda function. When you press a button, AWS will run it and give you the output.
Think of it as making a tiny program in the cloud that says “Hello from Lambda!”
You’ll see a big button called Create function. Click it.
On the page that appears:
hello_lambda.This creates an empty Lambda function for you.
On the next page, you’ll see a section called Code source or Code editor.
Delete anything that’s already there and paste this code:
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': 'Hello from Lambda!'
}
This is a tiny Python function. AWS will run this whenever you “invoke” it.
Click the Deploy button above the editor to save your code.
test1 and click Save.AWS will run your Lambda function and show the result at the bottom of the page:
{
"statusCode": 200,
"body": "Hello from Lambda!"
}
That’s AWS running your code and giving you the response.
You now have a working Lambda function in your account.
We are going to write our Lambda function on our own computer first, then upload it to AWS Lambda.
When you use the AWS Console, you’re typing directly in the browser.
But in real projects, you want your code saved on your computer. This allows version control (Git), testing locally, and easier editing.
On your computer, open any folder.
Create a new file named lambda_function.py.
Inside it, paste this code:
def lambda_handler(event, context):
name = event.get('name', 'World') # If 'name' not provided, default is 'World'
return {
'statusCode': 200,
'body': f'Hello {name}!'
}
This is your Lambda function.
event = input AWS sends (like JSON data).context = info about the runtime.AWS Lambda wants your code uploaded as a .zip file.
In your terminal (Command Prompt, PowerShell, or Linux terminal), run:
zip function.zip lambda_function.py
Now you have function.zip containing your code.
(This step literally zips your file.)
You can upload it in two ways:
hello_lambda_cli.function.zip.Run this command in your terminal:
aws lambda create-function \
--function-name hello_lambda_cli \
--runtime python3.9 \
--role arn:aws:iam::<your-account-id>:role/<lambda-execution-role> \
--handler lambda_function.lambda_handler \
--zip-file fileb://function.zip
Here:
--function-name = name of your Lambda.--runtime = Python version.--role = IAM role ARN (permissions for Lambda to run).--handler = entry point to your code.--zip-file = your zipped code file.After uploading, go to AWS Lambda Console → your function → Test.
Input:
{
"name": "Emmimal"
}
Output will be:
{
"statusCode": 200,
"body": "Hello Emmimal!"
}Example:
lambda_client.create_function(...) from Python.This is great for automation and large-scale projects.
In your terminal (Command Prompt, PowerShell, or Linux shell):
pip install boto3
If it already says “Requirement already satisfied” — you’re good.
In your Python script, at the top:
import boto3
This lets you use AWS services via Python code.
Then you create a client for a service. For Lambda:
lambda_client = boto3.client('lambda')
Now lambda_client can create, update, delete, or invoke Lambda functions programmatically.
Up until now, you:
With Boto3, you can:
We will learn how to create, run, update, and delete Lambda functions using Python.
aws configure Enter: AWS Access Key, Secret Key, Region, output format.pip install boto3Create a file called lambda_function.py:
def lambda_handler(event, context):
name = event.get('name', 'World') # If no name given, default is 'World'
return {
'statusCode': 200,
'body': f'Hello {name}!'
}
Explanation:
lambda_handler is the function AWS will run.event contains input data.context contains AWS runtime info (we don’t use it here)."Hello Emmimal!".Lambda needs the code in a .zip file:
zip function.zip lambda_function.py
This creates function.zip that contains your code.
Create a new Python file, for example manage_lambda.py:
import boto3
# Connect to AWS Lambda
lambda_client = boto3.client('lambda')
# Read the zipped Lambda code
with open('function.zip', 'rb') as f:
zipped_code = f.read()
# Create the Lambda function
response = lambda_client.create_function(
FunctionName='hello_lambda_boto3', # Name of your Lambda
Runtime='python3.9', # Python version
Role='arn:aws:iam::<your-account-id>:role/<lambda-execution-role>', # IAM role
Handler='lambda_function.lambda_handler', # File.function_name
Code={'ZipFile': zipped_code}, # Upload zipped code
Timeout=15, # Max time Lambda can run
MemorySize=128, # Memory in MB
Publish=True # Make it live immediately
)
print("Lambda Created:")
print(response)
What this does:
Add this to the same file or a new file:
import boto3
lambda_client = boto3.client('lambda')
# Call the Lambda function
response = lambda_client.invoke(
FunctionName='hello_lambda_boto3', # Lambda name
InvocationType='RequestResponse', # Wait for the response
Payload=b'{"name":"Emmimal"}' # Input data
)
# Read and print the output
print(response['Payload'].read().decode('utf-8'))
Output:
{"statusCode": 200, "body": "Hello Emmimal!"}
If you change lambda_function.py, zip it again, then run:
import boto3
lambda_client = boto3.client('lambda')
with open('function.zip', 'rb') as f:
zipped_code = f.read()
lambda_client.update_function_code(
FunctionName='hello_lambda_boto3',
ZipFile=zipped_code,
Publish=True
)
print("Lambda Code Updated")
Explanation:
import boto3
lambda_client = boto3.client('lambda')
lambda_client.delete_function(FunctionName='hello_lambda_boto3')
print("Lambda Deleted")
Explanation:
| Action | Boto3 Method | What it does |
|---|---|---|
| Create | create_function() | Uploads code and makes Lambda |
| Invoke | invoke() | Runs Lambda with input data |
| Update | update_function_code() | Replace old Lambda code |
| Delete | delete_function() | Removes Lambda completely |
Environment variables are key-value pairs you can store in your Lambda function.
Use them for:
You can set them with update_function_configuration():
import boto3
lambda_client = boto3.client('lambda')
lambda_client.update_function_configuration(
FunctionName='hello_lambda_boto3',
Environment={
'Variables': {
'STAGE': 'dev',
'API_KEY': '12345'
}
}
)
print("Environment variables set!")
Explanation:
STAGE → environment name, e.g., “dev” or “prod”API_KEY → secret key or any configuration valueInside your lambda_function.py, use Python’s os.environ:
import os
def lambda_handler(event, context):
stage = os.environ.get('STAGE', 'default') # Get the STAGE variable
api_key = os.environ.get('API_KEY', 'none') # Get API_KEY variable
return {
'stage': stage,
'api_key': api_key
}
Explanation:
os.environ.get('KEY', 'default') reads the variableIf you set:
STAGE = dev
API_KEY = 12345
And run your Lambda function, the output will be:
{
"stage": "dev",
"api_key": "12345"
}
Why This Is Useful:
Lambda functions run inside AWS, but they cannot automatically access other AWS services like S3, DynamoDB, or SNS.
An IAM role is like a special ID card for your Lambda function.
It tells AWS what the Lambda is allowed to do, for example:
When you create a Lambda, you attach a role to it to grant the necessary permissions.
lambda_s3_readonly_roleRole='arn:aws:iam::<your-account-id>:role/lambda_s3_readonly_role'
Now the Lambda function can read from S3 buckets but cannot write to them.
| Policy Name | Purpose |
|---|---|
| AmazonS3ReadOnlyAccess | Read files from S3 |
| AmazonDynamoDBFullAccess | Read/write DynamoDB tables |
| AmazonSNSFullAccess | Publish messages to SNS |
| CloudWatchLogsFullAccess | Write logs to CloudWatch |
When creating a Lambda function with Boto3:
response = lambda_client.create_function(
FunctionName='hello_lambda_boto3',
Runtime='python3.9',
Role='arn:aws:iam::<your-account-id>:role/lambda_s3_readonly_role',
Handler='lambda_function.lambda_handler',
Code={'ZipFile': zipped_code},
)
Role specifies what permissions the Lambda has.Always attach minimal permissions required by the Lambda function.
This reduces security risks and keeps your AWS account safe.
A trigger is something that tells your Lambda when to run automatically.
Without a trigger, Lambda will only run if you manually invoke it.
Scenario: You want your Lambda to say “Hello” every time someone uploads a file to S3.
hello_lambda_boto3).Now: Every time someone uploads a file to that bucket, your Lambda runs automatically.
import json
def lambda_handler(event, context):
# event contains info about the file uploaded
file_name = event['Records'][0]['s3']['object']['key']
bucket_name = event['Records'][0]['s3']['bucket']['name']
print(f"File {file_name} uploaded to bucket {bucket_name}")
return {
'statusCode': 200,
'body': json.dumps(f"Processed {file_name} from {bucket_name}")
}
event is automatically sent by S3 to Lambda.Scenario: You want your Lambda to run every hour, like a scheduled task.
rate(1 hour) (runs every hour).Now: Lambda runs automatically every hour.
def lambda_handler(event, context):
print("Lambda ran on schedule!")
return {"statusCode": 200, "body": "Scheduled Lambda executed"}
Scenario: You want to call your Lambda function by visiting a web URL.
/hello.Now: Visiting the URL triggers your Lambda.
def lambda_handler(event, context):
name = event.get("queryStringParameters", {}).get("name", "World")
return {"statusCode": 200, "body": f"Hello {name}!"}
https://<api-id>.execute-api.<region>.amazonaws.com/hello?name=Emmimal"Hello Emmimal!"| Trigger Type | When Lambda Runs | Example |
|---|---|---|
| S3 Event | When a file is uploaded | Process uploaded file |
| CloudWatch | On a schedule | Run hourly reports |
| API Gateway | When someone calls a URL | Web API endpoint |
requests, pandas, numpy), you can’t just pip install inside Lambda.mkdir python
pip install requests -t python/
-t python/ installs the library into the python folder.zip -r layer.zip python
layer.zip will contain your dependencies.requests-layer.layer.zip.Now your Lambda can use the libraries in the layer.
Example Lambda function using requests:
import requests
def lambda_handler(event, context):
response = requests.get("https://api.github.com")
return {
'statusCode': 200,
'body': response.text[:200] # return first 200 characters
}
requests library is not installed in Lambda by default.Lambda functions don’t run on your computer; they run on AWS servers. To see what’s happening inside your code, you need logs. To track performance, you need metrics. AWS gives us CloudWatch for both.
You can use Python’s built-in logging module to print messages to CloudWatch Logs.
import logging
# Create a logger object
logger = logging.getLogger()
logger.setLevel(logging.INFO) # We want info-level messages
def lambda_handler(event, context):
logger.info("Lambda function started") # Log message at start
# Example processing
name = event.get("name", "World")
logger.info(f"Processing request for {name}") # Log the input
response = {"message": f"Hello {name}!"}
logger.info(f"Response generated: {response}") # Log the output
return {"statusCode": 200, "body": response}
Explanation:
logger.info() sends messages to CloudWatch Logs.logger.error() for errors or logger.warning() for warnings./aws/lambda/hello_lambda_boto3).You will see something like this:
START RequestId: 12345 Version: $LATEST
Lambda function started
Processing request for Emmimal
Response generated: {'message': 'Hello Emmimal!'}
END RequestId: 12345
REPORT RequestId: 12345 Duration: 45.00 ms Memory: 128 MB
START and END are added by Lambda automatically.logger.info() messages are between them.AWS automatically tracks Lambda performance metrics in CloudWatch:
| Metric Name | Meaning |
|---|---|
| Invocations | How many times the Lambda was called |
| Duration | How long the Lambda ran (ms) |
| Errors | Number of failed executions |
| Throttles | Number of requests rejected due to limits |
By default, when you call a Lambda, your code waits for the result. This is called synchronous invocation.
Sometimes, you want Lambda to run in the background without waiting. This is asynchronous invocation.
import boto3
lambda_client = boto3.client('lambda')
# Asynchronous call
response = lambda_client.invoke(
FunctionName='hello_lambda_boto3',
InvocationType='Event', # Event = asynchronous
Payload=b'{"name":"Emmimal"}'
)
print("Lambda triggered asynchronously")
InvocationType='Event' tells AWS: don’t wait for a response.Lambda can scale automatically. Concurrency controls how many Lambda instances run at the same time.
lambda_client.put_function_concurrency(
FunctionName='hello_lambda_boto3',
ReservedConcurrentExecutions=5 # max 5 instances at once
)
Sometimes Lambda fails to process an event.
Example DLQ setup is usually done in the console or via Boto3 like this:
lambda_client.update_function_configuration(
FunctionName='hello_lambda_boto3',
DeadLetterConfig={
'TargetArn': 'arn:aws:sqs:<region>:<account-id>:my-dlq'
}
)
Step Functions let you combine multiple Lambda functions into a workflow.
This allows complex applications without writing complicated code in a single Lambda.
| Feature | Purpose |
|---|---|
| Asynchronous Invocation | Run Lambda in background without waiting for response |
| Concurrency | Limit or control how many instances run simultaneously |
| Dead Letter Queue (DLQ) | Capture failed events for debugging |
| Step Functions | Combine multiple Lambdas into a workflow with state management |
STAGE without touching code.import os
def lambda_handler(event, context):
stage = os.environ.get('STAGE', 'dev')
return {"stage": stage}
# Publish a new version via Boto3
lambda_client.publish_version(FunctionName='hello_lambda_boto3')
requests or pandas.mkdir python
pip install requests -t python/
zip -r layer.zip python
layer.zip to Lambda Layers and attach it to functions.Following these practices keeps your Lambda functions efficient, maintainable, and secure.
We’ve covered everything from basic to advanced AWS Lambda with Boto3 and Python.
You learned how to:
With this knowledge, you can confidently build and manage serverless applications on AWS.
1. What is AWS Lambda primarily used for?
2. Which Python library is used to manage AWS Lambda programmatically?
3. Which event can trigger a Lambda function?
4. How do you pass configuration values to a Lambda function?
5. What does the `InvocationType=’Event’` do in Boto3?
6. Which AWS service is commonly used to monitor Lambda logs?
7. Which file format is used to upload Python code to Lambda?
8. How do you attach additional Python libraries to Lambda?
9. Which of the following controls the max number of simultaneous Lambda executions?
10. Which Lambda property defines the function entry point?
AWS Lambda is a serverless computing service that lets you run code without managing servers. You only pay for the compute time your code uses.
You can create a Lambda function either through the AWS Management Console or programmatically using Python and Boto3. Define a handler function, package your code as a ZIP file, and upload it to AWS Lambda.
Boto3 is the AWS SDK for Python. It allows you to programmatically create, update, invoke, and manage AWS Lambda functions directly from Python scripts.
Lambda can be triggered by various AWS services, such as:
S3 (file uploads)
API Gateway (HTTP requests)
CloudWatch Events (scheduled tasks)
DynamoDB streams
Environment variables allow you to store configuration settings or secrets outside of your code. You can access them in Python using os.environ.get('VARIABLE_NAME').
Use Lambda Layers to include external Python libraries. Package your libraries in a ZIP file and attach the layer to your Lambda function.
Synchronous (RequestResponse): Waits for the function to finish and returns the result immediately.
Asynchronous (Event): Invokes the function and returns immediately without waiting for completion.
AWS Lambda integrates with CloudWatch Logs and CloudWatch Metrics. You can track execution duration, error count, memory usage, and logs for debugging.
Reserved concurrency allows you to control the maximum number of simultaneous executions of a Lambda function. This prevents your function from overloading other resources.
Yes! Lambda can read/write to S3, DynamoDB, RDS, SNS, SQS, and more, provided its IAM execution role has the required permissions.
After debugging production systems that process millions of records daily and optimizing research pipelines that…
The landscape of Business Intelligence (BI) is undergoing a fundamental transformation, moving beyond its historical…
The convergence of artificial intelligence and robotics marks a turning point in human history. Machines…
The journey from simple perceptrons to systems that generate images and write code took 70…
In 1973, the British government asked physicist James Lighthill to review progress in artificial intelligence…
Expert systems came before neural networks. They worked by storing knowledge from human experts as…
This website uses cookies.