get_item from dynamodb with python

Viewed 11102

This question is killing me softly at the moment. I am trying to learn python, lambda, and Dynamodb.

Python looks awesome, I am able to connect to MySQL while using a normal MySQL server like Xampp, the goal is to learn to work with Dynamodb, but somehow I am unable to get_items from the Dynamodb. This is really kicking my head in and already taking the last two days.

Have watched tons of youtube movies and read the aws documentation.

Any clues what I am doing wrong. My code till now;

import json
import boto3
from boto3.dynamodb.conditions import Key, Attr

#always start with the lambda_handler
def lambda_handler(event, context):

    # make the connection to dynamodb
    dynamodb = boto3.resource('dynamodb')

    # select the table
    table = dynamodb.Table("html_contents")

    # get item from database
    items = table.get_item(Key={"id": '1'})

Everywhere I look I see that I should do it like this. But I keep getting the following error

{errorMessage=An error occurred (ValidationException) when calling the GetItem operation: The provided key element does not match the schema, errorType=ClientError, stackTrace=[["\/var\/task\/lambda_function.py",16,"lambda_handler","\"id\": '1'"],["\/var\/runtime\/boto3\/resources\/factory.py",520,"do_action","response = action(self, *args, **kwargs)"],["\/var\/runtime\/boto3\/resources\/action.py",83,"__call__","response = getattr(parent.meta.client, operation_name)(**params)"],["\/var\/runtime\/botocore\/client.py",314,"_api_call","return self._make_api_call(operation_name, kwargs)"],["\/var\/runtime\/botocore\/client.py",612,"_make_api_call","raise error_class(parsed_response, operation_name)"]]}

My database structure.

enter image description here

My DynamoDb settings Table name html_contents Primary partition key id (Number) Primary sort key - Point-in-time recovery DISABLEDEnable Encryption DISABLED Time to live attribute DISABLEDManage TTL Table status Active

What am I doing wrong here? I start to think I did something wrong with the aws configuration.

Thank you in advance.

Wesley

2 Answers

Thats to @ippi.

It was the quotes that I am using.

table.get_item(Key={"id": '1'})

needed to be

table.get_item(Key={"id": 1})

As I am using a numeric and not a string. Hope this helps for the next person(s) with the same problem.

You're facing this problem because you have created a table with a partition key whose data type is an integer. Now you're performing a read an item operation specifying partition as a string which needs to be an integer that causes this issue.

I'm the author of Lucid-Dynamodb, a minimalist wrapper to AWS DynamoDB. It covers all the Dynamodb operations.

Reference: https://github.com/dineshsonachalam/Lucid-Dynamodb#4-read-an-item

Related