Using the JavaScript Client Library

This page demonstrates how to use the google-apis-javascript-client library with Google Compute Engine. In this exercise, you use the JavaScript client library to authorize requests, and create, list, or delete Google Compute Engine resources from outside 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.

To complete this tutorial, you must have some proficiency with HTML and JavaScript.

Before you begin

  • If you are new to Google Compute Engine, try one of the Quickstart tutorials.
  • To run the JavaScript examples in this tutorial, set up a web server. If you are using a laptop or desktop, you can install a web server such as Apache or Nginx on your machine. If you want to set up a web server in a Google Compute Engine instance, see Running a basic Apache web server.
If you

Getting Started

This example describes how to use OAuth 2.0 authorization in a web application, and how to manage instances 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

For an advanced code sample, visit the GoogleCloudPlatform GitHub page.

Loading the Client Library

To use the JavaScript client library in your application, 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 loads the client library:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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 Cloud Platform Console. If you already have a registered application, you can use the client ID and client secret from that application. If you don't have a registered application or would like to register a new application:

  1. In the Google Cloud Platform Console, go to the Credentials page.

    Go to the Credentials page

  2. Click Create credentials, and select OAuth client ID.
  3. If this is your first application, you are prompted to create a consent screen, which is displayed when your applications request access to your users' data. Click Configure consent screen, fill out the form with information about your application. Save your changes.
  4. On the Create client ID page, select Web application, and click Create.
  5. Type a name for the key, and in the Authorized JavaScript origins box, type the origin URI of your application. For example, if you are hosting your application on myexampleapplication.com, the origin URI is http://myexampleapplication.com. If you are testing the application on your desktop or laptop, you can use http://localhost .
  6. To create the key, click Create.
  7. Save your client ID and the client secret, so that you can use them in your application.

To authorize your application, use the gapi.auth.authorize() method, and provide your:

  • Client ID
  • Client secret, in the API_KEY variable
  • A callback function
The method also provides an immediate field. If you set immediate to true, the authorization is performed in the backgcround, 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="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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>

Open your page in a browser. After the page loads, you are prompted to authorize the application. After you have successfully authorized the application, an alert is shown, letting you know that your application was authorized successfully.

Initializing the Google Compute Engine API in the application

Next, you 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, then invoke it after your application has been successfully authorized:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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 explore basic operations, start by constructing requests to list specific resources. Add the following to your page:

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

Now, define the 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
  });
}

In addition to the project and zone fields, you can add fields for the maximum result size, filter instances, and other configurations. For a list of all possible fields for this method, see 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="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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 useful feature when listing resources is the filter field, which filters your results based an expression. For example, you can exclude terminated instances by using 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 methods 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.firewalls.list()

Listing Operations

You can list the following types of operations:

  • Per-zone operations are operations performed on resources that are in a specific zone. For example, per-zone operations include operations performed on 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 of regions and zones.

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 web page, add the following lines:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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 page, add the following lines:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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>

Adding a Disk

Before you can create an instance, you need to provide a bootable root persistent disk for the instance. To add a disk, use the gapi.client.compute.disks.insert() method, and specify 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 web page, add the following lines:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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_FAMILY = 'debian-9';

     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/family/' +
       DEFAULT_IMAGE_FAMILY;

     [...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()">Add a Disk</button>
  </body>
</html>

Refresh your page in the browser, and click the Add a Disk button to create your new disk.

Adding an Instance

To add an instance, use the gapi.client.compute.instances.insert() method, and specify 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, as in the following example:

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="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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()">Add a Disk</button>
    <button onclick="insertInstance()">Add 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.

Adding an Instance with Metadata

When you create an instance, you can also pass 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 to your code, as shown below:

/**
 * 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 an instance, use the gapi.client.compute.instances.get() method, and provide the instance and project fields:

/**
 * 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 page, add the following lines:

<!DOCTYPE html>

  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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 the Get an Instance button.

Deleting an Instance

To delete an instance, use the gapi.client.compute.instances.delete() method, and provide the instance name and 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 page, add the following lines:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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 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 page, add the following code:

<!DOCTYPE html>
<html>
  <head>
   <meta charset='utf-8' />
   <link rel="stylesheet" src="style.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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 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="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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_FAMILY = 'debian-9';

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/family/' +
  DEFAULT_IMAGE_FAMILY;

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>

What's next

After you have completed this exercise, you can:

  • Download an advanced sample, and view other samples at the googlecloudplatform GitHub page. The advanced sample includes some more complex dispatching methods and is cleaner than our sample here.
  • If you want to use the Python client library, see Using the Python Client Library.
  • For information on performing other tasks with the API, review the API reference.
  • Start creating your own applications!

Send feedback about...

Compute Engine Documentation