Now that we created a note and saved it to our database, let’s add an API to retrieve a note given its id.

Add the Function

Create a new file in backend/functions/get.js in your project root with the following:

import handler from "../util/handler";
import dynamoDb from "../util/dynamodb";

export const main = handler(async (event) => {
  const params = {
    TableName: process.env.TABLE_NAME,
    // 'Key' defines the partition key and sort key of the item to be retrieved
    Key: {
      userId: "123", // The id of the author
      noteId: event.pathParameters.id, // The id of the note from the path
    },
  };

  const result = await dynamoDb.get(params);
  if (!result.Item) {
    throw new Error("Item not found.");
  }

  // Return the retrieved item
  return result.Item;
});

This follows exactly the same structure as our previous create.js function. The major difference here is that we are doing a dynamoDb.get(params) to get a note object given the userId (still hardcoded) and noteId that’s passed in through the request.

Add the route

Let’s add a new route for the get note API.

Add the following below the POST /notes route in stacks/ApiStack.js.

"GET /notes/{id}": "functions/get.main",

Deploy our changes

If you switch over to your terminal, you’ll notice that you are being prompted to redeploy your changes. Go ahead and hit ENTER.

Note that, you’ll need to have sst start running for this to happen. If you had previously stopped it, then running npx sst start will deploy your changes again.

You should see that the API stack is being updated.

Stack dev-notes-ApiStack
  Status: deployed
  Outputs:
    ApiEndpoint: https://5bv7x0iuga.execute-api.us-east-1.amazonaws.com

Test the API

Let’s test the get notes API. In the previous chapter we tested our create note API. It should’ve returned the new note’s id as the noteId.

Head back to the API tab in the SST Console and select the /notes/{id} API.

Set the noteId as the id and click Send.

You should see the note being returned in the response.

SST Console get note API request

Next, let’s create an API to list all the notes a user has.