0

I'm building an API. Now I am building GET lambda function to retrieve multiple items from DynamoDB database. I wrote this function with boto3.query() method and I was told that it is much faster and better to use batch_get_item() method. For now my code looks like this.

  import json
    import boto3
    from boto3.dynamodb.conditions import Key
    
    
    def lambda_handler(event, context):
    
        
        id = 0
        if 'cat_id' in event:
            id = event['cat_id']
            cat_list = id.split(',') 
            
        dynamodb_client = boto3.client('dynamodb', region_name="us-east-2")
        try:
            resp = []
            for i in cat_list:
                response = dynamodb_client.query(
                TableName='CATS',
                KeyConditionExpression='cat_id = :a',
                ExpressionAttributeValues={
                        ':a': {'S': i}
                        }
                )
                resp.append(response['Items'])
            
            return {    
                'statusCode': 200,    
                'body': resp
            }
            
        except:
            return {    
                'statusCode': 400,    
                'body': json.dumps(f"We could not retrieve these cats.")  
            }

How should I rewrite this function with a batch_get_item() method? The most important thing for me is to be able to retrieve items with query string for example /list?id=1,2,3

Thank you in advance

2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.