DEV Community

Aissa Laribi
Aissa Laribi

Posted on

Creating Unique IDs programmatically on DynamoDB

Create a DynamoDB Table

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

Terminal UUID

Copy and paste the uuid, and create the item on the table

Item

Create a put_dynamodb function

put_dynamodb Lambda function

Go to Configuration Permissions, Click on the Role Name and Attach the DynamoDbFullAccess policy to this Role

Role Lambda

Attach Dynamodb Policy To Lambda 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')
    }


Enter fullscreen mode Exit fullscreen mode

Let's test the function

Test 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')
    }


Enter fullscreen mode Exit fullscreen mode

Image description

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')
    }



Enter fullscreen mode Exit fullscreen mode

Now let's check our database

DynamoDb updated

As you can see we haven't entered any id manually, and they have been generated programmatically.

Top comments (0)