Objective:
Extract raw data from an open-source API and store it in an Amazon S3 bucket using AWS Lambda with Python.
Step-by-Step Solution:
Prerequisites:
- An AWS account with necessary permissions to create S3 buckets, Lambda functions, and IAM roles.
- Basic understanding of AWS services: S3, Lambda, IAM.
- Familiarity with Python programming.
Step 1: Choose a Public API
For this solution, we'll use the JSONPlaceholder API, a free online REST API for testing and prototyping.
- API Endpoint:
https://jsonplaceholder.typicode.com/posts
- This endpoint returns a list of sample posts in JSON format.
Step 2: Create an S3 Bucket
-
Log in to the AWS Management Console.
-
Navigate to the S3 Service:
- Click on "Services" at the top-left.
- Under "Storage," select S3.
-
Create a New Bucket:
- Click Create bucket.
- Bucket name: Enter a globally unique name, e.g.,
your-bucket-name.
- Region: Choose your preferred region.
- Leave other settings as default unless you have specific requirements.
-
Configure Bucket Permissions:
- By default, the bucket is private.
- We'll grant access to the Lambda function via IAM roles, so no changes are needed here.
-
Finalize Creation:
- Click Create bucket at the bottom.
Step 3: Set Up an IAM Role for Lambda
An IAM Role is needed to grant the Lambda function permissions to interact with S3 and write logs to CloudWatch.
-
Navigate to IAM Service:
- Go to "Services" and select IAM under "Security, Identity, & Compliance".
-
Create a New Role:
- Click Roles in the sidebar.
- Click Create role.
-
Select Trusted Entity:
- Trusted entity type: AWS service.
- Use case: Lambda.
- Click Next.
-
Attach Policies:
- We'll attach two policies:
- AWSLambdaBasicExecutionRole: Allows writing logs to CloudWatch.
- Custom S3 Access Policy: Allows the function to put objects into your S3 bucket.
-
Create a Custom S3 Access Policy:
-
Attach Policies to the Role:
-
Add Tags (Optional):
- Tags can be used for identification and cost allocation.
- Click Next.
-
Review and Create Role:
- Role name:
LambdaS3AccessRole.
- Description: (Optional) "Role for Lambda function to access S3 bucket."
- Review the policies attached.
- Click Create role.
Step 4: Create the Lambda Function
-
Navigate to the Lambda Service:
- Go to "Services" and select Lambda under "Compute".
-
Create a New Function:
- Click Create function.
- Author from scratch.
-
Configure Function Basics:
- Function name:
DataExtractionFunction.
- Runtime: Python 3.9 (or the latest available).
- Permissions:
- Expand Change default execution role.
- Select Use an existing role.
- Choose LambdaS3AccessRole from the dropdown.
-
Create Function:
- Click Create function at the bottom.
Step 5: Write the Lambda Function Code
-
Replace the Default Code:
- Scroll down to the Code source section.
- Delete any existing code in the editor.
-
Paste the Following Code (Ensure to Replace your-bucket-name with Your Actual Bucket Name):
import json
import urllib.request
import boto3
from datetime import datetime
def lambda_handler(event, context):
# The API URL
url = "https://jsonplaceholder.typicode.com/posts"
# Fetch data from the API
try:
response = urllib.request.urlopen(url)
data = response.read() # Read the response
decoded_data = data.decode('utf-8') # Decode bytes to string
print(f"Data fetched from API: {len(decoded_data)} bytes")
except Exception as e:
print(f"Error fetching data from API: {e}")
raise e # Re-raise exception to report failure to Lambda
# Prepare S3 client
s3 = boto3.client('s3')
bucket_name = 'your-bucket-name' # Replace with your bucket name
# Generate timestamp
timestamp = datetime.utcnow().strftime('%Y-%m-%dT%H-%M-%SZ')
s3_key = f'staging/posts_{timestamp}.json'
try:
s3.put_object(Bucket=bucket_name, Key=s3_key, Body=decoded_data)
print(f"Successfully saved data to s3://{bucket_name}/{s3_key}")
except Exception as e:
print(f"Error saving data to S3: {e}")
raise e # Re-raise exception to report failure to Lambda
Notes on the Code:
-
Imports:
json: For handling JSON data.
urllib.request: For making HTTP requests.
boto3: AWS SDK for Python to interact with S3.
datetime: For timestamp generation.
-
Function Logic:
- Fetches data from the API endpoint.
- Decodes bytes to a UTF-8 string.
- Initializes an S3 client.
- Generates a timestamp to create a unique filename.
- Uploads the data to the specified S3 bucket under the
staging/ directory.
-
Error Handling:
- If an error occurs during the fetch or upload, it logs the error and re-raises the exception, which allows Lambda to log the failure.
-
Save the Function:
- Click Deploy in the top-right corner of the code editor to save your changes.
Step 6: Test the Lambda Function
-
Configure a Test Event:
- Click Test in the top-right corner.
- In the Configure test event modal:
- Event template: Select Hello World.
- Event name:
TestEvent.
- Click Create.
-
Run the Test:
- Click Test again to execute the function with the test event.
-
Verify Execution:
- Execution Results: Should show Execution result: succeeded.
- Logs:
Step 7: Verify the Data in S3
-
Go to the S3 Service:
- Navigate back to S3 from the AWS Management Console.
-
Access Your Bucket:
- Click on your-bucket-name from the list.
-
Navigate to the staging/ Directory:
- You should see a folder named staging/.
- Click on it to open.
-
Confirm the File Exists:
- You should see a file named like
posts_2023-10-05T12-34-56Z.json.
- This file contains the raw data fetched from the API.
-
Optional - View the File Content:
- Click on the file.
- Click Download to download the file locally.
- Open it in a text editor to verify the content.
Step 8: Automate the Process (Optional - Schedule the Lambda Function)
To automate the data extraction process, you can schedule the Lambda function to run at specific intervals using Amazon EventBridge (formerly CloudWatch Events).
-
Navigate to EventBridge:
- Go to "Services" and select EventBridge under "Integration".
-
Create a Rule:
- Click Rules in the sidebar.
- Click Create rule.
-
Configure Rule Details:
- Name:
DailyDataExtractionRule.
- Description: (Optional) "Triggers the Lambda function daily to extract data."
- Define pattern: Schedule.
-
Set the Schedule:
- Fixed rate of every: Choose your interval, e.g.,
1 day.
- Or use a cron expression for specific times (e.g.,
cron(0 0 * * ? *) for every day at 00:00 UTC).
-
Select Targets:
- Target: Lambda function.
- Function: Select
DataExtractionFunction.
-
Configure Input (Optional):
- Leave as default unless you need to pass specific data to the function.
-
Create the Rule:
- Click Create at the bottom.
Additional Considerations:
Summary
You've successfully:
- Chosen a public API to extract data from.
- Created an S3 bucket with appropriate permissions.
- Set up an IAM role for Lambda with the necessary policies.
- Written a Python-based Lambda function to fetch data and store it in S3.
- Tested the function to ensure it's working correctly.
- Optionally scheduled the function to run automatically.
This setup allows you to automate the extraction of raw data from an API and store it in S3 for further processing, analysis, or archiving.
Feel free to adjust the code and configurations to suit your specific needs or to handle different APIs and data formats.