amazon web services - How to access the event object with python in AWS Lambda? - Stack Overflow
[deleted by user]
Accessing Lambda Python event - ERROR
amazon web services - Navigating Event in AWS Lambda Python - Stack Overflow
Videos
I am writing a Python Lambda that will be invoked via HTTP. A web service will make an HTTP call to an API Gateway resource that I define, which will then invoke the Lambda. My Lambda handler will look like:
def lambda_handler(event, context):
// do stuff down here
return responseObjectI am trying to find documentation on event and context so I know how to do things like:
-
extract query string parameters from requests
-
extract path parameters from requests
-
inspect the request entity
-
etc.
Surprising I can find no official AWS documentation on what fields/properties these two objects have on them when they are invoked from an API Gateway resource action. I found this article which was sort of helpful but nothing official from AWS. Can anyone point me in the right direction?
The event data passed to Lambda contains the Instance ID.
You then need to call describe_tags() to retrieve a dictionary of the tags.
import boto3
client = boto3.client('ec2')
client.describe_tags(Filters=[
{
'Name': 'resource-id',
'Values': [
event['detail']['instance-id']
]
}
]
)
In the Details Section of the Event, you will get the instance Id's. Using the instance id and AWS SDK you can query the tags. The following is the sample event
{
"version": "0",
"id": "ee376907-2647-4179-9203-343cfb3017a4",
"detail-type": "EC2 Instance State-change Notification",
"source": "aws.ec2",
"account": "123456789012",
"time": "2015-11-11T21:30:34Z",
"region": "us-east-1",
"resources": [
"arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"
],
"detail": {
"instance-id": "i-abcd1111",
"state": "running"
}
}
» pip install aws-lambda-event-handler
You are having this problem because the contents of the body is a JSON. But in string format. You should parse it to be able to access it like a normal dictionary. Like so:
import json
def handler(event: dict, context: object):
body = event['Records'][0]['body']
body = json.loads(body)
# use the body as a normal dictionary
You are getting only a single char when using integer indexes because it is a string. So, using [n] in an string will return the nth char.
It's because your getting stringified JSON data. You need to load it back to its Python dict format.
There is a useful package called lambda_decorators. you can install with pip install lambda_decorators
so you can do this:
from lambda_decorators import load_json_body
@load_json_body
def lambda_handler(event, context):
print(event['Records'][0]['body'])
# Now you can access the the items in the body using there index and keys.
This will extract the JSON for you.