0
votes

I am trying to have my server less function working as i am trying my hands on it.

I am trying to perform API PUT method , which will be integrated with proxy lambda function

I have a lambda function as below:

def lambda_handler(event, context):
    
    param = event['queryStringParameters']
    dynamodb = boto3.resource('dynamodb', region_name="us-east-1")
    table = dynamodb.Table('*****')
    
          
    response = table.put_item(
        Item = {



        }
        
    )

i want to insert the Param value which i am getting from query parameters into DynamoDB table.

I am able to achieve it by :

response = table.put_item(
            Item = param 
)

But the issue here is if the partition key is present it will just over ride the value in place of throwing an error of present partition key.

I know the PUT method is idempotent.

Is there any other way i can achieve this ?

1
Can you elaborate more on why this is an issue in your case: the issue here is if the partition key is present it will just over ride the value in place of throwing an error of present partition keyShawn
@Shawn . I am want partition key to be unique for each insert. If there an attempt to insert a new record with same partition key. Then i have to have a case for that to throw an error stating partition key is already present.sumanth shetty

1 Answers

0
votes

Per https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.put_item, you can:

"perform a conditional put operation (add a new item if one with the specified primary key doesn't exist)"

Note

To prevent a new item from replacing an existing item, use a conditional expression that contains the attribute_not_exists function with the name of the attribute being used as the partition key for the table. Since every record must contain that attribute, the attribute_not_exists function will only succeed if no matching item exists.

Also see DynamoDB: updateItem only if it already exists

If you really need to know whether the item exists or not so you can trigger your exception logic, then run a query first to see if the item already exists and don't even call put_item. You can also explore whether using a combination of ConditionExpression and one of the ReturnValues options (for put_item or update_item) may return enough data for you to know if an item existed.