Connect to DynamoDB from Python using Boto3 SDK
Create Access Key
Firstly need to create access key ID and secret access key. Under Identity and Access Management (IAM) -> access management->users, select Add User to create a user and check Programmatic access tickbox. Under Set Permissions, select attach existing policies directly / create you own policy to give proper access. For demo purpose, give it AdminstratorAccess. At the end , it provides the access key ID and secret access key. Save those.
Install Boto
Simply
pip install boto3
Establish connection
The boto3.client and the boto3.resource are for creating resources, and for accessing the created resources.
client.exceptions are just predefined exceptions.
import boto3
client = boto3.client(
'dynamodb',
aws_access_key_id='the id',
aws_secret_access_key='the secret',
)
Conneciton to resource
dynamodb = boto3.resource(
'dynamodb',
aws_access_key_id='the id',
aws_secret_access_key='the secret',
)
Create a new table programmatically (this can be done manually as well if want to)
Search for "boto3 create_table" for reference details.
try:
table = client.create_table(
TableName='MyTable',
KeySchema=[
{
'AttributeName': 'timestamp',
'KeyType': 'HASH' #hash or range
}
],
AttributeDefinitions=[
{
'AttributeName': 'timestamp',
'AttributeType': 'N' #N for number, B for boolean, S for string
}
],
#LocalSecondaryIndexes = [...], #if need to add local indexes, put in here, check reference for the syntax
#GlobalSecondaryIndexes = [...], #if need to add global indexes, put in here
BillingMode= 'PAY_PER_REQUEST', #'PROVISIONED'|'PAY_PER_REQUEST', if provisioned, also need to provided provisiond details
)
print("Creating table")
waiter = client.get_waiter('table_exists')
waiter.wait(TableName='MyTable') #wait for MyTable to be created
print("Table created")
except Exception as e:
print(str(e))
Insert item
client.put_item( Item=... )
Query
client.query(...)
Many other operations:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html
More credential authentication methods for boto3 client. Or just search for boto3 credentials.
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html