Create a DynamoDB Table
Leave the Partition Key Set To String, this way it will be easier to create Unique Ids Identifiers because unlike MySQL Databases DynamoDB will not generate an auto increment ID. Furthermore, if we select Number or Binaries, there will be a conflict between DynamoDB and the
uuid library because they respectively use different decimal calculation.
Go to the Terminal and create an uuid
Copy and paste the uuid, and create the item on the table
Create a put_dynamodb function
Go to Configuration Permissions, Click on the Role Name and Attach the DynamoDbFullAccess policy to this Role
First check if we can retrieve the data
import json
import uuid
import boto3
db = boto3.client('dynamodb')
def lambda_handler(event, context):
data = db.scan(TableName='database')
return {
'statusCode': 200,
'body': json.dumps('Success')
}
Let's test the function
Now, let's add a new item and an auto generated id with uuid module, and test the function
import json
import uuid
import boto3
db = boto3.client('dynamodb')
id_db=uuid.uuid4()
def lambda_handler(event, context):
data= db.put_item(TableName='database', Item={'id':{'S':str(id_db)},'item':{'S':'iphone-10'},'available':{'BOOL': False}})
return {
'statusCode': 200,
'body': json.dumps('Success')
}
Let's write the exact same code except that we are going to add a color attribute.
import json
import uuid
import boto3
db = boto3.client('dynamodb')
id_db=uuid.uuid4()
def lambda_handler(event, context):
data= db.put_item(TableName='database', Item={'id':{'S':str(id_db)},'item':{'S':'iphone-10'},'available':{'BOOL': False},'color':{'S':'pink'}})
return {
'statusCode': 200,
'body': json.dumps('Success')
}
Now let's check our database
As you can see we haven't entered any id manually, and they have been generated programmatically.
Top comments (0)