1. Search for and access the Lambda service page
2. Configure the Analyze Function on the Create a function page
In the first section, there are 3 options to create a template for the Lambda Function: Author from scratch, Use a blueprint, Container image
In the Basic information section:
In the Change default execution role section:
3. Configure the Analyze Function code in the Code Source section
import json
import boto3
import base64
# Initialize Rekognition client to call the image recognition service
rekognition = boto3.client('rekognition')
def lambda_handler(event, context):
try:
# Check if the request body exists
if 'body' not in event or not event['body']:
return {
"statusCode": 400,
"body": json.dumps({"error": "Empty request body"})
}
# Get the body from the incoming event (check if it's base64)
body_str = event['body']
if event.get("isBase64Encoded"): # If API Gateway is configured to send base64
body_str = base64.b64decode(event['body']).decode('utf-8')
# Convert JSON string to Python dictionary
body = json.loads(body_str)
# Get the base64 image data from the "image" field
image_base64 = body.get('image')
# If there is no image, return an error
if not image_base64:
return {
"statusCode": 400,
"body": json.dumps({"error": "Missing 'image' in request body"})
}
# Decode the image from base64 to bytes
image_bytes = base64.b64decode(image_base64)
# Call AWS Rekognition to detect labels in the image
response = rekognition.detect_labels(
Image={'Bytes': image_bytes}, # Pass the image as bytes
MaxLabels=10, # Limit to 10 labels returned
MinConfidence=75 # Only get labels with at least 75% confidence
)
# Return the recognition result as JSON
return {
"statusCode": 200,
"body": json.dumps({
"labels": response.get('Labels', []),
"message": "Image analyzed successfully"
}),
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*" # Allow calls from frontend
}
}
except Exception as e:
# If there is an error, log it and return a 500 error code
print("Error:", str(e))
return {
"statusCode": 500,
"body": json.dumps({"error": str(e)})
}
You have completed the step of configuring the Lambda Function for the Analyze Image feature by calling the AWS Rekognition