AWS Builder Center
Build Your First Serverless REST API with AWS API Gateway, Lambda and DynamoDB

Build Your First Serverless REST API with AWS API Gateway, Lambda and DynamoDB

Learn how to build a serverless Task Manager REST API using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB. This hands-on tutorial covers CRUD operations, Python implementation, database integration, IAM permissions, deployment, and API testing using Postman. A beginner-friendly introduction to building serverless applications on AWS.

CS undergrad exploring AWS and cloud computing
Introduction
Modern applications need APIs to communicate with databases, process requests, and manage information.
Traditionally, building an API requires setting up servers, configuring infrastructure, and managing application deployments.
But what if we could build an API without managing servers?
AWS provides several services that make this possible. By combining Amazon API Gateway, AWS Lambda, and Amazon DynamoDB, we can create a fully serverless REST API.
In this tutorial, we will build a simple Task Manager API that allows users to:
- Create a task. - View all tasks. - Retrieve a specific task. - Update an existing task. - Delete a task.
We will use Python for the Lambda function and DynamoDB to store task information.
By the end, you will understand how these AWS services work together to build a practical serverless application.
1. Understanding the Architecture
Our application will use three main AWS services.
Amazon API Gateway
API Gateway acts as the entry point for our application. It receives HTTP requests and forwards them to the appropriate Lambda function.
AWS Lambda
Lambda executes our Python code whenever an API request is received. We do not need to manage or maintain servers.
Amazon DynamoDB
DynamoDB is a fully managed NoSQL database that stores our tasks and allows Lambda to retrieve or modify them.
Application Architecture
The workflow looks like this:
User / Client
|
|
API Gateway
|
|
AWS Lambda
|
|
Amazon DynamoDB
|
Task Information
The user sends an HTTP request to API Gateway. API Gateway invokes Lambda, which processes the request and interacts with DynamoDB.
The result is then returned to the user as an HTTP response.
2. Prerequisites
Before starting, make sure you have:
- An active AWS account. - Basic knowledge of Python. - Basic understanding of HTTP methods and REST APIs. - Familiarity with AWS IAM permissions. - Postman or curl for testing API endpoints.
We will use Python 3.12 as our Lambda runtime.
3. Create a DynamoDB Table
First, we need a database to store our tasks.
Follow these steps:
1. Open the AWS Management Console. 2. Navigate to Amazon DynamoDB. 3. Select Tables and click Create table. 4. Enter the following configuration:
Setting| Value Table name| Tasks Partition key| taskId Key type| String Sort key| Not required
Keep the remaining settings at their default values and create the table.
Understanding the Data Structure
Each task will be stored as an item in DynamoDB.
For example:
{ "taskId": "task-101", "title": "Learn AWS Lambda", "description": "Understand serverless computing", "completed": false, "createdAt": "2026-11-08T10:00:00Z" }
The "taskId" attribute uniquely identifies each task.
4. Create the AWS Lambda Function
Now we need a Lambda function to handle our API requests.
Follow these steps:
1. Open AWS Lambda. 2. Click Create function. 3. Select Author from scratch. 4. Enter the following details:
Setting| Value Function name| TaskManagerFunction Runtime| Python 3.12 Architecture| x86_64 Permissions| Create a new execution role
Click Create function.
Configure Environment Variables
Open the Configuration tab and select Environment variables.
Add:
TABLE_NAME = Tasks
This allows our Lambda function to identify the DynamoDB table without hardcoding its name.
Lambda Function Code
Open the Code tab and replace the existing code with:
import json import boto3 import os import uuid from datetime import datetime, timezone
dynamodb = boto3.resource("dynamodb") table = dynamodb.Table(os.environ["TABLE_NAME"])
def response(status, body): return { "statusCode": status, "headers": { "Content-Type": "application/json" }, "body": json.dumps(body) }
def handler(event, context): try: method = event["requestContext"]["http"]["method"] task_id = event.get("pathParameters", {}).get("taskId")
\# Create a task
if method == "POST":
data = json.loads(event.get("body") or "\{}")

if not isinstance(data, dict) or not isinstance(
data.get("title"), str
) or not data\["title"].strip():
return response(400, \{"message": "Valid title is required"})

task = \{
"taskId": str(uuid.uuid4()),
"title": data\["title"].strip(),
"description": data.get("description", ""),
"completed": False,
"createdAt": datetime.now(
timezone.utc
).isoformat()
}

table.put\_item(Item=task)

return response(201, task)

\# Get all tasks
if method == "GET" and not task\_id:
result = table.scan()
return response(200, result.get("Items", \[]))

\# Get a specific task
if method == "GET" and task\_id:
result = table.get\_item(Key=\{"taskId": task\_id})

if "Item" not in result:
return response(404, \{"message": "Task not found"})

return response(200, result\["Item"])

\# Update a task
if method == "PUT" and task\_id:
data = json.loads(event.get("body") or "\{}")

allowed = \["title", "description", "completed"]
updates = \{
key: data\[key]
for key in allowed
if key in data
}

if not updates:
return response(400, \{"message": "No valid fields to update"})

names = \{}
values = \{}
expressions = \[]

for key, value in updates.items():
names\[f"#\{key}"] = key
values\[f":\{key}"] = value
expressions.append(f"#\{key} = :\{key}")

result = table.update\_item(
Key=\{"taskId": task\_id},
UpdateExpression="SET " + ", ".join(expressions),
ExpressionAttributeNames=names,
ExpressionAttributeValues=values,
ConditionExpression="attribute\_exists(taskId)",
ReturnValues="ALL\_NEW"
)

return response(200, result\["Attributes"])

\# Delete a task
if method == "DELETE" and task\_id:
table.delete\_item(
Key=\{"taskId": task\_id},
ConditionExpression="attribute\_exists(taskId)"
)

return response(200, \{"message": "Task deleted successfully"})

return response(405, \{"message": "Method not allowed"})

except json.JSONDecodeError:
return response(400, \{"message": "Invalid JSON"})

except Exception as error:
if error.response\["Error"]\["Code"] == "ConditionalCheckFailedException":
return response(404, \{"message": "Task not found"})

print("Application error:", str(error))
return response(500, \{"message": "Internal server error"})
This function handles all five operations using the HTTP method and optional task ID.
The example uses DynamoDB's "Scan" operation to retrieve all tasks. This is suitable for a small learning project, but production applications should consider pagination and more efficient query patterns.
5. Configure IAM Permissions
Our Lambda function needs permission to communicate with DynamoDB.
Open:
IAM → Roles → TaskManagerFunction execution role.
Attach a custom policy with the following permissions:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "dynamodb:PutItem", "dynamodb:GetItem", "dynamodb:Scan", "dynamodb:UpdateItem", "dynamodb:DeleteItem" ], "Resource": "arn:aws:dynamodb:YOUR_REGION:YOUR_ACCOUNT_ID:table/Tasks" } ] }
Replace "YOUR_REGION" and "YOUR_ACCOUNT_ID" with your AWS details.
This follows the Principle of Least Privilege by granting only the DynamoDB operations required by our application on the specific table.
6. Create an API Using Amazon API Gateway
Now we need to expose our Lambda function through HTTP endpoints.
Follow these steps:
1. Open Amazon API Gateway. 2. Select Create API. 3. Choose HTTP API. 4. Click Build. 5. Add an integration with "TaskManagerFunction".
Create the following routes:
HTTP Method| Route| Purpose POST| /tasks| Create a task GET| /tasks| Retrieve all tasks GET| /tasks/{taskId}| Retrieve a specific task PUT| /tasks/{taskId}| Update a task DELETE| /tasks/{taskId}| Delete a task
Connect all five routes to the same Lambda integration.
Create a stage and enable automatic deployment.
After deployment, copy the API endpoint.
For example:
Your API is now accessible through these endpoints.
7. Test the Application
We can use Postman to test our API.
Replace the example API URL with your actual API Gateway endpoint.
Test 1: Create a Task
Send a POST request:
POST /tasks
Request body:
{ "title": "Learn AWS", "description": "Build my first serverless application" }
Expected response: HTTP 201 Created.
{ "taskId": "generated-task-id", "title": "Learn AWS", "description": "Build my first serverless application", "completed": false, "createdAt": "2026-11-08T10:00:00Z" }
Test 2: Retrieve All Tasks
Send a GET request:
GET /tasks
This returns the tasks stored in DynamoDB.
Test 3: Retrieve a Specific Task
Send:
GET /tasks/generated-task-id
This retrieves the task matching the supplied ID.
Test 4: Update a Task
Send a PUT request:
PUT /tasks/generated-task-id
Request body:
{ "completed": true }
The task's completion status will be updated.
Test 5: Delete a Task
Send:
DELETE /tasks/generated-task-id
Expected response:
{ "message": "Task deleted successfully" }
You have now implemented all the basic CRUD operations.
8. Security and Optimization Considerations
Our application works, but there are several improvements worth considering before using it in production.
1. Input Validation
Validate incoming request data and reject invalid or unexpected values.
2. IAM Security
Avoid unrestricted permissions such as "Action: "*"" and restrict access to the required DynamoDB table.
3. API Throttling
Configure API Gateway throttling to control excessive requests and reduce abuse.
4. Monitoring
Use Amazon CloudWatch to monitor Lambda invocations, execution duration, errors, and application logs.
5. Authentication
For applications with multiple users, consider Amazon Cognito or another authentication mechanism. Ensure users can access only their own tasks.
6. Database Optimization
Avoid using DynamoDB Scan for large datasets. Use Query with an appropriate partition key and consider pagination.
7. Cost Management
Monitor API Gateway requests, Lambda execution, DynamoDB read/write activity, and storage usage.
9. Conclusion
In this tutorial, we built a serverless Task Manager REST API using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB.
We learned how to:
- Create and configure a DynamoDB table. - Develop a Python-based Lambda function. - Configure IAM permissions. - Expose HTTP endpoints through API Gateway. - Implement Create, Read, Update, and Delete operations. - Test API endpoints using Postman.
The biggest advantage of this architecture is that we do not need to provision or maintain traditional application servers.
AWS manages the underlying infrastructure, allowing developers to focus on application logic and functionality.
This project is a great starting point for understanding how serverless applications work in real-world environments.
What's Next?
Try extending this project by adding user authentication, task deadlines, filtering, pagination, and notifications using Amazon EventBridge.
Building small applications like this is one of the best ways to turn theoretical AWS knowledge into practical cloud development skills.
Thanks for reading
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article