Please note that the contents of this offline web site may be out of date. To access the most recent documentation visit the online version .
Note that links that point to online resources are green in color and will open in a new window.
We would love it if you could give us feedback about this material by filling this form (You have to be online to fill it)



Using Javascript Client Library

This document demonstrates how to use the google-apis-javascript-client library with Google Compute Engine. It describes how to authorize requests and how to create, list, and stop instances. This exercise discusses how to use the google-api-javascript-client library to access Google Compute Engine from outside a VM instance. It does not discuss how to build and run applications within a VM instance.

For a full list of available client libraries, including other Google client libraries and third-party open source libraries, see the Client Libraries page .

Contents

Setup

There is no setup necessary for this sample. However, you should have some proficiency with Javascript and have access to use Google Compute Engine. If not, please visit the signup page . This sample also assumes you have basic HTML knowledge and access to a webserver.

Getting Started

This basic sample describes how to use OAuth 2.0 authorization, and how to perform instance management tasks using the google-api-javascript-client library. At the end of this exercise, you should be able to:

  • Authorize your application to make requests to the Google Compute Engine API
  • Insert instances
  • List instances
  • List other resources (images, machine types, zones, machine type, networks, firewalls, and operations)
  • Delete instances

To skip this exercise and view the more advanced code sample, visit the GoogleCloudPlatform GitHub page.

Loading the Client Library

To use the Javascript client library, you first need to load it. The Javascript client library is located at:

https://apis.google.com/js/client.js

Create a basic HTML file that looks like the following:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
 </head>
  <body>
  </body>
</html>

Authorizing Requests

This sample uses a simple API key and client ID authorization method. To start, all applications are managed by the Google Developers Console . If you already have a registered application, you can use the client ID and API key from that application. If you don't have a registered application or would like to register a new application, follow the application registration process . Make sure to select Web Application as the application type.

Once on the application's page, expand the OAuth 2.0 Client ID section and make note of the Client ID . Then, expand the Browser Key section and make note of the API Key .

To authorize your application, use the gapi.auth.authorize() method, providing your client ID, API key, and a callback function. The method also provides an immediate field, which, when set to true, means that authorization is performed behind the scenes and no prompt is presented to the user. Add the following code to your HTML page:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">
     var PROJECT_ID = 'YOUR_PROJECT_ID';
     var CLIENT_ID = 'YOUR_CLIENT_ID';
     var API_KEY = 'YOUR_API_KEY';
     var SCOPES = 'https://www.googleapis.com/auth/compute';

     /**
      * Authorize Google Compute Engine API.
      */
     function authorization() {
       gapi.client.setApiKey(API_KEY);
       gapi.auth.authorize({
         client_id: CLIENT_ID,
         scope: SCOPES,
         immediate: false
       }, function(authResult) {
            if (authResult && !authResult.error) {
              window.alert('Auth was successful!');
            } else {
              window.alert('Auth was not successful');
            }
          }
       );
     }

     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
  </body>
</html>

View your page in a browser. On load, you should be prompted to authorize the application; once successfully authorized, an alert window should appear letting you know that your application was authorized successfully.

Initializing the Google Compute Engine API

Next, you need to initialize the API by calling gapi.client.load() , which accepts the API name, and API version number as parameters. In your HTML page, add an initialization function and invoke it once your application has been successfully authorized:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">
     var PROJECT_ID = 'YOUR_PROJECT_ID';
     var CLIENT_ID = 'YOUR_CLIENT_ID';
     var API_KEY = 'YOUR_API_KEY';
     var SCOPES = 'https://www.googleapis.com/auth/compute';
     var API_VERSION = 'v1';

     /**
      * Load the Google Compute Engine API.
      */
     function initializeApi() {
       gapi.client.load('compute', API_VERSION);
     }

     /**
      * Authorize Google Compute Engine API.
      */
     function authorization() {
       gapi.client.setApiKey(API_KEY);
       gapi.auth.authorize({
         client_id: CLIENT_ID,
         scope: SCOPES,
         immediate: false
       }, function(authResult) {
            if (authResult && !authResult.error) {
              initializeApi();
            } else {
              window.alert('Auth was not successful');
            }
          }
       );
     }

     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
  </body>
</html>

That's it! You can now start making requests to the API.

Listing Instances

To demonstrate some basic operations, start by constructing requests to list specific resources. Add the following to your webpage:

  </head>
  <body>
    <header>
      <h1>Google Compute Engine JavaScript Client Library Application</h1>
    </header>
    <button onclick="listInstances()">List Instances</button>
  </body>
</html>

Now, lets define our listInstances() function. To list instances, use the gapi.client.compute.instances.list() method:

/**
 * Google Compute Engine API request to retrieve the list of instances in
 * your Google Compute Engine project.
 */
function listInstances() {
  var request = gapi.client.compute.instances.list({
    'project': DEFAULT_PROJECT,
    'zone': DEFAULT_ZONE
  });
  request.execute(function(resp) {
    // Code to handle response
  });
}

The only required field for this method is the project field but you can also add fields that determine max result size, help filter instances, and other configurations. To see a list of all possible fields for this method, visit the API Explorer or review the API documentation .

Add the new listInstances() function to your webpage as follows:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">
     var PROJECT_ID = 'YOUR_PROJECT_ID';
     var CLIENT_ID = 'YOUR_CLIENT_ID';
     var API_KEY = 'YOUR_API_KEY';
     var SCOPES = 'https://www.googleapis.com/auth/compute';
     var API_VERSION = 'v1';
     
     var DEFAULT_PROJECT = PROJECT_ID;
     var DEFAULT_ZONE = 'ZONE_NAME'; // For example, us-central1-a
     

     /**
      * Load the Google Compute Engine API.
      */
     function initializeApi() {
       gapi.client.load('compute', API_VERSION);
     }

     /**
      * Authorize Google Compute Engine API.
      */
     function authorization() {
       gapi.client.setApiKey(API_KEY);
       gapi.auth.authorize({
         client_id: CLIENT_ID,
         scope: SCOPES,
         immediate: false
       }, function(authResult) {
            if (authResult && !authResult.error) {
              initializeApi();
            } else {
              window.alert('Auth was not successful');
            }
          }
       );
     }

     /**
      * Google Compute Engine API request to retrieve the list of instances in
      * your Google Compute Engine project.
      */
     function listInstances() {
       var request = gapi.client.compute.instances.list({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE
       });
       executeRequest(request, 'listInstances');
     }

     /**
      * Executes your Google Compute Engine request object and, subsequently,
      * prints the response.
      * @param {gapi.client.request} request A Google Compute Engine request
      *     object issued from the Google APIs JavaScript client library.
      * @param {string} apiRequestName The name of the example API request.
      */
     function executeRequest(request, apiRequestName) {
       request.execute(function(resp) {
         newWindow = window.open(apiRequestName, '',
           'width=600, height=600, scrollbars=yes');
         newWindow.document.write('<h1>' + apiRequestName + '</h1> <br />' +
           '<pre>' + JSON.stringify(resp.result, null, ' ') + '</pre>');
         if (resp.error) {
           newWindow.document.write('<h1>Error:</h1>');
           newWindow.document.write('<pre>' +
             JSON.stringify(resp.error, null, ' ') + '</pre>');
         }
       });
     }

     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
    <header>
      <h1>Google Compute Engine JavaScript Client Library Application</h1>
    </header>
    <button onclick="listInstances()">List Instances</button>
  </body>
</html>

Refresh your page and click the new List Instances button, which returns a list of instances that belong to the project you specified.

Filtering List Results

A particular useful feature when listing resources is the filter field, which allows you to filter your results based an expression. For example, you can filter terminated instances from running instances by providing the following filter expression:

/**
 * Google Compute Engine API request to retrieve a filtered list
 *  of instances in  your Google Compute Engine project.
 */
function listInstancesWithFilter() {
  var request = gapi.client.compute.instances.list({
    'project': DEFAULT_PROJECT,
    'zone': DEFAULT_ZONE,
    'filter': 'status ne TERMINATED'
  });
  var apiRequestName = 'listInstancesWithFilter';
  executeRequest(request, apiRequestName);
}

Listing Other Resources

To list other resources, use the respective methods described below:

Type Method
List Zones gapi.client.compute.zones.list()
List Machine Types gapi.client.compute.machinetypes.list()
List Global Operations gapi.client.compute.globalOperations.list()
List Per-zone Operations gapi.client.compute.zoneOperations.list()
List Images gapi.client.compute.images.list()
List Firewalls gapi.client.compute.machinetypes.list()

Listing Operations

Listing operation resources is unique because there are two types of operations you can list: per-zone and global operations. A per-zone operation is an operation performed on a resource that lives in a zone. Specifically, per-zone operations include disks and instances. Global operations are operations performed on global resources, such as machine types and images. For more information on per-zone and global resources, see the overview .

Listing Per-Zone Operations

To view a list of per-zone operations, use the gapi.client.compute.zoneOperations.list() method:

/**
 * Google Compute Engine API request to retreive the list of operations
 * (inserts, deletes, etc.) for your Google Compute Engine project.
 */
function listZoneOperations() {
  var request = gapi.client.compute.zoneOperations.list({
    'project': DEFAULT_PROJECT,
    'zone': DEFAULT_ZONE
  });
  executeRequest(request, 'listZoneOperations');
}

In your webpage, add the following lines:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">

     [...snip...]

     /**
      * Google Compute Engine API request to retreive the list of operations
      * (inserts, deletes, etc.) for your Google Compute Engine project.
      */
     function listZoneOperations() {
       var request = gapi.client.compute.zoneOperations.list({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE
       });
       executeRequest(request, 'listZoneOperations');
     }

     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
    <header>
      <h1>Google Compute Engine JavaScript Client Library Application</h1>
    </header>
    <button onclick="listInstances()">List Instances</button>
    <button onclick="listZoneOperations()">List Zone Operations</button>
  </body>
</html>
Listing Global Operations

To view a list of global operations, use the gapi.client.compute.globalOperations.list() method:

/**
 * Google Compute Engine API request to retreive the list of global
 * operations (inserts, deletes, etc.) for your Google Compute Engine
 * project.
 */
function listGlobalOperations() {
  var request = gapi.client.compute.globalOperations.list({
    'project': DEFAULT_PROJECT
  });
  executeRequest(request, 'listGlobalOperations');
}

In your webpage, add the following lines:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">

     [...snip...]
    
     /**
      * Google Compute Engine API request to retreive the list of global
      * operations (inserts, deletes, etc.) for your Google Compute Engine
      * project.
      */
     function listGlobalOperations() {
       var request = gapi.client.compute.globalOperations.list({
         'project': DEFAULT_PROJECT
       });
       executeRequest(request, 'listGlobalOperations');
     }

     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
    <header>
      <h1>Google Compute Engine JavaScript Client Library Application</h1>
    </header>
    <button onclick="listInstances()">List Instances</button>
    <button onclick="listZoneOperations()">List Zone Operations</button>
    <button onclick="listGlobalOperations()">List Global Operations</button>
  </body>
</html>

Inserting a Disk

Before you can create an instance, you'll need to provide a bootable root persistent disk for the instance. To insert a disk, use the gapi.client.compute.disks.insert() method, specifying the name, size, zone and source image with your request:

/**
 * Google Compute Engine API request to insert a disk into your cluster.
 */
function insertDisk() {
  var request = gapi.client.compute.disks.insert({
    'project': DEFAULT_PROJECT,
    'zone': DEFAULT_ZONE,
    'sourceImage': DEFAULT_IMAGE_URL,
    'resource': {
      'name': DEFAULT_DISK_NAME
    }
  });
  executeRequest(request, 'insertDisk');
}

In your webpage, add the following lines:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">

     [...snip...]
     
     var DEFAULT_NAME = 'test-node';
     var GOOGLE_PROJECT = 'debian-cloud'; // project hosting a shared image
     var DEFAULT_DISK_NAME = DEFAULT_NAME;
     var DEFAULT_IMAGE = 'debian-7-wheezy-v20131120';

     var BASE_URL = 'https://www.googleapis.com/compute/' + API_VERSION;
     var PROJECT_URL = BASE_URL + '/projects/' + DEFAULT_PROJECT;
     var GOOGLE_PROJECT_URL = BASE_URL + '/projects/' + GOOGLE_PROJECT;
     var DEFAULT_DISK_URL = PROJECT_URL + '/zones/' + DEFAULT_ZONE +
       '/disks/' + DEFAULT_DISK_NAME;
     var DEFAULT_IMAGE_URL = GOOGLE_PROJECT_URL + '/global/images/' +
       DEFAULT_IMAGE;

     [...snip...]

     /**
      * Google Compute Engine API request to insert a disk into your cluster.
      */
     function insertDisk() {
       var request = gapi.client.compute.disks.insert({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'sourceImage': DEFAULT_IMAGE_URL,
         'resource': {
           'name': DEFAULT_DISK_NAME
         }
       });
       executeRequest(request, 'insertDisk');
     }
     
     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
    <header>
      <h1>Google Compute Engine JavaScript Client Library Application</h1>
    </header>
    <button onclick="listInstances()">List Instances</button>
    <button onclick="listZoneOperations()">List Zone Operations</button>
    <button onclick="listGlobalOperations()">List Global Operations</button>
    <button onclick="insertDisk()">Insert a Disk</button>
  </body>
</html>

Refresh your webpage in the browser and click the Insert a Disk button to create your new disk.

Inserting an Instance

To insert an instance, use the gapi.client.compute.instances.insert() method, specifying an image, zone, machine type, and network interface object with your request:

/**
 * Google Compute Engine API request to insert your instance
 */
function insertInstance() {
  resource = {
    'image': DEFAULT_IMAGE_URL,
    'name': DEFAULT_IMAGE_NAME,
    'machineType': DEFAULT_MACHINE_URL,
    'disks': [{
     'source': DEFAULT_DISK_URL,
     'type': 'PERSISTENT',
     'boot': true
    }],
    'networkInterfaces': [{
      'network': DEFAULT_NETWORK
    }]
  };
  var request = gapi.client.compute.instances.insert({
    'project': DEFAULT_PROJECT,
    'zone': DEFAULT_ZONE,
    'resource': resource
  });
  request.execute(function(resp) {
    // Code to handle response
  });
}
Each resource page describes available zones, images, and machine types that you can use. When indicating specific resources, provide the full URL for the resource; for example, to specify an image, you need to provide the full URL to the image resource, like so:

https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/<image-name>

The URLs to other resources include:

Resource URL
Machine Types https://www.googleapis.com/compute/v1/projects/ <project-id> /global/machineTypes/ <machine-name>
Zones https://www.googleapis.com/compute/v1/projects/ <project-id> /zones/ <zone-name>
Network https://www.googleapis.com/compute/v1/projects/ <project-id> /global/networks/ <network-name>

In your webpage, add the following lines:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">

     [...snip...]
     
     var DEFAULT_IMAGE_NAME = DEFAULT_NAME;
     var DEFAULT_MACHINE_TYPE = 'n1-standard-1';

     var DEFAULT_MACHINE_URL = PROJECT_URL + '/zones/' + DEFAULT_ZONE +
       '/machineTypes/' + DEFAULT_MACHINE_TYPE;
     var DEFAULT_NETWORK = PROJECT_URL + '/global/networks/default';

     [...snip...]

     /**
      * Google Compute Engine API request to insert your instance
      */
     function insertInstance() {
       resource = {
         'image': DEFAULT_IMAGE_URL,
         'name': DEFAULT_IMAGE_NAME,
         'machineType': DEFAULT_MACHINE_URL,
         'disks': [{
          'source': DEFAULT_DISK_URL,
          'type': 'PERSISTENT',
          'boot': true
         }],
         'networkInterfaces': [{
           'network': DEFAULT_NETWORK
         }]
       };
       var request = gapi.client.compute.instances.insert({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'resource': resource
       });
       executeRequest(request, 'insertInstance');
     }
     
     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
    <header>
      <h1>Google Compute Engine JavaScript Client Library Application</h1>
    </header>
    <button onclick="listInstances()">List Instances</button>
    <button onclick="listZoneOperations()">List Zone Operations</button>
    <button onclick="listGlobalOperations()">List Global Operations</button>
    <button onclick="insertDisk()">Insert a Disk</button>
    <button onclick="insertInstance()">Insert an Instance</button>
  </body>
</html>

Refresh your webpage in the browser and click the Insert Instance button to create your new instance. Click the List Instances button to see your new instance appear in your list of instances.

Inserting an Instance with Metadata

When creating an instance, you can also pass in custom metadata . You can define any type of custom metadata, but custom metadata is particularly useful for running startup scripts . To create an instance with custom metadata, add the metadata field like so:

/**
 * Google Compute Engine API request to insert your instance with metadata
 */
function insertInstanceWithMetadata() {
  resource = {
    'image': DEFAULT_IMAGE_URL,
'name': 'node-with-metadata',
'machineType': DEFAULT_MACHINE_URL,
'disks': [{
 'source': DEFAULT_DISK_URL,
 'type': 'PERSISTENT',
 'boot': true
}],
'networkInterfaces': [{
  'network': DEFAULT_NETWORK
}],
'metadata': {
  'items': [{
    'value': 'apt-get install apache2',
    'key': 'startup-script'
  }]
}
  };
  var request = gapi.client.compute.instances.insert({
    'project': DEFAULT_PROJECT,
    'zone': DEFAULT_ZONE,
    'resource': resource
  });
  executeRequest(request, 'insertInstance');
}

The metadata for this instance defines a startup script that installs apache2.

Getting an Instance

To get information about a particular instance, use the gapi.client.compute.instances.get() method, passing in the instance and project field:

/**
 * Google Compute Engine API request to get your instance
 */
function getInstance() {
  var request = gapi.client.compute.instances.get({
    'project': DEFAULT_PROJECT,
    'zone': DEFAULT_ZONE,
    'instance': DEFAULT_IMAGE_NAME
  });
  request.execute(function(resp) {
    // Code to handle response
  });
}

In your webpage, add the following lines:

<!DOCTYPE html>

  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">

     [...snip...]
    
     /**
      * Google Compute Engine API request to get your instance
      */
     function getInstance() {
       var request = gapi.client.compute.instances.get({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'instance': DEFAULT_IMAGE_NAME
       });
       executeRequest(request, 'getInstance');
     }
    
     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
    <header>
      <h1>Google Compute Engine JavaScript Client Library Application</h1>
    </header>
    <button onclick="listInstances()">List Instances</button>
    <button onclick="listZoneOperations()">List Zone Operations</button>
    <button onclick="listGlobalOperations()">List Global Operations</button>
    <button onclick="insertDisk()">Insert a Disk</button>
    <button onclick="insertInstance()">Insert an Instance</button>
    <button onclick="getInstance()">Get an Instance</button>
  </body>
</html>

Refresh your page and click on the Get an Instance button.

Deleting an Instance

To delete an instance, use the gapi.client.compute.instances.delete() method, providing the instance name and the project id:

/**
 * Google Compute Engine API request to delete your instance
 */
function deleteInstance() {
  var request = gapi.client.compute.instances.delete({
    'project': DEFAULT_PROJECT,
    'zone': DEFAULT_ZONE,
    'instance': DEFAULT_IMAGE_NAME
  });
  request.execute(function(resp) {
    // Code to handle response
  });
}

In your webpage, add the following lines:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">

     [...snip...]
    
     /**
      * Google Compute Engine API request to delete your instance
      */
     function deleteInstance() {
       var request = gapi.client.compute.instances.delete({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'instance': DEFAULT_IMAGE_NAME
       });
       executeRequest(request, 'deleteInstance');
     }
    
     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
    <header>
      <h1>Google Compute Engine JavaScript Client Library Application</h1>
    </header>
    <button onclick="listInstances()">List Instances</button>
    <button onclick="listZoneOperations()">List Zone Operations</button>
    <button onclick="listGlobalOperations()">List Global Operations</button>
    <button onclick="insertDisk()">Insert a Disk</button>
    <button onclick="insertInstance()">Insert an Instance</button>
    <button onclick="getInstance()">Get an Instance</button>
    <button onclick="deleteInstance()">Delete an Instance</button>
  </body>
</html>

Refresh your page and click on the Delete an Instance button.

Deleting a Disk

To delete a disk, use the gapi.client.compute.disks.delete() method, providing the disk name, project id and zone:

/**
 * Google Compute Engine API request to delete your disk
 */
function deleteDisk() {
  var request = gapi.client.compute.disks.delete({
    'project': DEFAULT_PROJECT,
    'zone': DEFAULT_ZONE,
    'disk': DEFAULT_DISK_NAME
  });
  executeRequest(request, 'deleteDisk');
}

In your webpage, add the following lines:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">

     [...snip...]
    
     /**
      * Google Compute Engine API request to delete your disk
      */
     function deleteDisk() {
       var request = gapi.client.compute.disks.delete({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'disk': DEFAULT_DISK_NAME
       });
       executeRequest(request, 'deleteDisk');
     }
    
     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
    <header>
      <h1>Google Compute Engine JavaScript Client Library Application</h1>
    </header>
    <button onclick="listInstances()">List Instances</button>
    <button onclick="listZoneOperations()">List Zone Operations</button>
    <button onclick="listGlobalOperations()">List Global Operations</button>
    <button onclick="insertDisk()">Insert a Disk</button>
    <button onclick="insertInstance()">Insert an Instance</button>
    <button onclick="getInstance()">Get an Instance</button>
    <button onclick="deleteInstance()">Delete an Instance</button>
    <button onclick="deleteDisk()">Delete a disk</button>
  </body>
</html>

Refresh your page and click on the Delete a Disk button.

Full Sample

Here is the full code sample for this exercise:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
   <script src="https://apis.google.com/js/client.js"></script>
   <script type="text/javascript">
     var PROJECT_ID = 'YOUR_PROJECT_ID';
     var CLIENT_ID = 'YOUR_CLIENT_ID';
     var API_KEY = 'YOUR_API_KEY';
     var SCOPES = 'https://www.googleapis.com/auth/compute';
     var API_VERSION = 'v1';

     var DEFAULT_PROJECT = PROJECT_ID;
     var DEFAULT_ZONE = 'ZONE_NAME'; // For example, us-central1-a

     var DEFAULT_NAME = 'test-node';
     var GOOGLE_PROJECT = 'debian-cloud'; // project hosting a shared image
     var DEFAULT_DISK_NAME = DEFAULT_NAME;
     var DEFAULT_IMAGE = 'debian-7-wheezy-v20131120';

     var BASE_URL = 'https://www.googleapis.com/compute/' + API_VERSION;
     var PROJECT_URL = BASE_URL + '/projects/' + DEFAULT_PROJECT;
     var GOOGLE_PROJECT_URL = BASE_URL + '/projects/' + GOOGLE_PROJECT;
     var DEFAULT_DISK_URL = PROJECT_URL + '/zones/' + DEFAULT_ZONE +
       '/disks/' + DEFAULT_DISK_NAME;
     var DEFAULT_IMAGE_URL = GOOGLE_PROJECT_URL + '/global/images/' +
       DEFAULT_IMAGE;

     var DEFAULT_IMAGE_NAME = DEFAULT_NAME;
     var DEFAULT_MACHINE_TYPE = 'n1-standard-1';

     var DEFAULT_MACHINE_URL = PROJECT_URL + '/zones/' + DEFAULT_ZONE +
       '/machineTypes/' + DEFAULT_MACHINE_TYPE;
     var DEFAULT_NETWORK = PROJECT_URL + '/global/networks/default';

     /**
      * Authorize Google Compute Engine API.
      */
     function authorization() {
       gapi.client.setApiKey(API_KEY);
       gapi.auth.authorize({
         client_id: CLIENT_ID,
         scope: SCOPES,
         immediate: false
       }, function(authResult) {
            if (authResult && !authResult.error) {
              initializeApi();
            } else {
              window.alert('Auth was not successful');
            }
          }
       );
     }

     /**
      * Load the Google Compute Engine API.
      */
     function initializeApi() {
       gapi.client.load('compute', API_VERSION);
     }

     /**
      * Executes your Google Compute Engine request object and, subsequently,
      * prints the response.
      * @param {gapi.client.request} request A Google Compute Engine request
      *     object issued from the Google APIs JavaScript client library.
      * @param {string} apiRequestName The name of the example API request.
      */
     function executeRequest(request, apiRequestName) {
       request.execute(function(resp) {
         newWindow = window.open(apiRequestName, '',
           'width=600, height=600, scrollbars=yes');
         newWindow.document.write('<h1>' + apiRequestName + '</h1> <br />' +
           '<pre>' + JSON.stringify(resp.result, null, ' ') + '</pre>');
         if (resp.error) {
           newWindow.document.write('<h1>Error:</h1>');
           newWindow.document.write('<pre>' +
             JSON.stringify(resp.error, null, ' ') + '</pre>');
         }
       });
     }

     /**
      * Google Compute Engine API request to delete your instance
      */
     function deleteInstance() {
       var request = gapi.client.compute.instances.delete({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'instance': DEFAULT_IMAGE_NAME
       });
       executeRequest(request, 'deleteInstance');
     }

     /**
      * Google Compute Engine API request to delete your disk
      */
     function deleteDisk() {
       var request = gapi.client.compute.disks.delete({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'disk': DEFAULT_DISK_NAME
       });
       executeRequest(request, 'deleteDisk');
     }

     /**
      * Google Compute Engine API request to get your instance
      */
     function getInstance() {
       var request = gapi.client.compute.instances.get({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'instance': DEFAULT_IMAGE_NAME
       });
       executeRequest(request, 'getInstance');
     }

     /**
      * Google Compute Engine API request to insert a disk into your cluster.
      */
     function insertDisk() {
       var request = gapi.client.compute.disks.insert({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'sourceImage': DEFAULT_IMAGE_URL,
         'resource': {
           'name': DEFAULT_DISK_NAME
         }
       });
       executeRequest(request, 'insertDisk');
     }

     /**
      * Google Compute Engine API request to insert your instance with metadata
      */
     function insertInstanceWithMetadata() {
       resource = {
         'image': DEFAULT_IMAGE_URL,
         'name': 'node-with-metadata',
         'machineType': DEFAULT_MACHINE_URL,
         'disks': [{
          'source': DEFAULT_DISK_URL,
          'type': 'PERSISTENT',
          'boot': true
         }],
         'networkInterfaces': [{
           'network': DEFAULT_NETWORK
         }],
         'metadata': {
           'items': [{
             'value': 'apt-get install apache2',
             'key': 'startup-script'
           }]
         }
       };
       var request = gapi.client.compute.instances.insert({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'resource': resource
       });
       executeRequest(request, 'insertInstance');
     }

     /**
      * Google Compute Engine API request to insert your instance
      */
     function insertInstance() {
       resource = {
         'image': DEFAULT_IMAGE_URL,
         'name': DEFAULT_IMAGE_NAME,
         'machineType': DEFAULT_MACHINE_URL,
         'disks': [{
          'source': DEFAULT_DISK_URL,
          'type': 'PERSISTENT',
          'boot': true
         }],
         'networkInterfaces': [{
           'network': DEFAULT_NETWORK
         }]
       };
       var request = gapi.client.compute.instances.insert({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'resource': resource
       });
       executeRequest(request, 'insertInstance');
     }

     /**
      * Google Compute Engine API request to retreive the list of global
      * operations (inserts, deletes, etc.) for your Google Compute Engine
      * project.
      */
     function listGlobalOperations() {
       var request = gapi.client.compute.globalOperations.list({
         'project': DEFAULT_PROJECT
       });
       executeRequest(request, 'listGlobalOperations');
     }

     /**
      * Google Compute Engine API request to retreive the list of operations
      * (inserts, deletes, etc.) for your Google Compute Engine project.
      */
     function listZoneOperations() {
       var request = gapi.client.compute.zoneOperations.list({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE
       });
       executeRequest(request, 'listZoneOperations');
     }

     /**
      * Google Compute Engine API request to retrieve a filtered list
      *  of instances in  your Google Compute Engine project.
      */
     function listInstancesWithFilter() {
       var request = gapi.client.compute.instances.list({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE,
         'filter': 'status ne TERMINATED'
       });
       var apiRequestName = 'listInstancesWithFilter';
       executeRequest(request, apiRequestName);
     }

     /**
      * Google Compute Engine API request to retrieve the list of instances in
      * your Google Compute Engine project.
      */
     function listInstances() {
       var request = gapi.client.compute.instances.list({
         'project': DEFAULT_PROJECT,
         'zone': DEFAULT_ZONE
       });
       executeRequest(request, 'listInstances');
     }

     /**
      * Driver for sample application.
      */
     $(window).load(authorization);
    </script>
  </head>
  <body>
   <header>
      <h1>Google Compute Engine JavaScript Client Library Application</h1>
    </header>
    <button onclick="listInstances()">List Instances</button>
    <button onclick="listInstancesWithFilter()">List Instances with Filter</button>
    <button onclick="listZoneOperations()">List Zone Operations</button>
    <button onclick="listGlobalOperations()">List Global Operations</button>
    <button onclick="insertDisk()">Insert a Disk</button>
    <button onclick="insertInstance()">Insert an Instance</button>
    <button onclick="insertInstanceWithMetadata()">Insert Instance with Metadata</button>
    <button onclick="getInstance()">Get an Instance</button>
    <button onclick="deleteInstance()">Delete an Instance</button>
    <button onclick="deleteDisk()">Delete a disk</button>
  </body>
</html>

Next Steps

Now that you have completed this exercise, you can:

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.