arrow_back

App Dev - Deploying an API for the Quiz Application: Node.js

Sign in Join
Get access to 700+ labs and courses

App Dev - Deploying an API for the Quiz Application: Node.js

Lab 2 hours universal_currency_alt 5 Credits show_chart Introductory
info This lab may incorporate AI tools to support your learning.
Get access to 700+ labs and courses

Overview

In this lab, you deploy the Quiz application API into Google Compute Engine and leverage Cloud Endpoints to provide monitoring functionality.

Objectives

In this lab, you learn how to perform the following tasks:

  • Create an Open API specification from the existing Quiz application REST API.
  • Deploy the specification as a Cloud Endpoint.
  • Provision a Compute Engine instance with the Extensible Service Proxy to host the Cloud Endpoints API.

Setup and requirements

For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.

  1. Sign in to Qwiklabs using an incognito window.

  2. Note the lab's access time (for example, 1:15:00), and make sure you can finish within that time.
    There is no pause feature. You can restart if needed, but you have to start at the beginning.

  3. When ready, click Start lab.

  4. Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.

  5. Click Open Google Console.

  6. Click Use another account and copy/paste credentials for this lab into the prompts.
    If you use other credentials, you'll receive errors or incur charges.

  7. Accept the terms and skip the recovery resource page.

Activate Google Cloud Shell

Google Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud.

Google Cloud Shell provides command-line access to your Google Cloud resources.

  1. In Cloud console, on the top right toolbar, click the Open Cloud Shell button.

    Highlighted Cloud Shell icon

  2. Click Continue.

It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:

Project ID highlighted in the Cloud Shell Terminal

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  • You can list the active account name with this command:
gcloud auth list

Output:

Credentialed accounts: - @.com (active)

Example output:

Credentialed accounts: - google1623327_student@qwiklabs.net
  • You can list the project ID with this command:
gcloud config list project

Output:

[core] project =

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: Full documentation of gcloud is available in the gcloud CLI overview guide .

Task 1. Preparing the case study application

In this section, you access Cloud Shell, clone the git repository containing the Quiz application, configure environment variables, and run the application.

Clone source code in Cloud Shell

  1. To clone the repository for the class, execute the following command:
git clone --depth=1 https://github.com/GoogleCloudPlatform/training-data-analyst
  1. Create a soft link as a shortcut to the working directory:
ln -s ~/training-data-analyst/courses/developingapps/v1.3/nodejs/cloudendpoints ~/cloudendpoints

Configure and run the case study application

  1. Change to the directory that contains the sample files for this lab:
cd ~/cloudendpoints/start
  1. To replace the default region in a file with the lab-assigned region, run the following commands:
export APP_REGION={{{project_0.startup_script.app_gcp_region | APP_REGION}}} export REGION={{{project_0.default_region | REGION}}} sed -i 's/us-central1/'"$REGION"'/g' prepare_environment.sh sed -i 's/us-central/'"$APP_REGION"'/g' prepare_environment.sh
  1. To configure the Quiz application, execute the following command:
. prepare_environment.sh

If prompted, Bind the role to service account? (Y/n)?, enter n.

Note: This script file:
  • Creates an App Engine application.
  • Creates the Datastore database.
  • Exports environment variables GCLOUD_PROJECT and GCLOUD_BUCKET.
  • Runs npm install.
  • Creates entities in Cloud Datastore.
  • Installs an Open API generator tool, api2swagger.
  • Prints out the Google Cloud Platform Project ID.

If you see ERROR: (gcloud.functions.deploy), retry the full gcloud functions deploy command you see after running cat ./prepare_environment.sh.

You can run gcloud functions list to verify the function is created and available.

Note: Warnings generated by the installation of the Open API generator can be safely ignored in this lab.
  1. To run the web application, execute the following command:
npm start

The application is now running from Cloud Shell.

  1. In Cloud Shell, click Web preview > Preview on port 8080 to preview the quiz application.
  2. Modify the URL by adding /api/quizzes/places to the end of the hostname. Replace /?authuser=0 with /api/quizzes/places.
Note: You should see JSON data returned from the quiz application API corresponding to the questions in the places quiz.
  1. Make a note of the complete API URL to use later in this lab and save the url so you can paste it in a command in the next section.
Note: The URL will look similar to: https://8080-cs-***.cloudshell.dev/api/quizzes/places

Click Check my progress to verify the objective.

Configure and run the case study application

Task 2. Generating an Open API specification

In this section, you will generate an Open API specification that will form the basis for deploying your Cloud Endpoint.

Create an Open API specification

  1. Open a second Cloud Shell window.

  2. Open a new tab by clicking the plus sign add iconin the terminal.

  3. To change the directory to the Cloud Endpoints working folder, execute the following command:

cd ~/cloudendpoints/start/endpoint
  1. Update the PATH environment variable to set the path for the api2swagger command:
export PATH=$PATH:`npm root -g`/api2swagger/bin
  1. To Install api2swagger python package:
npm install -g api2swagger
  1. To generate the Open API specification, execute the following command, replacing [API_URL_FROM_CLIPBOARD] with the API URL saved in the previous step of form https://8080-cs-.../api/quizzes/places:
api2swagger -e [API_URL_FROM_CLIPBOARD] -o ./quiz-api.json Note: The api2swagger tool will make the request against the API and display a series of prompts. If you don't complete the proper replacement, you'll see an Invalid hostname error.
  1. Enter responses to the api2swagger prompts using the following table:

Prompt

Response

Title of Swagger Spec ?

Quite Interesting Quiz API

Description of Swagger Spec ?

An API for the Quite Interesting Quiz

Terms of Service URL

(Press enter key)

Version of your API Program ?

(Press enter key)

Contact Name?

(Press enter key)

Contact URL ?

(Press enter key)

Contact Email ?

(Press enter key)

License Name ?

(Press enter key)

License URL ?

(Press enter key)

Does your API support http ?

Y

Pick Base Path from your API ?

Use the up and down arrows to select:

❯ /api/quizzes

(Press enter key)

A verbose explanation of the operation behavior ?

Gets questions for a quiz

A short summary of what the operation does ?

Get quiz questions

Additional external documentation for this operation ?

(Press enter key)

Unique string used to identify the operation ?

getQuizQuestions

A list of tags for API documentation control ?

(Press enter key)

API Path has any dynamic parameters ?

Y (Press enter key)

Choose Dynamic Params in URL ?

Use the up and down arrows to move to:
❯◉ places


Then press the space bar to select places, then press enter

Name of URL Param ?

quizName

Description of URL Param ?

The name of the quiz

Type of query param ?

Use the up and down arrows to select:
❯ string

(Press enter key)

Note: The api2swagger tool will display the output for the Open API specification.

Edit the Open API specification

  1. In Cloud Shell, click Open Editor.

You may need to click Open in New Window if third-party cookie blocking is enabled.

  1. Navigate to cloudendpoints/start/endpoint.
  2. In the Cloud Shell Code Editor, open quiz-api.json.
  3. Replace the value for the "host" key with a hostname using a string in the form quiz-api.endpoints.[Project-ID].cloud.goog.
Note: The following sample shows the modification in the host line.

Be sure you replace [GCP-Project-ID] with your GCP Project ID.

You can find the GCP Project ID in the left panel of the lab instructions under your credentials.

endpoint/quiz-api.json

{ "swagger": "2.0", "host": "quiz-api.endpoints.qwiklabs-gcp-XX-XXXX.cloud.goog", "schemes": [ "https", "http" ], Note: When you deploy your Open API specification in the next section, the Service Management API will use the host value in your deployment configuration file to create a new Cloud Endpoints service with the name quiz-api.endpoints.[PROJECT-ID].cloud.goog (if it does not exist), and then configure the service according to your OpenAPI configuration file.

Cloud Endpoints uses DNS-compatible names to uniquely identify services. Because projects in Google Cloud Platform are guaranteed to have a globally unique name, you can use your project name to create a unique API service name. You can also map your own DNS name to your API.
  1. Save the file.

Deploy the API Specification to Cloud Endpoints

  1. Click Open Terminal to return to Cloud Shell.

  2. To deploy the Open API specification as a Cloud Endpoint, execute the following command in the Cloud Shell window:

gcloud endpoints services deploy quiz-api.json

If you see an error like PERMISSION_DENIED: Ownership for domain name, make sure your host in the quiz-api.json file matches the suggested format including the correct your project-id.

Note: The service definition takes a few minutes to deploy. You will see a warning related to the API being available to all clients without supplying a key.
  1. To view the Open API configuration name, execute the following command:
gcloud endpoints configs list --service="quiz-api.endpoints.$GOOGLE_CLOUD_PROJECT.cloud.goog"

Notice the project-id has been inserted. You can copy the service from the output of your deploy command.

Note: The service configuration will be returned, including the CONFIG_ID and SERVICE_NAME. You will need the both values in the next section.

Task 3. Deploying the API backend

In this section, you will provision a Compute Engine instance to run the API implementation and the Cloud Endpoints Extensible Service Proxy.

Create a Compute Engine instance

  1. In the Cloud console, on the Navigation menu (☰), click Compute Engine > VM Instances.
  2. To create a new instance, click Create Instance.
  3. On the Machine configuration page, enter the values for the following fields:

Field

Value

Name

endpoint-host

Region

Zone

Series

E2

Machine type > Shared-core

e2-small

  1. Click OS and storage.

    Click Change to begin configuring your boot disk and select the following values:

    • Operating system: Debian
    • Version: Debian GNU/Linux 11 (bullseye)
  2. Click Networking.

  3. For Firewall, click Allow HTTP traffic.

  4. Click Security.

  5. For Access scopes, click Allow full access to all Cloud APIs.

  6. Click Advanced.

  7. For Metadata, click + Add Item twice.

  8. Enter the following metadata values:

endpoints-service-config-id

The CONFIG_ID for the endpoint in the form:
yyyy-mm-ddr0

endpoints-service-name

The SERVICE_NAME for the endpoint in the form:

quiz-api.endpoints.<Project-ID>.cloud.goog

  1. Click Create.

Wait for the provisioning of the VM to complete.

Note: The Compute Engine instance will take around 20 seconds to provision with Debian.

Install and run the API backend

  1. Return to the Cloud Shell window.
  2. To ensure that the working directory is set to the endpoint folder, execute the following command:
cd ~/cloudendpoints/start/endpoint/
  1. To copy the application source files from Cloud Shell to endpoint-host, execute the following command:
gcloud compute scp ./quiz-api endpoint-host:~/ --recurse --zone={{{project_0.default_zone | ZONE}}} Note: You may be prompted to create an SSH key. You can press the ENTER key for each prompt including the Y to create the .ssh directory.

It may take a few seconds to copy the files.
  1. Return to the Cloud Platform Console.
  2. On the Compute Engine page, to connect to the endpoint-host virtual machine, click SSH.
Note: You may need to click twice if you have a popup blocker. It will take a few seconds to establish the SSH connection.
  1. In the endpoint-host SSH window, install the software prerequisites:
sudo apt-get install ca-certificates curl gnupg -y sudo mkdir -p /etc/apt/keyrings curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg NODE_MAJOR=20 echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list sudo apt-get update sudo apt-get install nodejs -y

Click Check my progress to verify the objective.

Create a Compute Engine Instance and install the software prerequisites
  1. To run the quiz API application, execute the following commands within the SSH session:
export GCLOUD_PROJECT="$(curl -H Metadata-Flavor:Google http://metadata/computeMetadata/v1/project/project-id)" export GCLOUD_BUCKET=$GCLOUD_PROJECT-media export PORT=8081 cd ~/quiz-api npm install npm start
  1. Return to the Cloud Platform Console, which should still display the Compute Engine VM instance list.
  2. Establish a second SSH connection to endpoint-host.
  3. In the second endpoint-host SSH window, to install the Cloud Endpoints Extensible Service Proxy by executing the following commands:
export CLOUD_ENDPOINTS_REPO="google-cloud-endpoints-jessie" echo "deb http://packages.cloud.google.com/apt $CLOUD_ENDPOINTS_REPO main" | sudo tee /etc/apt/sources.list.d/google-cloud-endpoints.list curl --silent https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - sudo apt-get update && sudo apt-get install endpoints-runtime
  1. Still in the second endpoint-host SSH window, execute the following command to edit the nginx configuration file:
sudo nano /etc/default/nginx
  1. To modify the file, add the following declaration after the existing configuration:
PORT=80
  1. Save the file (press Ctrl+O then Enter).
  2. Exit nano (press Ctrl+X).
  3. To restart nginx, execute the following command:
sudo service nginx restart

Task 4. Testing and modifying Cloud Endpoint

In this section, you will verify the deployment of the endpoint and modify the configuration to allow serving via a hostname instead of an IP address.

Invoke the Cloud Endpoint via the IP address

  1. Return to the Cloud Platform Console > Compute Engine.
  2. To launch a browser window, click on the endpoint-host virtual machine's External IP address.
Note: A JSON message reporting Method does not exist will be displayed in the new browser window. This is expected behavior, because you have not associated a method with "/". You do not need to take corrective action.
  1. Add /api/quizzes/places to the end of the URL.
Note: You should see JSON data returned from the quiz API.
  1. In the Cloud Platform Console, on the Navigation menu, click Endpoints, and then click on your deployed endpoint.
Note: You should see a monitoring page for the quiz-api endpoint. After a few minutes, you should see the request that you made against the endpoint.

Modify and redeploy the Cloud Endpoint configuration

  1. Return to the Cloud Shell code editor, and select the quiz-api.json file.
  2. To allow the API to be accessed via the Cloud Endpoint hostname instead of the IP address, add the "x-google-endpoints" key and value shown in the following file fragment:

endpoint/quiz-api.json

{ "swagger": "2.0", "host": "quiz-api.endpoints.<Project-ID>.cloud.goog", "x-google-endpoints": [ { "name": "quiz-api.endpoints.<Project-ID>.cloud.goog", "target": "<endpoint-host-EXTERNAL-IP-ADDRESS>" } ], "schemes": [ "https", "http" ],
  1. Change the values of <Project-ID>, and <endpoint-host-EXTERNAL-IP-ADDRESS> then save the file.

The updated configuration should look similar to this:

{ "swagger": "2.0", "host": "quiz-api.endpoints.qwiklabs-gcp-04-a7b3469e256f.cloud.goog", "x-google-endpoints": [ { "name": "quiz-api.endpoints.qwiklabs-gcp-04-a7b3469e256f.cloud.goog", "target": "34.172.61.246" } ], "schemes": [ "https", "http" ],
  1. To redeploy the API, return to the Cloud Shell window, and execute the following command:
gcloud endpoints services deploy quiz-api.json
  1. Open a new browser tab, and navigate to: http://quiz-api.endpoints.<Project-ID>.cloud.goog/api/quizzes/gcp.
Note: You should see JSON data from the GCP quiz.

Task 5. Monitoring the API

In this section you will review the monitoring output from your API.

Inspect the API in the console

  1. Return to the Cloud Platform Console, and on the Navigation menu, click Endpoints, and then click on your deployed endpoint.
Note: You should see an overview page for the Quiz API.
  1. Take a few minutes to review the Requests, Latency, and Error graphs.
Note: You should see that the monitoring graphs allow you to observe the performance of your API as it executes requests from clients.

End your lab

When you have completed your lab, click End Lab. Google Cloud Skills Boost removes the resources you’ve used and cleans the account for you.

You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.

The number of stars indicates the following:

  • 1 star = Very dissatisfied
  • 2 stars = Dissatisfied
  • 3 stars = Neutral
  • 4 stars = Satisfied
  • 5 stars = Very satisfied

You can close the dialog box if you don't want to provide feedback.

For feedback, suggestions, or corrections, please use the Support tab.

Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

Before you begin

  1. Labs create a Google Cloud project and resources for a fixed time
  2. Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
  3. On the top left of your screen, click Start lab to begin

Use private browsing

  1. Copy the provided Username and Password for the lab
  2. Click Open console in private mode

Sign in to the Console

  1. Sign in using your lab credentials. Using other credentials might cause errors or incur charges.
  2. Accept the terms, and skip the recovery resource page
  3. Don't click End lab unless you've finished the lab or want to restart it, as it will clear your work and remove the project

This content is not currently available

We will notify you via email when it becomes available

Great!

We will contact you via email if it becomes available

One lab at a time

Confirm to end all existing labs and start this one

Use private browsing to run the lab

Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.