Open the Functions
section of Lambda console
Click Create function
Choose Author from scratch
In the Basic information
section, enter:
create-user
Python 3.13
x86_64
Change default execution role
: Keep Create a new role with basic Lambda permissions
to let Lambda create new execution role for the function.Click Create function
After the function is created, you will be redirected to the detail page for the function.
In the Code
tab, Code source
section:
Wait for the code editor to be loaded.
In the editor tab for lambda_function.py
, replace all the placeholder code with the following code:
import datetime
import os
import json
import uuid
import boto3
# Initialize DynamoDB resource and table
dynamodb = boto3.resource("dynamodb")
TABLE_NAME = os.environ.get("USERS_TABLE", "UsersTable")
table = dynamodb.Table(TABLE_NAME)
def getCurrentTime():
return datetime.datetime.now().replace(microsecond=0).isoformat()
def response(status_code, body=None):
"""
Helper to build HTTP responses
"""
resp = {
"statusCode": status_code,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
}
if body is not None:
resp["body"] = json.dumps(body)
return resp
def lambda_handler(event, context):
"""
Lambda handler to create a user and persist data in DynamoDB.
Expects JSON body with 'id', 'name', 'email', and optionally other attributes.
"""
try:
data = json.loads(event["body"]) if "body" in event else event
except json.JSONDecodeError:
return response(400, {"error": "Invalid JSON body: " + event["body"]})
now = getCurrentTime()
id = uuid.uuid4()
try:
# Validate required fields
name = data["name"]
email = data["email"]
except (KeyError, json.JSONDecodeError):
return response(
400, {"error": "Invalid request body: name, and email are required."}
)
item = {
"id": str(id),
"name": name,
"email": email,
"created_at": now,
"updated_at": now,
**{k: v for k, v in data.items() if k not in ["name", "email"]},
}
try:
table.put_item(Item=item, ConditionExpression="attribute_not_exists(id)")
return response(201, item)
except dynamodb.meta.client.exceptions.ConditionalCheckFailedException:
return response(409, {"error": "User with given id already exists."})
except Exception as e:
return response(500, {"error": str(e)})
Click Deploy (Ctrl + Shift + U)
to deploy the lambda function.
Open the Configuration
tab
Open the Permissions
section
In the Execution Role
, click on the role name create-user-role-XXXXXXXX
to open the page of the IAM role.
In the page of the IAM role, Permissions
tab, click the Add permissions
button, choose Attach Polices
.
Search for AmazonDynamoDBFullAccess
policy.
Select AmazonDynamoDBFullAccess
policy.
Click Add permissions
to attach the IAM policy to the IAM Role.