-2

I'm trying to write a lambda function to upload files to my S3 bucket.

I'm new to coding so I don't understand why this doesn't work.

I get a "KeyError" for Body. Can anyone explain what this means and how do I fix my code?

Thanks in advance.

import base64
import boto3
import json
import uuid

s3 = boto3.client('s3')


def lambda_handler(event, context):
    print(event)
    response = s3.put_object(
        Bucket='s3-bucket',
        Key=str(uuid.uuid4()) + '.jpg',
        Body=event.body,
    )

    image = response['Body'].read()
    return {
        'headers': { 
            "Content-Type": "image/jpg",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Credentials": True,
        },
        'statusCode': 200,
        'body': base64.b64encode(image).decode('utf-8'),
        'isBase64Encoded': True
    }

I tried replacing Body = event.body with Body=event['body'] or Body = event('body') but it still doesn't work.

I expect my lambda function to be able to upload a file to my S3 bucket.

Obtas
  • 1
  • 1
  • 2
    [put_object](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.put_object)'s return value does not have a `Body` key, so that's where the error is coming from. You want to upload the image from `event.body` *and* return it as your response body? – erik258 Feb 01 '23 at 23:47
  • 2
    If you read the [put_object docs](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.put_object), you'll see that the response doesn't have a Body. Why would you be trying to read the body? – jarmod Feb 01 '23 at 23:47
  • All I'd like to do is upload an image to the S3 bucket. I don't need it to return the image, I would just like it to return a response that this process has succeeded. – Obtas Feb 02 '23 at 09:34
  • The lack of an exception indicates that it succeeded. If you want to, you can also check that the response has an ETag. – jarmod Feb 02 '23 at 16:11

1 Answers1

0

Your call to put_object will raise an exception if it fails. You can catch this and respond accordingly, for example:

import boto3
from botocore.exceptions import ClientError

def lambda_handler(event, context):
    print(event)

    try:
        response = s3.put_object(
            Bucket='s3-bucket',
            Key=str(uuid.uuid4()) + '.jpg',
            Body=event.body)

        return {
            'headers': { ... },
            'statusCode': 200
        }
    except ClientError as e:
        print("Error from put_object:", event)

        return {
            'headers': { ... },
            'statusCode': 500
        }
jarmod
  • 71,565
  • 16
  • 115
  • 122