Call the Create API

Thanks for these tutorials, I had been trying to teach myself and was getting there but this is much faster!

I’m getting an alert when I submit the create button. “Error: Request failed with status code 404”. I searched the comments and found Kissa’s 404 error but she said in another discussion that it was due to her region and url being swapped in her config file. I have double checked all the info in the config file matches what is in AWS, is in the right fields and even looks the same as the examples you provided in each of those sections. Went back to the last point it was working and redid the steps up to this one and it still is giving me a 404 error.

Not sure if this helps but 2 things that went wrong up to this point. I initially was in the ‘us-east-2’ region before I realized how often you need regions or that regions could even be different in different services and to maintain my sanity I went back and deleted the first S3 bucket that I had made in that region and moved it to ‘us-east-1’ (I have verified that is where mine is.) But I had restarted from scratch and redid all the steps through that point so I don’t know if somehow that old bucket has thrown a monkey wrench in the works. Another kerfuffle I ran into was with the formatting of the Windows command line in the “Test the API’s” chapter. I didn’t read past the mac code to see that you provided the windows code after it and ended up following a bunch of the suggestions like rolling back my serverless framework version and redeploying it a couple of times before I realized that wasn’t the issue and went back to the current version. Other than that, everything has looked identical to what you show as the expected result. Sorry for the long-winded post, just want to make sure I’m giving you any pertinent information. Here’s my git repos:


https://github.com/Meaix88/serverless-stack-client.git

Help me Obi-wan Kenobi! You’re my only help!

I’m not totally sure whats going on but any idea why the https:// is missing here?

That was it, thanks! Can’t believe I missed that, especially since Kissa’s 404 had to do with her config file as well. ah well…tired eyes are the devil in coding.

1 Like

Hi, I’ve completed the tutorial and am now trying to customize for my own app. I’m trying to get modify the createNote API so that I can add an array to DynamoDB (ideally a mix of strings and numbers with labels, but will settle for just an array of strings). Can you let me know what the purpose is of this function:

function createNote(note) {
  return API.post("notes", "/notes", {
    body: note
  });

Here’s my attempt but I can’t get it to add anything besides the text of the “note box” to Dynamo.

import React, { useState } from "react";
import { FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import LoaderButton from "../components/LoaderButton";
import config from "../config";
import "./NewAdu.css";
import { API } from "aws-amplify";
import { s3Upload } from "../libs/awsLib";

export default function NewAdu(props) {
  const [content, setContent] = useState("");
  const [purchprice, setPurchprice] = useState("");
  const [purchdate, setPurchdate] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  function validateForm() {
    return content.length > 0 && purchprice.length > 0 && purchdate.length > 0;
  }

  async function handleSubmit(event) {
    event.preventDefault();

    setIsLoading(true);

    try {
      await createAdu({ content, purchprice, purchdate });
      props.history.push("/");
    } catch (e) {
      alert(e);
      setIsLoading(false);
    }
  }

  function createAdu(note) {
    return API.post("notes", "/notes", {
      body: note
    });
  }

  return (
    <div className="NewAdu">
      <form onSubmit={handleSubmit}>
        <FormGroup controlId="content">
          <FormControl
            autoFocus
            value={content}
            componentClass="textarea"
            onChange={e => setContent(e.target.value)}
          />
        </FormGroup>
        <FormGroup controlId="purchprice" bsSize="large">
          <ControlLabel>Purchase Price</ControlLabel>
          <FormControl
            type="number"
            value={purchprice}
            onChange={e => setPurchprice(e.target.value)}
          />
        </FormGroup>
        <FormGroup controlId="purchdate" bsSize="large">
          <ControlLabel>Purchase Date</ControlLabel>
          <FormControl
            type="date"
            value={purchdate}
            onChange={e => setPurchdate(e.target.value)}
          />
        </FormGroup>
        <LoaderButton
          block
          type="submit"
          bsSize="large"
          bsStyle="primary"
          isLoading={isLoading}
          disabled={!validateForm()}
        >
          Create
        </LoaderButton>
      </form>
    </div>
  );
}

In case anyone else is a beginner and looking to do the same, you need to do the above and then also modify create.js to actually put these items to dynamo.

1 Like

Ah I see. Thanks for sharing!

I am calling the create API and have hardcoded the string to test out my API right now:

async function createProfile(param) {
    //apiName first param coming from index.js
    //path second param coming from endpoint path
    const jsonData = "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}";
    return API.post('notes', '/notes', {
        body: jsonData
    });
}

But when I check dynamoDB, all I see is an entry created with just the userId and createdDate. There’s no content or attachment values populated from the above jsonData.
I can see this in the cloud watch logs which means the request is making through. But again no data in dynamoDB:

(4ce87038-204b-4d46-982b-15add74b9e5a) Method request body before transformations: "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}"

Any idea where I might be wrong and is there any way to debug the serverless create endpoint by stepping through it in some IDE?

Hmm any idea why the jsonData is encoded as a string?

You can compare it to what we are doing:

I am keeping it in the same format as this example: Can’t I keep it as a string for testing?

{
  "body": "{\"content\":\"hello world\",\"attachment\":\"hello.jpg\"}",
  "requestContext": {
   "identity": {
     "cognitoIdentityId": "USER-SUB-1234"
    }
   }
 }

Well on the frontend we are using the Amplify AWS library. It’ll convert it to a string. That example is from when we were testing the Lambda function directly.

Its resolved now! As you mentioned, I was stringify-ing the data in the UI. Thanks a lot :slight_smile:

1 Like

All of the notes section have an error related to a double / call to API. I replaced this

function createNote(note) { return API.post("notes", "/notes", { body: note, }); }

with this

function createNote(note) { return API.post("notes", "notes", { body: note, }); }

for everywhere there was a ‘/notes’ which wasn’t in the Routes.js

I honestly don’t know if this was the correct approach but it worked and fixed all of my headaches.

I think you might have set something else wrong along the way. Compare it to the GitHub sample repo:

I checked and all the config is exactly the same as in the example code, but this line 51 as you pasted it

return API.post(“notes”, “/notes”, {

was giving me an error, so I removed the slash and the error was gone

Weird. What about this line in your config. Make sure it doesn’t have a trailing slash.

If you are having problems with the page redirecting and you’re using Firefox Quantum, use Chrome or any Chromium-based browser. Firefox have this thing where it doesn’t allow CORS to run locally because it’s on HTTP instead of HTTPS

It’s like a safety thingy

Oh that’s interesting. Thanks for reporting!

Hello Team , First of all Thank you so much for creating and maintaining this project.
This is an amazing work !

I have been working on adding more features to the that implementation and have a question about amplify Storage data upload.

I noticed that you guys use 5MBs of max file size and understand its probably more or less related to S3 max chunk size upload which is also 5MB.

However if you needed to upload files that are larger that 5MBs how would you go about this. Because after removing the limitation in React i still get an error from amazon :

[50:08.104 AWSS3Provider ManagedUpload - error happened while finishing the upload. Cancelling the multipart upload Error: Request failed with status code 400]

it would be great if someone has worked on this and can help… anyway i have a meeting with amazon support this week and will post here any updates later on.

1 Like

Hmmm that’s odd because the 5MB limit is very arbitrary. It should word for larger files as well. Did you figure out whats going on?

hey Jay, yes. I ended up talking to aws support. Amplify does not support file upload larger than 5gb(this is called multipart upload). I had to use lambda. This is a really bad limitation of amplify.

i apologize for the type . its 5GB not 5MB :frowning: