Skip to main content

Command Palette

Search for a command to run...

Building a Serverless Application using AWS Lambda:

Pushing User Data into AWS DynamoDB with Python Lambda Function and API

Published
5 min read

Introduction

In this blogpost, we will explore how to build a serverless application using AWS services such as AWS Lambda and DynamoDB. Our goal is to create an API that allows users to push their data into a DynamoDB table by invoking a Python Lambda function. We'll cover the concepts and workflow of this application, including the necessary code and steps to test it.

Introduction to Serverless Architecture

Serverless architecture allows developers to focus on writing code without worrying about server management. It enables scalable and cost-effective application development by automatically managing infrastructure resources. AWS Lambda is a core component of serverless architecture, allowing us to run code in response to events without provisioning or managing servers.

Overview of AWS Services:

  • AWS Lambda: A compute service that runs your code in response to events. We'll utilize Lambda to execute our Python function whenever the API is invoked.

  • DynamoDB: A NoSQL database service offered by AWS. We'll store user data in DynamoDB tables, leveraging its scalability, low latency, and flexible data model.

  • API Gateway: A fully managed service for creating, deploying, and managing APIs. API Gateway will provide a RESTful interface for users to interact with our serverless application.

Creating a DynamoDB Table

We'll use the AWS CLI to create a DynamoDB table. Open the terminal and execute the following command:

aws dynamodb create-table --table-name UserData --attribute-definitions AttributeName=UserId,AttributeType=S --key-schema AttributeName=UserId,KeyType=HASH --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5

This command creates a table named "UserData" with a primary key "UserId" of type string. We set the provisioned throughput to 5 read capacity units and 5 write capacity units, but you can adjust these values based on your requirements.

Creating an API Gateway

  1. To create an API Gateway, follow these steps in the AWS Management Console:
  • Open the API Gateway service.

  • Click "Create API" and select "REST API."

  • Choose the protocol and create a new API.

  • Define the API resources and methods.

  • Configure the integration with AWS Lambda, specifying the Lambda function you'll create later.

Developing the Python Lambda Function

We'll now write the Python code for our Lambda function. This function will receive user data as input and store it in the DynamoDB table.

import boto3

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('UserData')

    # Extract user data from the API request
    user_id = event['userId']
    user_name = event['userName']
    # ... (add more fields as needed)

    # Store user data in DynamoDB
    table.put_item(Item={'UserId': user_id, 'UserName': user_name})

    return {
        'statusCode': 200,
        'body': 'Data stored successfully'
    }

Integrating API Gateway with Lambda

To create the API Gateway and integrate it with our Lambda function, follow these steps in the AWS Management Console:

  1. Open the API Gateway service in the AWS Management Console.

  2. Click on "Create API" and select "REST API" as the protocol.

  3. Choose the type of API you want to create. For this tutorial, we'll select "New API" and provide a name for our API.

  4. Define the API resources and methods:

    • Click on "Actions" and select "Create Resource" to define a resource for our API.

    • Specify the resource path, such as "/userdata" to represent the endpoint for user data.

    • Create a POST method for the resource to allow users to push data.

    • Configure the integration with AWS Lambda:

      • Select the Lambda function region and provide the Lambda function name we created earlier.

      • Click on "Save" to save the integration settings.

  5. Deploy the API:

    • Click on "Actions" and select "Deploy API."

    • Choose the deployment stage, such as "prod" or "dev," and click on "Deploy."

  6. Test the API:

    • Once the API is deployed, you will see an Invoke URL. Copy this URL for testing.

    • Use tools like cURL or Postman to send a POST request to the Invoke URL with user data in the request body.

    • Verify that the data is successfully stored in DynamoDB by checking the response and DynamoDB table.

Testing the Application

Now that we have our serverless application set up, let's test it to ensure everything is functioning as expected:

  1. Open a tool like Postman or any REST client of your choice.

  2. Set the request method to POST.

  3. Set the request URL to the API Gateway Invoke URL obtained during deployment.

  4. In the request body, provide user data in JSON format. For example:

     {
       "userId": "123",
       "userName": "John Doe"
     }
    
    1. Send the request and check the response.

      • If the data is successfully stored in DynamoDB, you should receive a response with a status code of 200 and a body message indicating successful storage.

      • In case of any errors or issues, check the response and verify the configurations of your Lambda function, API Gateway, and DynamoDB.

Conclusion

In this tutorial, we explored the process of building a serverless application using AWS services. We started by understanding the concept of serverless architecture and the benefits it offers. Then, we introduced key AWS services like AWS Lambda, API Gateway, and DynamoDB.

We went through the steps of creating a DynamoDB table using the AWS CLI and creating an API Gateway to provide a RESTful interface for our users. We developed a Python Lambda function that receives user data through the API Gateway and stores it in DynamoDB. Finally, we tested the application by sending requests to the API and verified the data storage.

Serverless architecture provides a flexible and scalable approach to application development, allowing developers to focus on writing code and delivering value. By leveraging AWS services, we can build robust and efficient serverless applications that scale with demand and minimize infrastructure management.

By following the steps outlined in this tutorial, you now have the knowledge and tools to create your serverless applications using AWS services. Experiment, explore, and unleash the full potential of serverless computing!

Remember to monitor and manage your AWS resources to optimize costs and ensure the smooth operation of your serverless applications. Happy serverless coding!