In this lab, you learn how to perform the following tasks:
Call APIs from JavaScript.
Separate requests from responses in order to call APIs in parallel.
Setup and requirements
For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.
Sign in to Qwiklabs using an incognito window.
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.
When ready, click Start lab.
Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.
Click Open Google Console.
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.
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.
In Cloud console, on the top right toolbar, click the Open Cloud Shell button.
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:
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:
A second JavaScript policy will accept the responses and combine the results.
In the Navigator pane, click Proxy endpoints > default > PreFlow.
On the Request PreFlow flow, click Add Policy Step (+).
In the Add policy step pane, select Create new policy, and then select Extension > Javascript.
Specify the following values:
Property
Value
Name
JS-SendRequests
Display name
JS-SendRequests
For Javascript file, select Create New Resource.
For Resource name, specify sendRequests.js.
Click Add.
For Javascript file, select sendRequests.js.
Click Add.
Click Resources > jsc > sendRequests.js.
Paste the following code into the .js file:
// search is a query parameter with a comma-separated list of topics to be searched
var searchParam = context.getVariable("request.queryparam.search");
if (searchParam === null || searchParam.length === 0) {
throw("search query parameter not found");
}
var search = searchParam.split(",");
print("search=" + search);
// call max 5 in parallel
var maxCalls = search.length;
if (maxCalls > 5) {
maxCalls = 5;
}
print("maxCalls=" + maxCalls);
// URL to the Google Books API
var url="https://www.googleapis.com/books/v1/volumes?country=US&q=subject:";
var searchTerms = [];
// for each search term, call the Google API
for (var i=0; i < maxCalls; i++) {
var searchTerm = search[i];
print("" + i + ": " + searchTerm);
print("GET " + url + ""+searchTerm);
var req = httpClient.get(url+searchTerm);
// store the request in a session for later retrieval
searchTerms.push(searchTerm);
context.session["searchTerm:" + searchTerm] = req;
}
context.session["searchTerms"] = searchTerms;
print("done sending the requests");
This code makes a separate request for each search term passed in, up to a maximum of 5. The request is made without waiting for the response, which causes the requests to be executed in parallel.
Note: If you build a proxy like this for production use, validate the search query parameter and return an error before calling the services.
The request objects are stored in the context.session object. Other JavaScript policies can retrieve entities stored in context.session.
Task 3. Add a JavaScript policy to process the responses
In this task, you create a JavaScript policy to retrieve the responses and combine them into a single response.
In the Navigator pane, click Proxy endpoints > default > PreFlow.
Note: You could put the JS-ProcessResponses policy in the response flow if your proxy is also going to call a backend service.
On the Request PreFlow flow, click Add Policy Step (+).
In the Add policy step pane, select Create new policy, and then select Extension > Javascript.
Specify the following values:
Property
Value
Name
JS-ProcessResponses
Display name
JS-ProcessResponses
For Javascript file, select Create New Resource.
For Resource name, specify processResponses.js.
Click Add.
For Javascript file, select processResponses.js.
Click Add.
Click Policies > JS-ProcessResponses.
Change the configuration for the JS-ProcessResponses policy:
The maximum time limit for the JavaScript policy is changed from 200 milliseconds to 5 seconds.
continueOnError is set to true, so that the call will return whatever has been successfully retrieved if the policy times out.
Note: Evaluation orgs have a documented time limit of 200 milliseconds, so the 5-second limit might not be applied. In a paid org, the timeLimit attribute should be in effect.
Click Resources > jsc > processResponses.js.
Paste the following code into the .js file:
var searchTerms = context.session["searchTerms"];
var resp = [];
// Iterate for each search term
for (var i=0; i < searchTerms.length; i++) {
// retrieve request object from session
var searchTerm = searchTerms[i];
req = context.session["searchTerm:" + searchTerm];
req.waitForComplete();
print("Got response for " + searchTerm);
if (req.isSuccess()) {
print("Success!");
item = {
query : searchTerm,
result : JSON.parse(req.getResponse().content)
};
}
else {
print("Error: " + JSON.stringify(req.getError()));
item = {
query : searchTerm,
result : null
}
}
resp.push(item);
print(item);
// store JSONresponse in a temporary flow variable
context.setVariable("bookResponses", JSON.stringify(resp));
}
print("done processing responses");
This code retrieves all of the requests previously stored in the session and waits for each to complete. All responses are combined into a single object.
Task 4. Add an AssignMessage policy to build the response
To specify that you want the new revision deployed to the eval environment, select eval as the Environment, and then click Deploy.
Click Confirm.
Check deployment status
A proxy that is deployed and ready to take traffic will show a green status on the Overview tab.
When a proxy is marked as deployed but the runtime is not yet available and the environment is not yet attached, you may see a red warning sign. Hold the pointer over the Status icon to see the current status.
If the proxy is deployed and shows as green, your proxy is ready for API traffic. If your proxy is not deployed because there are no runtime pods, you can check the provisioning status.
Check provisioning status
In Cloud Shell, to confirm that the runtime instance has been installed and the eval environment has been attached, run the following commands:
export PROJECT_ID=$(gcloud config list --format 'value(core.project)'); echo "PROJECT_ID=${PROJECT_ID}"; export INSTANCE_NAME=eval-instance; export ENV_NAME=eval; export PREV_INSTANCE_STATE=; echo "waiting for runtime instance ${INSTANCE_NAME} to be active"; while : ; do export INSTANCE_STATE=$(curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" -X GET "https://apigee.googleapis.com/v1/organizations/${PROJECT_ID}/instances/${INSTANCE_NAME}" | jq "select(.state != null) | .state" --raw-output); [[ "${INSTANCE_STATE}" == "${PREV_INSTANCE_STATE}" ]] || (echo; echo "INSTANCE_STATE=${INSTANCE_STATE}"); export PREV_INSTANCE_STATE=${INSTANCE_STATE}; [[ "${INSTANCE_STATE}" != "ACTIVE" ]] || break; echo -n "."; sleep 5; done; echo; echo "instance created, waiting for environment ${ENV_NAME} to be attached to instance"; while : ; do export ATTACHMENT_DONE=$(curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" -X GET "https://apigee.googleapis.com/v1/organizations/${PROJECT_ID}/instances/${INSTANCE_NAME}/attachments" | jq "select(.attachments != null) | .attachments[] | select(.environment == \"${ENV_NAME}\") | .environment" --join-output); [[ "${ATTACHMENT_DONE}" != "${ENV_NAME}" ]] || break; echo -n "."; sleep 5; done; echo "***ORG IS READY TO USE***";
When the script returns ORG IS READY TO USE, you can proceed to the next steps.
While you are waiting
Learn more while you wait for the deployment to complete:
In this task, you use the debug tool to test and examine the proxy.
Start a debug session
Click the Debug tab, and then click Start Debug Session.
In the Start debug session pane, on the Environment dropdown, select eval.
Click Start.
Test the API proxy using private DNS
The eval environment in the Apigee organization can be called using the hostname eval.example.com. The DNS entry for this hostname has been created within your project, and it resolves to the IP address of the Apigee runtime instance. This DNS entry has been created in a private zone, which means it is only visible on the internal network.
Cloud Shell does not reside on the internal network, so Cloud Shell commands cannot resolve this DNS entry. A virtual machine (VM) within your project can access the private zone DNS. A virtual machine named apigeex-test-vm was automatically created for this purpose. You can make API proxy calls from this machine.
The curl command will be used to send API requests to an API proxy. The -k option for curl tells it to skip verification of the TLS certificate. For this lab, the Apigee runtime uses a self-signed certificate. For a production environment, you should use certificates that have been created by a trusted certificate authority (CA).
In Cloud Shell, open a new tab, and then open an SSH connection to your test VM:
The first gcloud command retrieves the zone of the test VM, and the second opens the SSH connection to the VM.
If asked to authorize, click Authorize.
For each question asked in the Cloud Shell, click Enter or Return to specify the default input.
Your logged in identity is the owner of the project, so SSH to this machine is allowed.
Your Cloud Shell session is now running inside the VM.
Call the proxy
In the Cloud Shell SSH session, send the following curl command:
curl -k -X GET "https://eval.example.com/lab8a/v1?search=java,sql,python" | jq
Your response should be an array of 3 query objects, each with the search term and a result object containing the response payload. The beginning of your response should look something like this:
[
{
"query" : "java",
"result" : {
"items" : [
{
"accessInfo" : {
"accessViewStatus" : "SAMPLE",
"country" : "US",
"embeddable" : true,
"epub" : {
"isAvailable" : false
},
"pdf" : {
"isAvailable" : true
},
"publicDomain" : false,
"quoteSharingAllowed" : false,
"textToSpeechPermission" : "ALLOWED",
"viewability" : "PARTIAL",
"webReaderLink" : "http://play.google.com/books/reader?id=nzhxR1spWEYC&hl=&source=gbs_api"
},
"etag" : "I/aKsW0+3W4",
"id" : "nzhxR1spWEYC",
"kind" : "books#volume",
"saleInfo" : {
"country" : "US",
"isEbook" : false,
"saleability" : "NOT_FOR_SALE"
},
"selfLink" : "https://www.googleapis.com/books/v1/volumes/nzhxR1spWEYC",
Note: The ordering of the queries in the response may be unpredictable because the subjects were searched in parallel.
Congratulations!
In this lab, you used JavaScript policies to call services in parallel and combine the responses into a single response.
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 2022 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.
Labs erstellen ein Google Cloud-Projekt und Ressourcen für einen bestimmten Zeitraum
Labs haben ein Zeitlimit und keine Pausenfunktion. Wenn Sie das Lab beenden, müssen Sie von vorne beginnen.
Klicken Sie links oben auf dem Bildschirm auf Lab starten, um zu beginnen
Privates Surfen verwenden
Kopieren Sie den bereitgestellten Nutzernamen und das Passwort für das Lab
Klicken Sie im privaten Modus auf Konsole öffnen
In der Konsole anmelden
Melden Sie sich mit Ihren Lab-Anmeldedaten an. Wenn Sie andere Anmeldedaten verwenden, kann dies zu Fehlern führen oder es fallen Kosten an.
Akzeptieren Sie die Nutzungsbedingungen und überspringen Sie die Seite zur Wiederherstellung der Ressourcen
Klicken Sie erst auf Lab beenden, wenn Sie das Lab abgeschlossen haben oder es neu starten möchten. Andernfalls werden Ihre bisherige Arbeit und das Projekt gelöscht.
Diese Inhalte sind derzeit nicht verfügbar
Bei Verfügbarkeit des Labs benachrichtigen wir Sie per E-Mail
Sehr gut!
Bei Verfügbarkeit kontaktieren wir Sie per E-Mail
Es ist immer nur ein Lab möglich
Bestätigen Sie, dass Sie alle vorhandenen Labs beenden und dieses Lab starten möchten
Privates Surfen für das Lab verwenden
Nutzen Sie den privaten oder Inkognitomodus, um dieses Lab durchzuführen. So wird verhindert, dass es zu Konflikten zwischen Ihrem persönlichen Konto und dem Teilnehmerkonto kommt und zusätzliche Gebühren für Ihr persönliches Konto erhoben werden.
In this lab, you'll call services in parallel using JavaScript.