Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

CRUD API (HTTP API + Lambda + DynamoDB)

Introduction

In this lesson, we will explore how to create a CRUD (Create, Read, Update, Delete) API using AWS Serverless technologies, specifically AWS Lambda and DynamoDB. This architecture allows developers to build scalable applications without managing servers.

Key Concepts

What is CRUD?

CRUD refers to the four basic operations that can be performed on a data source:

  • Create: Add new data.
  • Read: Retrieve existing data.
  • Update: Modify existing data.
  • Delete: Remove existing data.

AWS Lambda

AWS Lambda is a serverless compute service that runs your code in response to events and automatically manages the underlying compute resources for you.

AWS DynamoDB

DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability.

Step-by-Step Guide

Follow these steps to create a CRUD API using AWS Lambda and DynamoDB:

  1. Set Up Your AWS Account: Sign up for AWS and log in.
  2. Create a DynamoDB Table:
    Tip: Use a primary key that uniquely identifies each item.
    
                    // Example Table Creation
                    const AWS = require('aws-sdk');
                    const dynamoDB = new AWS.DynamoDB();
    
                    const params = {
                        TableName: 'Users',
                        KeySchema: [
                            { AttributeName: 'userId', KeyType: 'HASH' } // Partition key
                        ],
                        AttributeDefinitions: [
                            { AttributeName: 'userId', AttributeType: 'S' }
                        ],
                        ProvisionedThroughput: {
                            ReadCapacityUnits: 5,
                            WriteCapacityUnits: 5
                        }
                    };
    
                    dynamoDB.createTable(params, function(err, data) {
                        if (err) console.log(err);
                        else console.log("Table created:", data);
                    });
                    
  3. Create Lambda Functions: Implement functions for each CRUD operation.
  4. Set Up API Gateway: Create an HTTP API to trigger your Lambda functions.
  5. Test Your API: Use tools like Postman to test all CRUD operations.

Lambda Function Example


        const AWS = require('aws-sdk');
        const dynamoDB = new AWS.DynamoDB.DocumentClient();

        exports.handler = async (event) => {
            const userId = event.pathParameters.userId;
            const params = {
                TableName: 'Users',
                Key: { userId }
            };

            try {
                const data = await dynamoDB.get(params).promise();
                return {
                    statusCode: 200,
                    body: JSON.stringify(data.Item)
                };
            } catch (error) {
                return {
                    statusCode: 500,
                    body: JSON.stringify({ error: error.message })
                };
            }
        };
        

Best Practices

  • Use environment variables to store sensitive information.
  • Implement API versioning to manage changes.
  • Enable logging and monitoring for Lambda functions using CloudWatch.
  • Optimize your DynamoDB queries to minimize costs.

FAQ

What is the cost of using AWS Lambda?

The cost of AWS Lambda is based on the number of requests and the duration of your code execution. You pay only for what you use.

Can I run my existing applications on AWS Lambda?

Yes, but you may need to refactor them to fit into a serverless architecture.

How does DynamoDB handle scalability?

DynamoDB automatically scales to adjust for capacity and maintain performance as your application grows.