CRUD operations using API Gateway, Lambda and DynamoDB

Creating Table in DynamoDB

This is an asynchronous operation. Upon receiving a create table request, DynamoDB immediately returns a response with a Table status of CREATING. After the table is created, DynamoDB sets the Table status to ACTIVE.

import boto3
import json
def lambda_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.create_table(
TableName='UserTable',
KeySchema=
{
'AttributeName': 'username',
'KeyType': 'HASH'
},
AttributeDefinitions=
{
'AttributeName': 'password',
'AttributeType': 'RANGE'
},
ProvisionedThroughput={
'ReadCapacityUnits': 1,
'WriteCapacityUnits': 1
}
)
return table.table_status

Writing to Table in DynamoDB

import json
import boto3
def put_user_data(username, password, dynamodb=None):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('UserTable')
response = table.put_item(
Item={
'username': username,
'password': password
}
)
return response
def lambda_handler(event, context):

username=event['username']
password=event['password']
dynamo_resp = put_user_data(username,password)
return {
'statusCode': 200,
'body': json.dumps(dynamo_resp)
}
{
"username": "user1",
"password": "user1"
}

Reading from Table in DynamoDB

import json
import boto3
def get_user(username, dynamodb=None):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('UserTable')
response = table.get_item(Key={'username': username})
return response
def lambda_handler(event, context):
# TODO implement
username=event['username']
get_data = get_user(username)
return {
'statusCode': 200,
'body': json.dumps(get_data)
}
{
"username": "user1"
}

Deletion from Table in DynamoDB

import json
import boto3
def delete_user_data(username):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('UserTable')
response = table.delete_item(
Key={
'username': username
}
)
return response
def lambda_handler(event, context):
# TODO implement
username=event['username']
resp=delete_user_data(username)
return {
'statusCode': 200,
'body': json.dumps(resp)
}
{
"username": "user1"
}

Updating the Table in dynamodb

import json
import boto3
def update_password(username, password):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('UserTable')
response = table.update_item(
Key={
'username': username,
},
UpdateExpression = 'SET password = :val1',
ExpressionAttributeValues={':val1': password }
)
return response
def lambda_handler(event, context):
username=event['username']
password=event['password']
resp=update_password(username,password)
return {
'statusCode': 200,
'body': json.dumps(resp)
}
{
"username": "user1",
"password": "user1"
}
create resource type