AWS Serverless and AWS DynamoDB

SUMIT THAKUR
Sep 1, 2019 · 3 min read

Going to you use the AWS SDK for Python (Boto 3) to write simple programs to perform the following Amazon DynamoDB operations:

  • Install DynamoDB Local
  • Table Creation for DynamoDB Local
  • Perform create, read, update, and delete operations on the table.
  • Run simple queries.

Few Steps to setup serverless on machine

1. Install Serverless

npm install -g serverless

Check serverless version and successfully installed or not use command

serverless --version

2. AWS Credentials configuration

Using single command line in terminal

serverless config credentails --provider aws --key <KEY> --secret <KEY>

Configure using aws CLI

  1. For this we need to install aws cli
pip install awscli --upgrade --user

check aws version and successfully install or not

aws --versionwhich aws

Configure using aws cli

If you have the AWS CLI installed, then you can use it to configure your credentials file:

aws configureaws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY
Default region name REGION
Default output format

3. Installation Boto3

Install the latest Boto 3 release via pip:

pip install boto3

You may also install a specific version:

pip install boto3==1.0.0

4. Using Boto 3

To use Boto 3, you must first import it and tell it what service you are going to use:

import boto3# Let's use Amazon dynamodb
client = boto3.client('dynamodb'))

4.1 Creating a New Table

In order to create a new table, use the DynamoDB.ServiceResource.create_table() method

import boto3# Get the service resource.
dynamodb = boto3.resource('dynamodb')
# Create the DynamoDB table.
table = dynamodb.create_table(
TableName='users',
KeySchema=[
{
'AttributeName': 'username',
'KeyType': 'HASH'
},
{
'AttributeName': 'last_name',
'KeyType': 'RANGE'
}
],
AttributeDefinitions=[
{
'AttributeName': 'username',
'AttributeType': 'S'
},
{
'AttributeName': 'last_name',
'AttributeType': 'S'
},
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
# Wait until the table exists.
table.meta.client.get_waiter('table_exists').wait(TableName='users')
# Print out some data about the table.
print(table.item_count)

This creates a table named users that respectively has the hash and range primary keys username and last_name. This method will return a DynamoDB.Table resource to call additional methods on the created table.

4.2 Using an Existing Table

It is also possible to create a DynamoDB.Table resource from an existing table:

import boto3# Get the service resource.
dynamodb = boto3.resource('dynamodb')# Instantiate a table resource object without actually
# creating a DynamoDB table. Note that the attributes of this table
# are lazy-loaded: a request is not made nor are the attribute
# values populated until the attributes
# on the table resource are accessed or its load() method is called.table = dynamodb.Table('users')# Print out some data about the table.
# This will cause a request to be made to DynamoDB and its attribute
# values will be set based on the response.
print(table.creation_date_time)

Expected Output (Please note that the actual times will probably not match up):

2015-06-26 12:42:45.149000-07:00

4.3 Creating a New Item

Once you have a DynamoDB.Table resource you can add new items to the table using DynamoDB.Table.put_item():

table.put_item(
Item={
'username': 'janedoe',
'first_name': 'Jane',
'last_name': 'Doe',
'age': 25,
'account_type': 'standard_user',
}
)

For all of the valid types that can be used for an item, refer to Valid DynamoDB Types.

4.4 Getting an Item

You can then retrieve the object using DynamoDB.Table.get_item():

response = table.get_item(
Key={
'username': 'janedoe',
'last_name': 'Doe'
}
)
item = response['Item']
print(item)

Expected Output:

{u'username': u'janedoe',
u'first_name': u'Jane',
u'last_name': u'Doe',
u'account_type': u'standard_user',
u'age': Decimal('25')}

4.5 Updating Item

You can then update attributes of the item in the table:

table.update_item(
Key={
'username': 'janedoe',
'last_name': 'Doe'
},
UpdateExpression='SET age = :val1',
ExpressionAttributeValues={
':val1': 26
}
)

Then if you retrieve the item again, it will be updated appropriately:

response = table.get_item(
Key={
'username': 'janedoe',
'last_name': 'Doe'
}
)
item = response['Item']
print(item)

Expected Output:

{u'username': u'janedoe',
u'first_name': u'Jane',
u'last_name': u'Doe',
u'account_type': u'standard_user',
u'age': Decimal('26')}

4.6 Deleting Item

You can also delete the item using DynamoDB.Table.delete_item():

table.delete_item(
Key={
'username': 'janedoe',
'last_name': 'Doe'
}
)

4.7 Deleting a Table

Finally, if you want to delete your table call DynamoDB.Table.delete():

table.delete()
SUMIT THAKUR

Written by

Software Developer (Full Stack Android, AWS)

More From Medium

Also tagged Dynamodb

Also tagged Serverless Apps

Also tagged Serverless Apps

Publishing an application on AWS SAM

17

Also tagged Dynamodb

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade