Project: Serverless API
In this project you build Kuza Notes, a small REST API for saving study notes, using three serverless services: API Gateway (an HTTP API) receives requests, Lambda runs Python code, and DynamoDB stores the notes. You deploy it all with one template, test it with curl and then delete it cleanly.
Goal and features
The API will support four routes:
| Method and path | Action | Success status |
|---|---|---|
POST /notes | Create a note from JSON {"title": ..., "body": ...} | 201 |
GET /notes | List notes, newest first | 200 |
GET /notes/{noteId} | Fetch one note | 200 (404 if missing) |
DELETE /notes/{noteId} | Delete one note | 200 |
Before you start
- Budget alerts are set up (see Creating an AWS Account Safely).
- The AWS CLI v2 is signed in with an SSO profile (
aws sts get-caller-identityworks). - The AWS SAM CLI is installed (see the SAM documentation for your OS), and Python 3.13 is available locally for
sam build.
Create this folder structure:
kuza-notes/
├── template.yaml
└── src/
├── app.py
└── requirements.txt (empty: boto3 is included in the Lambda runtime)
Step 1: The template
template.yaml uses SAM to define the table, the function, its permissions and the four API routes:
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Kuza Notes - a serverless notes API
Globals:
Function:
Runtime: python3.13
Timeout: 10
MemorySize: 256
Resources:
NotesTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: noteId
AttributeType: S
KeySchema:
- AttributeName: noteId
KeyType: HASH
NotesFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: app.lambda_handler
Environment:
Variables:
TABLE_NAME: !Ref NotesTable
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref NotesTable
Events:
ListNotes:
Type: HttpApi
Properties:
Path: /notes
Method: GET
CreateNote:
Type: HttpApi
Properties:
Path: /notes
Method: POST
GetNote:
Type: HttpApi
Properties:
Path: /notes/{noteId}
Method: GET
DeleteNote:
Type: HttpApi
Properties:
Path: /notes/{noteId}
Method: DELETE
Outputs:
ApiUrl:
Description: Base URL of the notes API
Value: !GetAtt ServerlessHttpApi.ApiEndpoint
- The
HttpApievents make SAM create one HTTP API (logical IDServerlessHttpApi) with a route for each event, all using Lambda proxy integration with payload format 2.0. TABLE_NAMEpasses the generated table name to the code, so nothing is hard-coded.- SAM gives the function an execution role with basic logging permissions, plus the
DynamoDBCrudPolicytemplate scoped to this one table.
The IAM permissions, explained
If you built this by hand in the console instead, you would create an execution role trusted by lambda.amazonaws.com, attach the managed policy AWSLambdaBasicExecutionRole for logs, and add a least-privilege inline policy like this one (with your Region, account ID and table name):
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "NotesTableAccess",
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:GetItem",
"dynamodb:DeleteItem",
"dynamodb:Scan"
],
"Resource": "arn:aws:dynamodb:eu-west-1:123456789012:table/kuza-notes-NotesTable-ABC123"
}
]
}
SAM's DynamoDBCrudPolicy allows a few more actions (such as UpdateItem and Query), still limited to this table. Either way, the function cannot touch any other table or service.
Step 2: The function
src/app.py
import base64
import json
import os
import uuid
from datetime import datetime, timezone
import boto3
TABLE = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
def response(status, body):
return {
"statusCode": status,
"headers": {"Content-Type": "application/json"},
"body": json.dumps(body, default=str, sort_keys=True),
}
def read_json_body(event):
raw = event.get("body") or "{}"
if event.get("isBase64Encoded"):
raw = base64.b64decode(raw).decode("utf-8")
return json.loads(raw)
def lambda_handler(event, context):
route = event["routeKey"] # for example "POST /notes"
params = event.get("pathParameters") or {}
if route == "GET /notes":
items = TABLE.scan(Limit=50).get("Items", [])
items.sort(key=lambda note: note["createdAt"], reverse=True)
return response(200, items)
if route == "POST /notes":
try:
data = read_json_body(event)
except (json.JSONDecodeError, UnicodeDecodeError):
return response(400, {"error": "Body must be valid JSON"})
title = str(data.get("title", "")).strip()
if not title:
return response(400, {"error": "title is required"})
note = {
"noteId": str(uuid.uuid4()),
"title": title[:100],
"body": str(data.get("body", ""))[:2000],
"createdAt": datetime.now(timezone.utc).isoformat(timespec="seconds"),
}
TABLE.put_item(Item=note)
return response(201, note)
if route == "GET /notes/{noteId}":
item = TABLE.get_item(Key={"noteId": params["noteId"]}).get("Item")
if item is None:
return response(404, {"error": "Note not found"})
return response(200, item)
if route == "DELETE /notes/{noteId}":
TABLE.delete_item(Key={"noteId": params["noteId"]})
return response(200, {"deleted": params["noteId"]})
return response(404, {"error": "Route not found"})
How it works:
- The table object is created outside the handler, so warm invocations reuse it.
- HTTP API events include
routeKey, such asGET /notes/{noteId}, which makes routing simple. Path values arrive inpathParameters. - The request body arrives as a string (base64-encoded for some content types), so it is decoded and parsed with
json.loads. - Every response has a
statusCode, a JSON content-type header and a string body.sort_keys=Truekeeps the JSON key order predictable, anddefault=strsafely converts any DynamoDBDecimalvalues. - Input is validated and trimmed, so a client cannot store a 5 MB "title".
Step 3: Build and deploy
cd kuza-notes sam validate sam build sam deploy --guided --profile kuza-admin
The guided deploy asks a few questions. Answer roughly like this, then confirm the change set:
Stack Name [sam-app]: kuza-notes AWS Region [eu-west-1]: eu-west-1 Confirm changes before deploy [y/N]: y Allow SAM CLI IAM role creation [Y/n]: Y Disable rollback [y/N]: N NotesFunction has no authentication. Is this okay? [y/N]: y (asked once per route; exact wording varies by SAM CLI version) Save arguments to configuration file [Y/n]: Y
When it finishes, SAM prints the stack outputs. Your API ID will differ:
Next time, sam build && sam deploy reuses the saved answers in samconfig.toml.
Step 4: Test with curl
Store the URL in a shell variable (macOS/Linux/Git Bash), then try each route. IDs and times in the outputs will differ for you:
API=https://abc123defg.execute-api.eu-west-1.amazonaws.com
curl -s -X POST "$API/notes" \
-H "Content-Type: application/json" \
-d '{"title": "Revise organic chemistry", "body": "Alkanes, alkenes and alkynes before Friday"}'
curl -s "$API/notes" curl -s "$API/notes/3f6c1a52-8d1e-4b7a-9a0e-2c5d7e9f1b23"
Now check the error handling and deletion:
curl -s -X POST "$API/notes" -H "Content-Type: application/json" -d '{"body": "no title"}'
curl -s "$API/notes/does-not-exist"
curl -s -X DELETE "$API/notes/3f6c1a52-8d1e-4b7a-9a0e-2c5d7e9f1b23"
If something fails, read the function's logs: sam logs --stack-name kuza-notes --name NotesFunction --tail. A 500 error with {"message":"Internal Server Error"} usually means the function raised an exception or returned a response without a string body.
This practice API has no authentication: anyone who learns the URL can create and delete notes, and every request costs a little money. Do not store personal data in it, do not share the URL publicly, and delete the stack when you finish. Extension idea 1 below adds proper sign-in.
Step 5: Clean up
sam delete --stack-name kuza-notes
This deletes the API, the function, its role and the DynamoDB table (with its data). Then:
- Check CloudFormation shows no
kuza-notesstack. - Delete the function's log group in CloudWatch → Log groups (named like
/aws/lambda/kuza-notes-NotesFunction-...), because Lambda created it outside the stack. - If
sam deletedid not remove it, empty and delete the SAM artifacts bucket thatsam deploy --guidedcreated (its name starts withaws-sam-cli-managed-default), or keep it for future SAM projects.
Extend it
- Add sign-in: create an Amazon Cognito user pool and attach a JWT authorizer to the HTTP API. Store a
userIdfrom the token with each note, change the table key touserId(partition) plusnoteId(sort), and replace the scan with aqueryso users see only their own notes. - Add editing: a
PUT /notes/{noteId}route that usesupdate_itemwith aConditionExpressionso it fails cleanly if the note does not exist. - Add a front end and reminders: host a small HTML and JavaScript page on S3 and CloudFront (see Hosting a Static Website), enable CORS on the API, and use EventBridge Scheduler with SNS to send a reminder before an exam date stored in the note.
Key points
- API Gateway, Lambda and DynamoDB together make an API with no servers to manage and no cost when idle beyond storage.
- SAM defines the whole stack in one template;
sam build,sam deployandsam deletemanage its lifecycle. - Lambda proxy responses need a status code, headers and a string body.
- Give the function least-privilege access to only its own table.
- Always delete practice stacks and leftover log groups.
Tip: use the ← and → keys to move between pages.
