Reputation: 1038
I'm trying to serve an audio file from S3 using a lambda function in python.
My lambda function is producing an Internal server error
message, with the CloudWatch log showing:
23:42:07 An error occurred during JSON serialization of response: b'\xff\xfb\x90\xc4\x00\x00\...
Below is the code in my python lambda function
import boto3
def getAudio(event, context):
#[Validate permissions here]
s3 = boto3.client('s3')
my_bucket = 'my-app'
my_key = "audio/%s.mp3"%(event['pathParameters']['audio_id'])
s3_object = s3.get_object(Bucket=my_bucket, Key=my_key)
return s3_object['Body'].read()
What is the appropriate way to retrieve and pass the audio file?
My endpoint is https://1cbbkp15ci.execute-api.us-east-1.amazonaws.com/dev/assert/audio/adfk-m1
Upvotes: 0
Views: 160
Reputation: 13055
Cleanest way to create a Signed URL for S3 and redirect to that URL.
Lambda (Validate Permissions and Create Signed URL) --> Redirect (302) --> Actual file in S3 bucket
Python Signed URL Generation Code:
import boto3
import requests
# Get the service client.
s3 = boto3.client('s3')
# Generate the URL to get 'key-name' from 'bucket-name'
url = s3.generate_presigned_url(
ClientMethod='get_object',
Params={
'Bucket': 'bucket-name',
'Key': 'key-name'
}
)
# Use the URL to perform the GET operation. You can use any method you like
# to send the GET, but we will use requests here to keep things simple.
response = requests.get(url)
Additionally, if you want the serve with right content type. Set the content type of the object in S3. You can set with command line or even with boto3 as well.
aws s3api put-object --bucket bucket --key foo.mp3 --body foo.mp3 --content-type audio/mpeg
Hope it helps.
Upvotes: 3