Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

I have the following lambda function code for simply printing out the Author and metadata of an uploaded event of an S3 bucket: 

from __future__ import print_function

import json

import urllib

import boto3

 

print('Loading function')

 

s3 = boto3.client('s3')

 

 

def lambda_handler(event, context):

 

    #print("Received event: " + json.dumps(event, indent=2))

    # bucket = event['Records'][0]['s3']['bucket']['name']

 

    for record in event['Records']:

        bucket = record[0]['s3']['bucket']['name']

        key = record[0]['s3']['object']['key']

        response = s3.head_object(Bucket=bucket, Key=key)

 

        logger.info('Response: {}'.format(response))

 

        print("Author : " + response['Metadata']['author'])

        print("Description : " + response['Metadata']['description'])

However, I am getting the following error while testing:

{

  "stackTrace": [

    [

      "/var/task/lambda_function.py",

      17,

      "lambda_handler",

      "for record in event['Records']:"

    ]

  ],

  "errorType": "KeyError",

  "errorMessage": "'Records'"

}

Am I doing anything wrong while accessing the bucket name and key name of the S3 object? If not, then what am I doing wrong here? 

1 Answer

0 votes
by (44.4k points)

Inside the AWS API, we have to configure the Integration Request. This can be done by clicking on Body Mapping Templates, Then set the content type to application/json. A generated mapping template appears, and edit it like this:

{

  "body" : $input.json('$'),

  "headers": {

    #foreach($header in $input.params().header.keySet())

    "$header": "$util.escapeJavaScript($input.params().header.get($header))" #if($foreach.hasNext),#end

 

    #end

  },

  "method": "$context.httpMethod",

  "params": {

    #foreach($param in $input.params().path.keySet())

    "$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end

 

    #end

  },

  "query": {

    #foreach($queryParam in $input.params().querystring.keySet())

    "$queryParam": "$util.escapeJavaScript($input.params().querystring.get($queryParam))" #if($foreach.hasNext),#end

 

    #end

  }  

}

Also, edit this part in the lambda function.

replace:

for record in event['Records']:

with:

for record in event['query']['Records']

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
0 votes
1 answer

Browse Categories

...