

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: AWS Lambda
incomplete
2: Deploy Lambda
incomplete
3: Testing Lambda Functions
incomplete
4: API Gateway
incomplete
5: CloudWatch Log Groups and Viewing Lambda Logs
incomplete
6: Other Lambda Use Cases
incomplete
7: Final Cleanup
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
AWS Lambda handlers in Python are just functions that:
event (input data)In other words, we don't worry about the runtime, the server, or even any sort of HTTP library. We just write a function that accepts an event object and returns a response object.
The process to create a new Lambda function is simple:
Create and deploy patientping-ip-function with role patientping-lambda-role by pasting Python code in the AWS Console.
Cost check: Lambda functions themselves don't cost anything when not running. Storage for the deployment package costs about $0.0000000034 per GB per hour (basically free for a small function like this).
def lambda_handler(event, context):
request_context = event.get("requestContext", {})
identity = request_context.get("identity", {})
ip_address = identity.get("sourceIp")
if not ip_address:
headers = event.get("headers", {})
ip_address = headers.get("X-Forwarded-For") or headers.get("x-forwarded-for")
if not ip_address:
ip_address = "unknown"
print(f"Received IP: {ip_address}")
return {
"statusCode": 200,
"headers": {
"Content-Type": "text/plain",
},
"body": f"Your IP address is: {ip_address}",
}
Run and submit the tests to verify your Lambda function is deployed correctly.
If you prefer CLI + local zip:
cat > lambda_function.py <<'PY'
def lambda_handler(event, context):
request_context = event.get("requestContext", {})
identity = request_context.get("identity", {})
ip_address = identity.get("sourceIp")
if not ip_address:
headers = event.get("headers", {})
ip_address = headers.get("X-Forwarded-For") or headers.get("x-forwarded-for")
if not ip_address:
ip_address = "unknown"
print(f"Received IP: {ip_address}")
return {
"statusCode": 200,
"headers": {
"Content-Type": "text/plain",
},
"body": ip_address,
}
PY
zip lambda-function.zip lambda_function.py
aws iam create-role --role-name patientping-lambda-role --assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}'
aws iam attach-role-policy --role-name patientping-lambda-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws lambda create-function --function-name patientping-ip-function --runtime python3.12 --role arn:aws:iam::YOUR_ACCOUNT_ID:role/patientping-lambda-role --handler lambda_function.lambda_handler --zip-file fileb://lambda-function.zip
In the next lesson, we'll test this function and learn how to update it.