How to do a Restful POST using Netlify Functions?

Hi. I’m trying to do a POST in my function. How would I go about writing one where I’d need to call an external API and pass some data?

I’ve got a test API running (api/test) and want to pass a json for testing:

{"a": "1", "b": "Textual content"}

For starters I want to just verify I can pass the data to the API. How would I write this?

Edit:
I’ve tried few examples and dumbed them down and seem to keep getting errors that I can’t understand. For example, I’m getting circular structure error (TypeError: Converting circular structure to JSON) with the code below and I don’t see where is where I’ve used circular structure. :man_shrugging:

const https = require('https');

exports.handler = (event, context, callback) => {
  const payload = JSON.stringify({"a": "1", "b": "Textual content"});
  
  const options = {
    hostname: "https://app.herokuapp.com",
    method: "POST",
    path: "/api/test",
  };
  
  const req = https.request(options,
      (res) => res.on("data", () => callback(null, "OK")))
  req.on("error", (error) => callback(JSON.stringify(error)));
  req.write(payload);
  req.end();
}

Hi,

In general it’s a better experience for you to use an http client library like node-fetch or axios. I personally prefer axios. You can then do the requests the same way you would on the web (fetch) or axios examples via their docs (https://github.com/axios/axios).

1 Like