Cloud function to test HTTP POST request with JSON document

Postman Screenshot

I had to write a cloud function to send some JSON data (nested arrays) to a Google Cloud Platform HTTP endpoint and record the response. I am not a web/software developer so had to do quite some work to get this Google Cloud Function running.

I used POSTMAN to send the request although I will be using ESP32 to do it later on.

I won’t discuss how to set up a GCP etc. here. But you can get enough info from the official GCP quickstart guide.

  • Create these two files on your desired directory.
    • package.json
    • index.js  <—- this is where the code is placed.

package.js

{
    "name": "sample-http",
    "version": "0.0.1"
  }
  

index.js

 exports.readBody = (req, res) => {
     // Construct message
     let message = constructMessage(req);
     res.status(200).send(message);
 };

 constructMessage = (req) => {
     // Read request
     let eventIDs = req.body.eventIDs;
     let imageNames = req.body.imageNames;
     let fileSizes = req.body.fileSizes;

     // Create response
     var obj = new Object();
     obj.eventID = eventIDs;
     obj.imageName = imageNames;
     obj.fileSize = fileSizes;

     var jsonString = JSON.stringify(obj);
     return JSON.parse(jsonString);
 };

Once you are done, deploy the cloud function.

$ gcloud functions deploy readBody --runtime nodejs14 --trigger-http --allow-unauthenticated

I know there are a few steps missing. But I wanted to present the code for the cloud function here for a noob like me to find when required.

Put a comment below if you need further details.

Related posts

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.