Building a Serverless Application with AWS Lambda and API Gateway

Introduction
Serverless architecture is revolutionizing cloud computing by allowing developers to focus on writing code without worrying about infrastructure management. AWS Lambda, in combination with Amazon API Gateway and DynamoDB, provides a powerful stack for building highly scalable and cost-efficient applications.
This article walks through the process of building a serverless application using AWS Lambda, API Gateway, and DynamoDB. We will create a simple RESTful API with CRUD operations, demonstrating how serverless functions scale automatically and eliminate infrastructure concerns.
Why Choose Serverless?
Serverless computing offers several advantages:
Automatic Scaling: AWS Lambda scales up or down based on the number of incoming requests.
Cost Efficiency: You only pay for the compute time consumed during function execution.
Reduced Operational Overhead: No need to manage servers, patches, or scaling.
Seamless Integration: Easily integrates with AWS services like DynamoDB, S3, and SNS.
Prerequisites
To follow along, you need:
An AWS account.
Basic knowledge of Python or Node.js.
AWS CLI installed and configured.
Serverless Framework (optional but recommended for deployment).
Architecture Overview
Our serverless application will consist of:
AWS Lambda: Handles API requests and interacts with DynamoDB.
API Gateway: Exposes Lambda functions as HTTP endpoints.
DynamoDB: Stores and retrieves application data.
Step 1: Setting Up DynamoDB
DynamoDB is a NoSQL database optimized for speed and scalability.
Creating a DynamoDB Table
Go to the AWS Management Console.
Navigate to DynamoDB and click Create table.
Set the table name as
Items
.Define a Partition Key (Primary Key) as
id
(String).Click Create table.
Step 2: Writing the AWS Lambda Function
AWS Lambda executes the application logic when triggered by API Gateway.
Installing Required Packages
For Python:
pip install boto3
For Node.js:
npm install aws-sdk
Creating a Lambda Function
Python Implementation
import json
import boto3
import uuid
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("Items")
def lambda_handler(event, context):
try:
body = json.loads(event["body"])
item_id = str(uuid.uuid4())
item_name = body["name"]
table.put_item(
Item={
"id": item_id,
"name": item_name,
}
)
return {
"statusCode": 200,
"body": json.dumps({"id": item_id, "name": item_name}),
}
except Exception as e:
return {"statusCode": 500, "body": json.dumps(str(e))}
Node.js Implementation
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB.DocumentClient();
const { v4: uuidv4 } = require("uuid");
exports.handler = async (event) => {
try {
const body = JSON.parse(event.body);
const itemId = uuidv4();
await dynamodb.put({
TableName: "Items",
Item: {
id: itemId,
name: body.name,
},
}).promise();
return {
statusCode: 200,
body: JSON.stringify({ id: itemId, name: body.name }),
};
} catch (error) {
return { statusCode: 500, body: JSON.stringify(error.message) };
}
};
Step 3: Deploying Lambda with API Gateway
Creating an API Gateway
Go to API Gateway in the AWS Console.
Click Create API → HTTP API.
Define an Integration and select Lambda Function.
Attach the Lambda function created earlier.
Deploy the API and note the generated endpoint.
Step 4: Testing the API
Use Postman or cURL to send a request:
curl -X POST "<API_ENDPOINT>" \
-H "Content-Type: application/json" \
-d '{"name": "Sample Item"}'
If successful, the response will include an item ID:
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"name": "Sample Item"
}
Step 5: Adding More CRUD Operations
Fetching an Item (GET)
Python Lambda Function:
def lambda_handler(event, context):
item_id = event["pathParameters"]["id"]
response = table.get_item(Key={"id": item_id})
return {"statusCode": 200, "body": json.dumps(response.get("Item", {}))}
Updating an Item (PUT)
Python Lambda Function:
def lambda_handler(event, context):
body = json.loads(event["body"])
item_id = event["pathParameters"]["id"]
table.update_item(
Key={"id": item_id},
UpdateExpression="set name = :n",
ExpressionAttributeValues={":n": body["name"]},
)
return {"statusCode": 200, "body": json.dumps({"message": "Updated successfully"})}
Deleting an Item (DELETE)
Python Lambda Function:
def lambda_handler(event, context):
item_id = event["pathParameters"]["id"]
table.delete_item(Key={"id": item_id})
return {"statusCode": 200, "body": json.dumps({"message": "Deleted successfully"})}
Conclusion
AWS Lambda, API Gateway, and DynamoDB offer a powerful combination for building serverless applications. With automatic scaling and minimal infrastructure management, developers can focus on business logic without worrying about servers.
By following this guide, you now have a working serverless REST API that handles CRUD operations efficiently. You can further enhance the application by adding authentication with AWS Cognito, monitoring with AWS CloudWatch, and deploying with the Serverless Framework.
Subscribe to my newsletter
Read articles from The DevOps Dojo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
