AWS Builder Center

Building a Serverless Expense Tracker API with AWS Lambda, API Gateway, and DynamoDB

A beginner-friendly walkthrough of building and deploying a REST API on AWS without managing any servers, including the mistakes I made and how I fixed them.

Introduction

I'm a final-year CS student, and I wanted to learn how backends work on AWS without managing servers. So I rebuilt a simple expense tracker, something I had already built in C++, as a serverless REST API. In this article, I'll walk through how I built it with AWS Lambda, API Gateway, and DynamoDB, and the mistakes I made along the way.
By the end, you'll have an API with two endpoints:
  •  POST /expenses  adds an expense
  •  GET /expenses  lists all expenses

Architecture

Client (curl/Postman) → API Gateway (HTTP API) → Lambda (Python) → DynamoDB
[Add a simple diagram or screenshot here]

Prerequisites

  • An AWS account (everything here fits within the free tier, but check current limits)
  • Basic Python knowledge
  •  curl  or Postman for testing

Step 1: Create the DynamoDB table

  1. Open the DynamoDB console and choose Create table.
  1. Table name:  Expenses 
  1. Partition key:  expenseId  (type: String)
  1. Keep the default settings (on-demand capacity is a good choice for a small project).
[Screenshot of the created table]

Step 2: Create the Lambda function

  1. Open the Lambda console and choose Create function → Author from scratch.
  1. Name:  expense-handler , Runtime: a current Python version.
  1. Paste in this code:
import json
import os
import uuid
from decimal import Decimal
import boto3
table = boto3.resource("dynamodb").Table(os.environ.get("TABLE_NAME", "Expenses"))
def response(status, body):
return {
"statusCode": status,
"headers": {"Content-Type": "application/json"},
"body": json.dumps(body, default=str), # default=str handles DynamoDB Decimals
}
def lambda_handler(event, context):
route = event["routeKey"]
if route == "POST /expenses":
data = json.loads(event.get("body") or "{}")
if "amount" not in data or "category" not in data:
return response(400, {"error": "amount and category are required"})
item = {
"expenseId": str(uuid.uuid4()),
"amount": Decimal(str(data["amount"])),
"category": data["category"],
"note": data.get("note", ""),
}
table.put_item(Item=item)
return response(201, item)
if route == "GET /expenses":
items = table.scan().get("Items", [])
return response(200, items)
return response(404, {"error": "Not found"})
  1. Choose Deploy.
Why  Decimal ? DynamoDB doesn't accept Python floats, so numbers must be converted to  Decimal . [Mention if you hit this error yourself.]

Step 3: Give Lambda permission to use DynamoDB

By default, Lambda can't touch your table. In the function's Configuration → Permissions, open its execution role in IAM and add a policy allowing only what's needed:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["dynamodb:PutItem", "dynamodb:Scan"],
"Resource": "arn:aws:dynamodb:<region>:<account-id>:table/Expenses"
}
]
}
This follows the principle of least privilege: the function can add and read items, and nothing else.

Step 4: Create the API in API Gateway

  1. Open API Gateway and create an HTTP API.
  1. Add a Lambda integration pointing to  expense-handler .
  1. Add two routes:  POST /expenses  and  GET /expenses .
  1. Deploy with the default stage and copy the Invoke URL.
[Screenshot of the routes]

Step 5: Test it

Add an expense:
curl -X POST https://<your-api-id>.execute-api.<region>.amazonaws.com/expenses \
-H "Content-Type: application/json" \
-d '{"amount": 250, "category": "food", "note": "lunch"}'
List expenses:
curl https://<your-api-id>.execute-api.<region>.amazonaws.com/expenses
A successful  POST  returns something like this (your  expenseId  will differ):
{"expenseId": "3f2b8c1e-9a4d-4c7e-b1a2-5d6e7f8a9b0c", "amount": "250", "category": "food", "note": "lunch"}
Note that  amount  comes back as a string. That's because my code uses  default=str  to serialize DynamoDB's  Decimal  type. It's fine for a demo, but a production API should convert it back to a number.

What went wrong (and how I fixed it)

Common pitfalls

These are the issues most likely to trip you up in this build:
  1.  AccessDeniedException  from DynamoDB. The Lambda execution role has no permission on the table by default. Fix: attach the least-privilege policy from Step 3, and make sure the table name and region in the ARN match yours.
  1.  Float types are not supported . DynamoDB rejects Python floats. Fix: convert with  Decimal(str(value)) , as in the code above.
  1.  KeyError: 'routeKey' . This happens if the API was created as a REST API instead of an HTTP API, because the event format differs. Fix: create an HTTP API, as in Step 4.
  1. A generic  Internal Server Error . The API response hides the real cause. Fix: open the function's Monitor → CloudWatch Logs and read the stack trace.

Limitations and next steps

  •  Scan  reads the whole table, which is fine for a demo but won't scale. For real use, you'd design a key schema around your query patterns.
  • No authentication yet. Adding Amazon Cognito or an API key would be the next step.
  • Adding  PUT  and  DELETE  routes would make it a full CRUD API.

Cleanup

To avoid unexpected charges, delete the API Gateway API, the Lambda function, and the DynamoDB table when you're done.

What I learned

Key takeaways

  • Serverless means you deploy code and configuration, not machines, but you still need to understand permissions.
  • IAM is the most common source of errors, and least-privilege policies are worth the extra minutes.
  • DynamoDB rewards designing your keys around your queries, which is why  Scan  is only a demo shortcut.
  • CloudWatch Logs is the first place to look when something fails.
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