Add a Create Note API

Like some other people here, I’m also getting a “Requested resource not found” error when running $ serverless invoke local --function create --path mocks/create-event.json

I’m not getting a code error, though. I get the caught exception from create.js:

{
    "statusCode": 500,
    "body": "{\"error\":\"Requested resource not found\"}"
}

With some console.logs, I’ve confirmed that my create.js file is receiving the create-event.json data correctly. I’ve also double-checked that my “notes” table actually exists, which I saw was an issue for some people. I feel like I might be missing something simple. Any ideas?

Edit: I figured it out. Apparently, you may need to manually set your AWS region, even if you’ve used all default options throughout the tutorial. In my case, I fixed the issue with the following code:

AWS.config.update({ region: "us-east-2" });

According to AWS’s docs, us-east-2 is the default region for accounts made after May 17, 2017.

When I run serverless invoke local --function create --path mocks/create-event.json in my terminal I am not getting back any type of results at all. No errors or anything. My code is matching the code from the tutorial other than my arn is using us-east-2 instead of us-east-1. Has anyone run into this as well? See my code below:

create.js

import * as uuid from "uuid";

import AWS from "aws-sdk";

const dynamoDb = new AWS.DynamoDB.DocumentClient();

export async function main(event, context) {

    // Request body is passed in as a JSON encoded string in 'event.body'

    const data = JSON.parse(event.body);

    const params = {

        TableName: process.env.tableName,

        Item: {

            // The attributes of the item to be created

            userId: "123", // The id of the author

            noteId: uuid.v1(), // A unique uuid

            content: data.content, // Parsed from request body

            attachment: data.attachment, // Parsed from request body

            createdAt: Date.now(), // Current Unix timestamp

        },

    };

    try {

        await dynamoDb.put(params).promise();

        return {

            statusCode: 200,

            body: JSON.stringify(params.Item),

        };

    } catch (e) {

        return {

            statusCode: 500,

            body: JSON.stringify({ error: e.message }),

        };

    }

}

serverles.yml

service: notes-api

# Create an optimized package for our functions

package:

  individually: true

plugins:

  - serverless-bundle # Package our functions with Webpack

  - serverless-offline

  - serverless-dotenv-plugin # Load .env as environment variables

provider:

  name: aws

  runtime: nodejs12.x

  stage: prod

  region: us-east-2

  # These environment variables are made available to our functions

  # under process.env.

  environment:

    tableName: notes

  # 'iamRoleStatements' defines the permission policy for the Lambda function.

  # In this case Lambda functions are granted with permissions to access DynamoDB.

  iamRoleStatements:

    - Effect: Allow

      Action:

        - dynamodb:Scan

        - dynamodb:Query

        - dynamodb:GetItem

        - dynamodb:PutItem

        - dynamodb:UpdateItem

        - dynamodb:DeleteItem

        - dynamodb:DescribeTable

      Resource: "arn:aws:dynamodb:us-east-2:*:*"

functions:

  # Defines an HTTP API endpoint that calls the main function in create.js

  # - path: url path is /notes

  # - method: POST request

  create:

    handler: create.main

    events:

      - http:

          path: notes

          method: post

create-event.json

{

    "body": "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}"

}

Where did you put that line of code into, I’m receiving errors when I try to implement it.

When I run the command below I receive this error

$ serverless invoke local --function create --path mocks/create-event.json
Serverless: Deprecation warning: Detected ".env" files. Note that Framework now supports loading variables from those files when "useDotenv: true" is set (and that will be the default
from next major release)
            More Info: https://www.serverless.com/framework/docs/deprecations/#LOAD_VARIABLES_FROM_ENV_FILES
Serverless: DOTENV: Loading environment variables from .env:
Serverless:      - tableName
Serverless: Deprecation warning: Starting with next major version, API Gateway naming will be changed from "{stage}-{service}" to "{service}-{stage}".
            Set "provider.apiGateway.shouldStartNameWithService" to "true" to adapt to the new behavior now.
            More Info: https://www.serverless.com/framework/docs/deprecations/#AWS_API_GATEWAY_NAME_STARTING_WITH_SERVICE
Serverless: Bundling with Webpack...
{
    "statusCode": 500,
    "body": "{\"error\":\"One or more parameter values were invalid: Missing the key userid in the item\"}"
}

I have checked and as far as I can see everything lines up with my code, my code from the create.js file for the item is as follows

export const main = handler(async (event, context) => {
    const data = JSON.parse(event.body);
    const params = {
        TableName: process.env.tableName,
        Item: {
            // The attributes of the item to be created
            userId: "123", // The id of the author
            noteId: uuid.v1(), // A unique uuid
            content: data.content, // Parsed from request body
            attachment: data.attachment, // Parsed from request body
            createdAt: Date.now(), // Current Unix timestamp
        },
    };

Hi @jayair, I’m following the companion epub guide v5.0.1 and the content of the create.js and create-event.json are different and contain more information? Would you know which one is the most uptodate?

Also I ran the serverless command in the mocks directory by accident and the command exited silently. Would have throught it would’ve complained that it couldn’t find the file denoted by the --path.

Thanks,
Mark.

1 Like

Hi @jayair, sorry now I spoke too soon, the companion updated the version of the create.js later in the chapter!

thanks,
Mark.

1 Like

You’ll need to set this at the top of your Lambda functions. Below the AWS import.

Try running this command instead:

SLS_DEBUG=* serverless invoke local --function create --path mocks/create-event.json

It might be that your tables have userid as the column but your code is using userId. Make sure the case is set correctly.

I tried the command and I get this:

image

I tried adding it to my system environment variables manually since I’m on Windows 10. I also tried running $Env:SLS_DEBUG='true'

Then when I ran serverless invoke local --function create --path mocks/create-event.json I get this:

PS C:\Users\eduardoq\Desktop\Projects\React-Projects\serverles-stack> serverless invoke local --function create --path mocks/create-event.json
Serverless: Load command interactiveCli
Serverless: Load command config
Serverless: Load command config:credentials
Serverless: Load command create
Serverless: Load command install
Serverless: Load command package
Serverless: Load command deploy
Serverless: Load command deploy:function
Serverless: Load command deploy:list
Serverless: Load command deploy:list:functions
Serverless: Load command invoke
Serverless: Load command invoke:local
Serverless: Load command info
Serverless: Load command logs
Serverless: Load command metrics
Serverless: Load command print
Serverless: Load command remove
Serverless: Load command rollback
Serverless: Load command rollback:function
Serverless: Load command slstats
Serverless: Load command plugin
Serverless: Load command plugin
Serverless: Load command plugin:install
Serverless: Load command plugin
Serverless: Load command plugin:uninstall
Serverless: Load command plugin
Serverless: Load command plugin:list
Serverless: Load command plugin
Serverless: Load command plugin:search
Serverless: Load command config
Serverless: Load command config:credentials
Serverless: Load command upgrade
Serverless: Load command uninstall
Serverless: Load command login
Serverless: Load command logout
Serverless: Load command generate-event
Serverless: Load command test
Serverless: Load command dashboard
Serverless: Load command output
Serverless: Load command output:get
Serverless: Load command output:list
Serverless: Load command param
Serverless: Load command param:get
Serverless: Load command param:list
Serverless: Load command studio
Serverless: Invoke invoke:local

Has anyone else ran into the issue I posted back on Jan 5th? I haven’t been able to figure out what’s going on. I tried looking online for other resources but haven’t found much. I have already tried uninstalling and reinstalling the serverless package, as well as downgrading serverless version but neither of them worked. If anyone has ran into this and found a solution, I would greatly appreciate your input.

What’s the actual error you are getting?