Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass body data with an Amplify REST request?

I'm using the AWS amplify REST API to make a get request to my lambda function in React Native. The API/Lambda function was generated by the Amplify CLI.

  const getData = async (loca) => {
    const apiName = "api1232231321";
    const path = "/mendpoint";
    const myInit = {
      body: {
        name: "bob",
      },
      queryStringParameters: {
        location: JSON.stringify(loca),
      },
    };

    return API.get(apiName, path, myInit);
  };

Unless I remove the body from this request, it just returns Error: Network Error with no other details. I seem to be able to get the queryStringParameters just fine though if I remove the body object.

If I do this, the request goes through fine without errors

const myInit = JSON.stringify({
  body: {
    name: "bob",
  },
});

But the body in the event (event.body) in lambda is always null. Same result if change body to data as well. My second thought was that perhaps I can only pass body data with a POST request however the docs seem to show that you can use a GET request since it documents how to access said body data...

Lambda function

exports.handler = async(event) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify(event),
  };
  return response;
};

How do I correctly pass body data?

like image 282
ProEvilz Avatar asked Nov 07 '22 06:11

ProEvilz


1 Answers

The Amplify SDK won't send a body on a API.get() call. You're first example looks fine but you'll need to use API.post() (or put) instead.

  const getData = async (loca) => {
    const apiName = "api1232231321";
    const path = "/mendpoint";
    const myInit = {
      body: {
        name: "bob",
      },
      queryStringParameters: {
        location: JSON.stringify(loca),
      },
    };

    return API.post(apiName, path, myInit);
  };
like image 179
kjones Avatar answered Nov 12 '22 12:11

kjones