Skip to content
Kuza Ndoto Academy

Project: Serverless API

Beginner → IntermediateChapter 8 · Page 28 of 307 min readUpdated 15 Nov 2026

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 pathActionSuccess status
POST /notesCreate a note from JSON {"title": ..., "body": ...}201
GET /notesList notes, newest first200
GET /notes/{noteId}Fetch one note200 (404 if missing)
DELETE /notes/{noteId}Delete one note200
Clientcurl, web app HTTPS API GatewayHTTP API4 routes event Lambdaapp.py (Python) boto3 DynamoDBnotes table IAM execution role CloudWatch Logs
Figure 1. Each request flows left to right and the response returns the same way. The execution role allows the function to use only this one table and to write its logs.

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-identity works).
  • 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 HttpApi events make SAM create one HTTP API (logical ID ServerlessHttpApi) with a route for each event, all using Lambda proxy integration with payload format 2.0.
  • TABLE_NAME passes 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 DynamoDBCrudPolicy template 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 as GET /notes/{noteId}, which makes routing simple. Path values arrive in pathParameters.
  • 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=True keeps the JSON key order predictable, and default=str safely converts any DynamoDB Decimal values.
  • 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:

Key ApiUrl Description Base URL of the notes API Value https://abc123defg.execute-api.eu-west-1.amazonaws.com

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"}'
{"body": "Alkanes, alkenes and alkynes before Friday", "createdAt": "2026-11-15T07:42:10+00:00", "noteId": "3f6c1a52-8d1e-4b7a-9a0e-2c5d7e9f1b23", "title": "Revise organic chemistry"}
curl -s "$API/notes"
curl -s "$API/notes/3f6c1a52-8d1e-4b7a-9a0e-2c5d7e9f1b23"
[{"body": "Alkanes, alkenes and alkynes before Friday", "createdAt": "2026-11-15T07:42:10+00:00", "noteId": "3f6c1a52-8d1e-4b7a-9a0e-2c5d7e9f1b23", "title": "Revise organic chemistry"}] {"body": "Alkanes, alkenes and alkynes before Friday", "createdAt": "2026-11-15T07:42:10+00:00", "noteId": "3f6c1a52-8d1e-4b7a-9a0e-2c5d7e9f1b23", "title": "Revise organic chemistry"}

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"
{"error": "title is required"} {"error": "Note not found"} {"deleted": "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.

Warning

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:

  1. Check CloudFormation shows no kuza-notes stack.
  2. Delete the function's log group in CloudWatch → Log groups (named like /aws/lambda/kuza-notes-NotesFunction-...), because Lambda created it outside the stack.
  3. If sam delete did not remove it, empty and delete the SAM artifacts bucket that sam deploy --guided created (its name starts with aws-sam-cli-managed-default), or keep it for future SAM projects.

Extend it

  1. Add sign-in: create an Amazon Cognito user pool and attach a JWT authorizer to the HTTP API. Store a userId from the token with each note, change the table key to userId (partition) plus noteId (sort), and replace the scan with a query so users see only their own notes.
  2. Add editing: a PUT /notes/{noteId} route that uses update_item with a ConditionExpression so it fails cleanly if the note does not exist.
  3. 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 deploy and sam delete manage 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.
Up next · Practice & CareersAWS Certifications & Cloud CareersCertification paths and cloud jobs.
→

Tip: use the ← and → keys to move between pages.