Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 70 ยท Real-world projects

Project: Serverless REST API

Build a notes API with API Gateway, Lambda and DynamoDB: routes, a least-privilege IAM role, tests with event fixtures and an emulator that runs the handler.

This project builds a small but realistic REST API without a single server: API Gateway receives HTTPS requests, Lambda runs the handler and DynamoDB stores the data. The API is a personal notes service. A signed-in user can create a note, read one, list their own notes and delete one, and nobody can see anyone else's notes. You will define the data model, write the handler, give the function a least-privilege IAM role, deploy it with a template and test it with event fixtures.

The real services cannot run here, so the template, IAM policy and CLI commands are read-only. What you can run is the actual handler code: it is written so that the table is injected, which lets the emulator below feed it API Gateway style events and a fake DynamoDB table. That is also exactly how you would unit test it on your own machine. For the background see Lambda Functions, API Gateway and Function URLs and DynamoDB Fundamentals.

The design

flowchart LR
    C["Client app"] -- "HTTPS + JWT" --> GW["API Gateway HTTP API"]
    GW -- "validate token" --> JWT["JWT authorizer<br/>(Cognito or OIDC)"]
    GW -- "proxy event v2.0" --> L["Lambda: notes handler"]
    L -- "PutItem, GetItem,<br/>Query, DeleteItem" --> T[("DynamoDB table: notes")]
    L -. "logs" .-> CW["CloudWatch Logs"]

The authorizer checks the token before Lambda runs; Lambda sees only the verified claims.

The routes:

Route Action
POST /notes create a note for the caller
GET /notes list the caller's notes
GET /notes/{id} read one note
DELETE /notes/{id} delete one note

An HTTP API is the cheaper and simpler choice here. It has built-in JWT authorizers and sends the Lambda function the version 2.0 payload, in which the route is routeKey, path variables are pathParameters and the verified token claims arrive in requestContext.authorizer.jwt.claims. The sub claim is the user's stable id.

The data model

Think of the access patterns first (DynamoDB Data Modeling): "all notes of one user" and "one note of one user". That gives a table with partition key owner and sort key noteId.

  • List = Query on owner, no scan needed.
  • Read one = GetItem on (owner, noteId).
  • Isolation comes for free: every read and write includes the caller's own owner taken from the verified token, never from the request body or URL. A user cannot even name someone else's item.

Use on-demand capacity (PAY_PER_REQUEST) so an idle API costs almost nothing.

The handler

Here is the function. It reads the user from the claims, routes on routeKey and talks to a table object that is passed in. In the real file, table comes from boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"]), created once outside the handler so warm invocations reuse it.

Python
import json, os, uuid
import boto3
from boto3.dynamodb.conditions import Key

_table = None

def get_table():
    global _table
    if _table is None:
        _table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
    return _table

def lambda_handler(event, context):
    return make_handler(get_table())(event, context)

make_handler is the pure part with no AWS imports at call time, shown in the first emulator. Keeping logic in a function that takes its dependencies as arguments is the single most useful habit for testable Lambda code.

Stand-in 1: run the handler end to end

The emulator contains the real handler logic, a three-line stand-in for Key, and a fake table that mimics the four DynamoDB calls the handler uses. It then plays a scenario: two users, creation, listing, reading and deleting, plus bad input and a user trying to read a note that belongs to somebody else.

Python The notes API, run end to end with a fake table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the two interesting lines. Alice asking for n3 gets a 404, not a 403: because the key always includes her own owner, Bob's item simply does not exist from her point of view, and the API does not leak that it exists. And deleting twice returns 404 the second time, which makes the delete idempotent in effect.

Deploying with a template

With the AWS Serverless Application Model (SAM), which extends CloudFormation, the whole stack is one read-only file:

YAML
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31

Resources:
  NotesTable:
    Type: AWS::DynamoDB::Table
    Properties:
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - { AttributeName: owner, AttributeType: S }
        - { AttributeName: noteId, AttributeType: S }
      KeySchema:
        - { AttributeName: owner, KeyType: HASH }
        - { AttributeName: noteId, KeyType: RANGE }

  NotesFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.lambda_handler
      Runtime: python3.13
      Timeout: 5
      MemorySize: 256
      Environment:
        Variables:
          TABLE_NAME: !Ref NotesTable
      Policies:
        - Statement:
            - Effect: Allow
              Action:
                - dynamodb:PutItem
                - dynamodb:GetItem
                - dynamodb:Query
                - dynamodb:DeleteItem
              Resource: !GetAtt NotesTable.Arn
      Events:
        Create: { Type: HttpApi, Properties: { Method: POST,   Path: /notes,      ApiId: !Ref Api } }
        List:   { Type: HttpApi, Properties: { Method: GET,    Path: /notes,      ApiId: !Ref Api } }
        Read:   { Type: HttpApi, Properties: { Method: GET,    Path: "/notes/{id}", ApiId: !Ref Api } }
        Delete: { Type: HttpApi, Properties: { Method: DELETE, Path: "/notes/{id}", ApiId: !Ref Api } }

  Api:
    Type: AWS::Serverless::HttpApi
    Properties:
      Auth:
        DefaultAuthorizer: JwtAuth
        Authorizers:
          JwtAuth:
            IdentitySource: $request.header.Authorization
            JwtConfiguration:
              issuer: https://cognito-idp.eu-west-1.amazonaws.com/eu-west-1_EXAMPLE
              audience: [example-client-id]
Terminal
sam build
sam deploy --guided
curl -H "Authorization: Bearer $TOKEN" -X POST "$API_URL/notes" -d '{"text":"hello"}'

Check the policy: four actions, one table ARN, nothing else. SAM adds the basic Lambda logging permissions itself. That brevity is the point of the next section.

Least privilege, and how to prove it

The role does not allow dynamodb:Scan, UpdateItem, BatchWriteItem or any other table, any S3 bucket, or any wildcard. If a bug or an injected payload makes the function call something unexpected, IAM refuses it. The method to find the minimal list is the same as in IAM Best Practices and Least Privilege: start from what the code calls, write exactly those actions, and later compare with real usage in CloudTrail or Access Analyzer.

Stand-in 2: fixtures, tests and a policy check

Event fixtures are plain JSON files saved from real API Gateway calls (or hand-written) and replayed in tests. The second emulator replays fixtures against the handler, asserts the results, and wraps the table in an enforcing table that rejects any action missing from the role's allow list. It also reports which allowed actions were never used, a sign that the policy could be tighter. To keep this block self-contained it repeats the handler with a deliberately lazy GET /notes implementation that uses scan, so you can watch least privilege catch it.

Python Replay fixtures and enforce a least-privilege policy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first run passes every fixture and shows DeleteItem as allowed but unused, since no fixture deletes anything: either add a delete fixture or drop the permission. The second run shows the failure mode in production: a code path that needs an unlisted action is denied at run time, so tests with an enforcing fake catch it before deployment. A real check also exists in the cloud: invoke the deployed function once and read the denial in CloudWatch Logs.

What to add next

  • Validation and limits. Cap the text length and the list size, and paginate Query with LastEvaluatedKey.
  • Throttling. Set stage-level rate limits on the API (API Gateway and Function URLs).
  • Observability. Log one structured JSON line per request with a request id, and add an alarm on 5xx responses (CloudWatch).
  • Cold starts. Python with boto3 initialised outside the handler is usually fine; measure before paying for provisioned concurrency (Lambda Concurrency, Cold Starts and Limits).
  • Cleanup. sam delete removes the whole stack, so experiments cost nothing afterward.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the handler take the owner from the verified token claims instead of the request body?

    Only the authorizer-verified claims can be trusted. Using them in every key makes cross-user access impossible by construction.
  2. 2. Which pair of operations fits the access patterns 'list my notes' and 'read one of my notes'?

    With owner as the partition key and noteId as the sort key, listing is a single-partition Query and reading is a keyed GetItem.
  3. 3. A function's role allows only PutItem, GetItem, Query and DeleteItem. The code calls Scan. What happens?

    IAM denies anything not explicitly allowed, which is exactly why a minimal policy limits the damage of bugs.
  4. 4. Why build the handler as make_handler(table) rather than creating the boto3 client inside the logic?

    Dependency injection keeps the logic pure and testable. The real table is created once outside the handler and passed in.

Summary

  • A serverless REST API is API Gateway (routing and JWT auth), Lambda (handler) and DynamoDB (on-demand table keyed for the access patterns).
  • Take the caller's identity from verified claims and put it in every key; isolation then needs no extra checks.
  • Give the function a role with exactly the actions and the one table ARN it uses.
  • Write the handler with an injected table so event fixtures and a fake table can test it locally.
  • Compare allowed actions with used actions to find over-permission, and keep the stack in a template so it can be deleted cleanly.

Next: Project: Three-Tier Web App.