An AWS Lambda function that enriches incoming request data with user preferences stored in DynamoDB.
This Lambda function intercepts requests and enriches the payload with user-specific preferences (language, notification settings, etc.) fetched from a DynamoDB table. If no user preferences are found, sensible defaults are applied.
- Data Enrichment: Automatically merges user preferences into request payloads
- Default Fallback: Applies default preferences when user data is not found
- Error Handling: Comprehensive error handling with proper HTTP status codes
- Logging: Structured logging for debugging and monitoring
- Flexible Input: Supports both direct Lambda invocation and API Gateway events
| Variable | Description | Required |
|---|---|---|
TABLE_NAME |
Name of the DynamoDB table containing user preferences | Yes |
The function expects a DynamoDB table with the following structure:
| Attribute | Type | Description |
|---|---|---|
id |
String (Partition Key) | Unique user identifier |
language |
String | User's preferred language code |
notifications_enabled |
Boolean | Whether notifications are enabled |
{
"body": "{\"id\": \"user123\", \"data\": \"example\"}"
}{
"statusCode": 200,
"body": "{\"id\": \"user123\", \"data\": \"example\", \"language\": \"en\", \"notifications_enabled\": false}",
"headers": {
"Content-Type": "application/json"
}
}{
"statusCode": 400,
"body": "{\"error\": \"Invalid JSON in request body\"}",
"headers": {
"Content-Type": "application/json"
}
}When user preferences are not found in DynamoDB:
| Preference | Default Value |
|---|---|
language |
"en" |
notifications_enabled |
false |
-
Create DynamoDB Table:
aws dynamodb create-table \ --table-name UserPreferences \ --attribute-definitions AttributeName=id,AttributeType=S \ --key-schema AttributeName=id,KeyType=HASH \ --billing-mode PAY_PER_REQUEST
-
Deploy Lambda Function:
zip function.zip lambda_function.py aws lambda create-function \ --function-name enrich-data \ --runtime python3.12 \ --handler lambda_function.lambda_handler \ --zip-file fileb://function.zip \ --role arn:aws:iam::ACCOUNT_ID:role/lambda-role \ --environment Variables={TABLE_NAME=UserPreferences} -
Set IAM Permissions: Ensure the Lambda execution role has
dynamodb:GetItempermission on the table.
# Install dependencies
pip install boto3
# Set environment variables
export TABLE_NAME=UserPreferences
# Run locally with AWS credentials configured
python -c "from lambda_function import lambda_handler; print(lambda_handler({'body': '{\"id\": \"test\"}'}, None))"