Creating Your First Google Cloud Function Part 1
August 05, 2019
I had a use case come up recently that made me think of using Google Cloud Functions, specifically I need to set up a service/end-point to send emails via a contact form on this very personal blog. But before I can do that, I’ll experiment and just set up a simple Google Cloud function that returns “Hello World!“.
In this tutorial, we will:
- Set up a Google Cloud Function in the GCP (Google Cloud Platform) UI Console
- Set up a development environment locally to deploy to that Google Cloud Function, in order to have SCM and a better development experience (it sucks just editing your function on the web console)
We’ll leave the second bullet point to Part 2 of this tutorial.
Setting up GCP Account
1. First, you’ll need to create your GCP account.
Follow this link to sign up with a free trial that gives you $300 worth of credit to use on your GCP account.
2. Create your first project
3. Make sure that billing is enabled.
Instructions can be found here.
4. Enable the Cloud Functions API
Creating Google Cloud Function
1. Go to the GCP Console
2. Navigate to Cloud Functions
You should be able to navigate using the navigation bar on the left side, or searching for “Cloud Functions” in the search bar at the top.
3. Create New Cloud Function
There should be a +
button that is used for creating a new Cloud Function; press that button.
4. Set Up New Cloud Function
You should now be directed to the Create Function
view. Name the function to whatever you want (I’ll call it “function-1”, the default name). Make sure that the trigger type is HTTP
. For the ‘Source Code’ option, select “Inline editor”. and for the ‘Runtime’ option, select “Node.js 8”. In the code editor below the ‘Runtime’ option, there should already be code to return “Hello World!”, like below:
If there isn’t just copy the code below:
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*/
exports.helloWorld = (req, res) => {
let message = req.query.message || req.body.message || 'Hello World!';
res.status(200).send(message);
};
Make sure the ‘Function to execute’ option is set ot “helloWorld”, and hit the ‘Create’ button to create your first Google Cloud Function.
5. Test the Cloud Function
You may have to wait a few minutes to test your new function, but once you see that it’s been deployed, you should be able to select it. Select the function, navigate to the ‘Trigger’ tab and click on the URL shown (in my case, https://us-central1-person-blog-gatsby.cloudfunctions.net/hello-world
). You should see “Hello World!“.