DEV Community

Sakshi Agarwal
Sakshi Agarwal

Posted on

Building a Serverless User Details Fetching API with AWS Lambda, DynamoDB, OOP Principles and Powertools

Introduction

In the world of serverless computing, AWS Lambda has gained popularity for its scalability and cost efficiency. In this blog post, we will explore how to build a Lambda function that fetches user details from DynamoDB using object-oriented programming (OOP) principles. To enhance our function with advanced observability and operational best practices, we will leverage the power of the AWS Lambda Powertools library.

Prerequisites:
To follow along with this tutorial, you should have a basic understanding of AWS Lambda, DynamoDB, and Python programming. You should also have an AWS account and the necessary permissions to create Lambda functions and access DynamoDB.

Here's an example of a Lambda function written using object-oriented programming (OOP) principles to fetch user details from DynamoDB:

from aws_lambda_powertools import Logger, Tracer, Validator
from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEvent

import boto3

logger = Logger()
tracer = Tracer()
validator = Validator()

class UserFetcher:
    def __init__(self, table_name):
        self.dynamodb = boto3.resource('dynamodb')
        self.table = self.dynamodb.Table(table_name)

    def fetch_user_details(self, user_id):
        response = self.table.get_item(Key={'user_id': user_id})
        user_details = response.get('Item')
        return user_details

@tracer.capture_lambda_handler
@logger.inject_lambda_context
def lambda_handler(event: APIGatewayProxyEvent, context):
    # Validate input using powertools.Validator
    validator.validate(event, "user_id")
    user_id = event.path_parameters.get('user_id')

    # Initialize UserFetcher object
    user_fetcher = UserFetcher('UserTable')

    try:
        # Fetch user details from DynamoDB
        user_details = user_fetcher.fetch_user_details(user_id)
        logger.info(f"Fetched user details: {user_details}")

        return {
            "statusCode": 200,
            "body": user_details
        }
    except Exception as e:
        logger.error(f"Error fetching user details: {str(e)}")
        return {
            "statusCode": 500,
            "body": "Error fetching user details"
        }

Enter fullscreen mode Exit fullscreen mode

Step 1: Setting Up the Environment
Before we begin writing code, let's set up our environment. Create a new Lambda function using the AWS Management Console or the AWS CLI. Choose a Python runtime, and configure the function with appropriate permissions to access DynamoDB. Install the AWS Lambda Powertools library by adding it to your function's deployment package.

Step 2: Writing the UserFetcher Class
To encapsulate the logic for fetching user details from DynamoDB, we will create a UserFetcher class using OOP principles. This class will have a constructor (init) method to initialize the DynamoDB resource and table, and a fetch_user_details method that takes a user_id as input and retrieves the corresponding user details from DynamoDB using the get_item API.

Step 3: Implementing Input Validation and Logging with Powertools
To enhance our function's robustness and visibility, we will use the AWS Lambda Powertools library. Within the lambda_handler function, we will use the powertools.utilities.validator module to validate the input and raise an exception if it's missing. Additionally, we will leverage powertools.Logger to log informative messages and handle any exceptions that occur during the execution of our Lambda function.

Step 4: Testing and Deploying the Lambda Function
Once we have written the code for our Lambda function, we can test it locally using a tool like the AWS SAM CLI or by creating a test event in the AWS Lambda console. Ensure that your DynamoDB table exists and has the required user data. Deploy the Lambda function to your AWS account using the deployment mechanism of your choice.

Conclusion:
In this blog post, we learned how to build a serverless API using AWS Lambda, DynamoDB, and OOP principles. We enhanced our Lambda function with input validation and logging using the AWS Lambda Powertools library. By following the step-by-step guide and leveraging Powertools, we created a robust and observable solution for fetching user details. This approach allows us to build scalable and reliable serverless applications while adhering to best practices and leveraging advanced tools.

Top comments (0)