could somebody please help me? I have a struggle in AWS Lambda function. My goal is to be able to retrieve info from DynamoDB using query string passed into GET method URL endpoint. For example when I type this query string I want to see only 1 and 2 cat /list?id=1&id=2. I know that the best way is to use query() method for this but I'm not sure how can I make a function which read query strings. I'm adding my current code. It would be very nice if someone could help, because I'm trying to figure it out for days now.
import json
import boto3
from boto3.dynamodb.conditions import Key
def lambda_handler(event, context):
#grab the category-id from the url, suppose url is in the form /list?id=1, where id is category id
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:
response = dynamodb_client.query(
TableName='CATS',
KeyConditionExpression='cat_id = :a',
ExpressionAttributeValues={
':a': {'S': id}
}
)
return {
'statusCode': 200,
'body': response['Items']
}
except:
return {
'statusCode': 400,
'body': json.dumps(f"We could not retrieve these cats.")
}
CodePudding user response:
you might want to check the logs on your cloudwatch. what did it say?
CodePudding user response:
Though your question is not so clear, what I understand is that you failed to grab the value of the request parameter passed to the lambda handler. Also in your question you have used /list?id=1&id=2
which shows 2 request parameter with same name, please correct your url.
You can get all the request data from the first parameter (event) of the lambda handler. Try something like below -
def lambda_handler(event, context):
#grab the category-id from the url, suppose url is in the form /list?id=1, where id is category id
id = 0
if 'id' in event:
id =event['id']
dynamodb_client = boto3.client('dynamodb', region_name="us-east-2")
try:
response = dynamodb_client.query(
TableName='CATS',
KeyConditionExpression='cat_id = :a',
ExpressionAttributeValues={
':a': {'S': id}
}
)
return {
'statusCode': 200,
'body': response['Items']
}
except:
return {
'statusCode': 400,
'body': json.dumps(f"We could not retrieve these cats.")
}
For API gateway settings to pass request parameters to lambda please take a look at this document https://aws.amazon.com/premiumsupport/knowledge-center/pass-api-gateway-rest-api-parameters/