How to read files from S3 using Python AWS Lambda

This post explains how to read a file from S3 bucket using Python AWS Lambda function. We will use boto3 apis to read files from S3 bucket.

Login to AWS account and Navigate to AWS Lambda Service.

Navigate to AWS Lambda function and select Functions

Click on Create function

Select Author from scratch

Enter Below details in Basic information
  • Function name: test_lambda_function
  • Runtime: choose run time as per the python version from output of Step 3
  • Architecture: x86_64
  • Select appropriate role that is having proper S3 bucket permission from Change default execution role

Click on create function
Import boto3 and create S3 client
   
import boto3
s3_client = boto3.client("s3")
 
Define bucket name and prefix
   
S3_BUCKET_NAME = 'BUCKET_NAME_HERE'
S3_BUCKET_PREFIX = 'PREFIX_HERE'  
 
Define lambda handler
   
def lambda_handler(event, context):   
    response = s3_client.list_objects_v2(Bucket=S3_BUCKET, Prefix=S3_PREFIX)
    s3_files = response["Contents"]
    for s3_file in s3_files:
        file_content = s3_client.get_object(Bucket=S3_BUCKET,Key=s3_file["Key"])["Body"].read()
        print(file_content)

 
Complete code for reading S3 files with AWS Lambda Python
   
import boto3

s3_client = boto3.client("s3")
S3_BUCKET_NAME = 'BUCKET_NAME_HERE'
S3_BUCKET_PREFIX = 'PREFIX_HERE'
  

def lambda_handler(event, context):   
    response = s3_client.list_objects_v2(Bucket=S3_BUCKET, Prefix=S3_PREFIX)
    s3_files = response["Contents"]
    for s3_file in s3_files:
        file_content = s3_client.get_object(Bucket=S3_BUCKET,Key=s3_file["Key"])["Body"].read()
        print(file_content)
  
 

Categories: AWS

Similar Articles