3

I am basically wondering if I can have an https Google Cloud function execute differently based on what I pass to it as a parameter (like any normal function with parameters). Possibly with a simple query inside the URL or any other method that works.

As an example, taking a look at the basic starter function in any tutorial:

exports.helloWorld = functions.https.onRequest((req, res) => {
  res.status(200).send('Hello, World!');
});

I would like to do something like:

exports.helloWorld = functions.https.onRequest((req, res) => {
  let name = req.query;
  res.status(200).send(`Hello, ${name}!`);
});

I hope this makes sense. Any help would be appreciated.

2 Answers 2

6

Indeed it is possible to pass various parameters to your Cloud Function.

Here's a simple example for your reference:

index.js

exports.helloWorld = (req, res) => {
  let name = req.body.name || req.query.name;
  res.status(200).send(`Hello ${name}!`);
};

I can call it via the URL provided for triggering the function, by appending that URL with /?name=<desired-name>:

https://<function-region>-<project-name>.cloudfunctions.net/<function-name>/?name=Christiaan

Alternatively, it can also be called using curl:

curl --data "name=Christiaan" https://<functions-region>-<project-name>.cloudfunctions.net/<function-name>

Output:

Hello Christiaan!
Sign up to request clarification or add additional context in comments.

Comments

0

Hello since HTTPS Cloud Functions are POST requests, you can pass parameters of any kind in the request body.

Example:
Cloud Function:

exports.helloWorld = functions.https.onRequest((req, res) => {
  let name = req.body.name;
  res.status(200).send(`Hello, {name}!`);
});

Client:

fetch('https://firebase.url/helloWorld ', {
    method: 'post',
    body: {name: "Name"},
  }).then(function(response) {
    return response.json();
  }).then(function(data) {
    console.log(data)
  });

You can use any request method here.

Hope this helps.

4 Comments

You would also need to add '$' to interpolate a variable in a JS string: res.status(200).send(`Hello, ${name}!`);
I tried doing this using Cloud Scheduler, by inserting {name: "Name"} into the body of a job there. But this returns undefined then. Any advice on that?
Eventually you need to add it like that: {"name": "Name"}
Thanks. Got it now. I also have to parse it to JSON in my code, as it just returns a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.