>
LOADING

AWS Lambda DynamoDB Data Access

AWS Lambda DynamoDB Data Access

by admin January 22, 2020

aws-lambda-dynamodb

AWS Lambda DynamoDB are two of the pillars of the platform. DynamoDB is a powerful NoSQL database from Amazon. Once data is stored in DynamoDB, you’ll need to access it in some fashion. In this article, we cover a simple way you can connect to DynamoDB using Lambda functions on AWS.

Lambda functions are a serverless implementation that allow you to treat code as functions and allow Amazon to scale to meet the demands of your application. Because you don’t need to manage instances with lambda functions, you have a simple infrastructure that can handle a large influx of users and provide a low-cost hosting option when you have little traffic.

To connect a lambda function to DynamoDB, we’re going to assume two things:

    1. You already have a lambda function created.
    2. You have a DynamoDB table ready, and you have the proper permissions to write to that table.

If you need help creating a lambda function, check out this article from AWS. Similarly, if you need help setting up a DynamoDB instance, check out this documentation.

For this tutorial, we’ll set the lambda runtime as python.

Using a Lambda Function to Read From a DynamoDB table

Your code will execute in the python function that you specify. In that file, you’ll want to execute something like this:

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

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
      if isinstance(o, decimal.Decimal):
        if o % 1 > 0:
          return float(o)
        else:
          return int(o)
      return super(DecimalEncoder, self).default(o)

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('your-table-name')
    response = table.query(
      KeyConditionExpression=Key('pk').eq(f"user|some_user_id") & Key('sk').begins_with('profile')
    )
    return {
      'statusCode': 200,
      'body': json.dumps(response['Items'], cls=DecimalEncoder)
    }

First, you’ll include necessary python modules. All included modules are automatically vendored by the AWS python SDK, botocore. Then, we’ll instantiate the DynamoDB table and execute a query.

Once the query is finished executing, we’ll return the results as JSON, being sure to encode data appropriately. DynamoDB has specific requirements pertaining to decimals.

Using a Lambda Function to Write To a DynamoDB table

To write to a table, you’re essentially performing the same steps as above. The main difference being you’re going to call the “put_item” operation on your table and set the appropriate keys for the item being written to the database.

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

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
      if isinstance(o, decimal.Decimal):
        if o % 1 > 0:
          return float(o)
        else:
          return int(o)
      return super(DecimalEncoder, self).default(o)

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('your-table-name')
    response = table.put_item(
      'pk': "user|some_user_id",
      'sk': "profile",
      'name': "Joe User"
    )
    print(response)
    return {
      'statusCode': 201,
      'body': json.dumps(response, cls=DecimalEncoder)
    }

As you can see, connecting your lambdas to a DynamoDB table in your region with a role that allows proper access is quite simple! We highly recommend using this stack when building out your applications.

If you’re looking to dive more into DynamoDB + Lambda, we recommend the following resources:

  • These talks from Rick Houlihan at re:invent are probably the best resources you can find on DynamoDB. Rick is extremely smart and gets across DynamoDB concepts in a clear manner. You can see Rick’s talk from re:invent 2018 and re:invent 2019 on YouTube.
  • To better understand Lambda, check out this resource on YouTube from Simplilearn. Also, the official documentation from AWS is always a great place to start.

 

Social Shares

Related Articles