Skip to main content

Python AWS Lambda: Getting Started Guide

Python AWS Lambda is a serverless compute service that lets you run Python code on AWS infrastructure without managing servers. You write a function, upload it to Lambda, and AWS automatically scales, executes, and bills you only for the time your code runs—measured in milliseconds. As of 2026, Lambda supports Python 3.12 and earlier, making it ideal for rapid development of microservices, data pipelines, and API backends.

What is AWS Lambda and How Does It Work?

AWS Lambda is an event-driven compute service. You package Python code, set memory allocation (128 MB to 10.24 GB), and Lambda automatically scales from zero to thousands of concurrent executions. Execution time is metered to the nearest millisecond, with a free tier of 1 million invocations and 400,000 GB-seconds per month. Unlike traditional servers, you don't pay for idle time—only for actual execution.

The service integrates with over 100 AWS services: API Gateway, S3, DynamoDB, SNS, SQS, CloudWatch Events, and others. When an event occurs (e.g., a file uploaded to S3), Lambda automatically invokes your function with that event data as input.

Step 1: Set Up Your AWS Account and IAM Role

Visit https://aws.amazon.com and create a free account if you don't have one. AWS grants new accounts 12 months of free tier benefits, including Lambda invocations and generous compute allowances. Verify your email and payment method (no charges during the free trial).

Next, set up an IAM role—the credentials that allow Lambda to execute and access other AWS services. In the AWS Management Console:

  1. Navigate to IAMRolesCreate Role
  2. Choose AWS Service, then Lambda
  3. Attach the policy AWSLambdaBasicExecutionRole (enables CloudWatch Logs)
  4. Name it lambda-basic-execution and create it
  5. Copy the role ARN (looks like arn:aws:iam::123456789012:role/lambda-basic-execution)

This role is required for every Lambda function and is the foundation of production deployments.

Step 2: Create Your First Lambda Function in the Console

In the Lambda Console:

  1. Click Create Function
  2. Choose Author from scratch
  3. Set:
    • Function name: my-first-function
    • Runtime: Python 3.12
    • Architecture: x86_64 (standard, widely supported)
    • Execution role: Use an existing role → select lambda-basic-execution
  4. Click Create Function

You now have a default Python 3.12 function with a simple "Hello from Lambda" handler. The inline editor shows:

import json

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

This is a complete, runnable function. The lambda_handler is the entry point—Lambda calls this when invoked.

Step 3: Test Your Function

In the Lambda Console:

  1. Click Test (top-right)
  2. Create a test event:
    • Event name: test-event
    • Event template: hello-world (pre-filled with minimal JSON {})
  3. Click Save then Test

The Execution result tab shows:

  • Status: Succeeded
  • Duration: ~5–15 ms
  • Billed Duration: 1000 ms (minimum chunk; Lambda bills in 1 ms increments after the first 1 second)
  • Memory Used: ~30 MB out of 128 MB allocated

The function response displays: { "statusCode": 200, "body": "\"Hello from Lambda!\"" }. Success!

Understanding Lambda Execution Context

When Lambda invokes your function, it passes two arguments:

  • event: A dictionary containing data from the triggering service (API Gateway request, S3 bucket event, etc.)
  • context: An object with metadata about the invocation (function name, request ID, remaining time, CloudWatch log group, etc.)

Test this by modifying your function:

import json

def lambda_handler(event, context):
print(f"Function name: {context.function_name}")
print(f"Request ID: {context.aws_request_id}")
print(f"Remaining time: {context.get_remaining_time_in_millis()} ms")

return {
'statusCode': 200,
'body': json.dumps({
'message': 'Hello from Lambda!',
'event_received': event
})
}

Click Deploy (top-right) to update the function code, then Test again. In the Logs section, you'll see your print statements. This demonstrates the execution environment and common debugging pattern.

Invoking Lambda from the AWS CLI

Install the AWS CLI (https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) and configure credentials:

aws configure

Invoke your function:

aws lambda invoke \
--function-name my-first-function \
--payload '{"name": "Alice"}' \
response.json

cat response.json

Output:

{"statusCode": 200, "body": "{\"message\": \"Hello from Lambda!\", \"event_received\": {\"name\": \"Alice\"}}"}

The AWS CLI is essential for automation, CI/CD pipelines, and local testing workflows.

Memory, Timeout, and Concurrency Settings

In the Lambda Console, under Configuration:

  • General: Adjust memory (default 128 MB; impacts CPU allocation and cost). Higher memory = faster execution and higher hourly rate, but reduced total duration often offsets the cost.
  • Timeout: Set how long Lambda allows execution before terminating (default 3 seconds, max 15 minutes). Increase for long-running jobs; decrease for fast APIs.
  • Concurrency: Control how many invocations run simultaneously. Reserved concurrency guarantees capacity; provisioned concurrency pre-warms instances to eliminate cold starts (costs more but critical for user-facing APIs).

For a hello-world function, defaults are fine. For production APIs handling user traffic, increase memory to 512 MB and set timeout to 30 seconds.

Key Takeaways

  • AWS Lambda is a serverless platform that automatically scales and charges only for execution time.
  • IAM roles are required; use AWSLambdaBasicExecutionRole for basic logging.
  • Create functions via the Console, AWS CLI, or Infrastructure-as-Code tools (covered later).
  • The lambda_handler(event, context) function is the entry point; event contains trigger data, context provides metadata.
  • Test in the Console or via AWS CLI for rapid iteration.
  • Configure memory, timeout, and concurrency based on workload; defaults suit simple functions, but production workloads need tuning.

Frequently Asked Questions

What is the AWS Lambda free tier?

AWS grants 1 million free invocations and 400,000 GB-seconds of compute per month, plus CloudWatch Logs storage. A typical hello-world function uses ~30 MB for ~5 ms, costing under 1 unit. You can explore Lambda extensively without charges.

Do I need to install Python to use Lambda?

No. Lambda is managed by AWS. You write Python code in the console editor or upload a ZIP file; Lambda handles the Python runtime. Your local machine is needed only for development and testing—Lambda runs the actual code on AWS infrastructure.

How do I pass environment variables to my function?

In the Lambda Console, go to ConfigurationEnvironment variables and add key-value pairs. Access them in code via import os; os.environ['MY_VAR']. This is safer than hardcoding credentials.

Can I use third-party Python libraries like requests or numpy?

Yes, but they must be included in your deployment package (ZIP file or Docker image). The default console editor does not support external dependencies. See the Lambda Layers article for dependency management strategies.

What happens if my function takes longer than the timeout?

Lambda terminates the function and returns a timeout error. Always set timeout conservatively: for API responses, 30 seconds; for batch jobs, 5+ minutes. Monitor CloudWatch Logs to detect slow patterns.

Further Reading