Add a List All the Notes API

Now we are going to add an API that returns a list of all the notes a user has.

Add the Function

Create a new file called `list.ts` with the following.
import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
import { APIGatewayProxyHandler } from 'aws-lambda';
export const main: APIGatewayProxyHandler = async (event, context) => {
const params = {
TableName: process.env.tableName,
// 'KeyConditionExpression' defines the condition for the query
// - 'userId = :userId': only return items with matching 'userId'
// partition key
// 'ExpressionAttributeValues' defines the value in the condition
// - ':userId': defines 'userId' to be Identity Pool identity id
// of the authenticated user
KeyConditionExpression: "userId = :userId",
ExpressionAttributeValues: {
":userId": event.requestContext.identity.cognitoIdentityId
try {
const result = await"query", params);
// Return the matching list of items in response body
return success(result.Items);
} catch (e) {
return failure({ status: false });

Again update the ./libs/dynamodb-lib with the Input Type:

import * as AWS from "aws-sdk";
export function call(action: string, params: AWS.DynamoDB.DocumentClient.PutItemInput | AWS.DynamoDB.DocumentClient.GetItemInput | AWS.DynamoDB.DocumentClient.QueryInput) {
const dynamoDb = new AWS.DynamoDB.DocumentClient();
return dynamoDb[action](params).promise();

This is pretty much the same as our get.ts except we only pass in the userId in the DynamoDB query call.

Configure the API Endpoint

Open the `serverless.yml` file and append the following.
# Defines an HTTP API endpoint that calls the main function in list.ts
# - path: url path is /notes
# - method: GET request
handler: list.main
- http:
path: notes
method: get
cors: true
authorizer: aws_iam

This defines the /notes endpoint that takes a GET request.


Create a `mocks/list-event.json` file and add the following.
"requestContext": {
"identity": {
"cognitoIdentityId": "USER-SUB-1234"

And invoke our function from the root directory of the project.

$ serverless invoke local --function list --path mocks/list-event.json

The response should look similar to this.

statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true
body: '[{"attachment":"hello.jpg","content":"hello world","createdAt":1487800950620,"noteId":"578eb840-f70f-11e6-9d1a-1359b3b22944","userId":"USER-SUB-1234"}]'

Note that this API returns an array of note objects as opposed to the get.ts function that returns just a single note object.

Next we are going to add an API to update a note.