2.1.2 • Public • Published

Google APIs Node.js Client

Build Status Code Coverage

Google's officially supported node.js client library for using Google APIs. It also supports authorization and authentication with OAuth 2.0.


This library is in Alpha. We will make an effort to support the library, but we reserve the right to make incompatible changes when necessary.

Migrating to version 2.x of this library

If you've used this library before 1.x, see our Migration Guide to learn about migrating your code from 0.x.x to 1.x. It's pretty easy :)

If your code already works with a 1.x version of this library, no work is required to move to 2.x. However, note that return data of getToken has become an array. Furthermore, it is recommended that you update any direct links in your code, as explained in the Migration Guide.

Supported APIs

The full list of supported APIs can be found here. The API endpoints are automatically generated, so if the API is not in the list, it is currently not supported by this API client library.


  • Ask your development related questions on Ask a question on Stackoverflow
  • If you've found an bug/issue, please file it on GitHub.

Working with Google Cloud APIs?

If you're working with Google Cloud Platform APIs such as Datastore, Cloud Storage or Pub/Sub, consider using gcloud, a Node idiomatic client for Google Cloud services.


This library is distributed on npm. In order to add it as a dependency, run the following command:

$ npm install googleapis --save


Example: Creates a URL Shortener client and retrieves the long url of the given short url:

var google = require('googleapis');
var urlshortener = google.urlshortener('v1');
var params = { shortUrl: '' };
// get the long url of a shortened url
urlshortener.url.get(params, function (err, response) {
  if (err) {
    console.log('Encountered error', err);
  } else {
    console.log('Long url is', response.longUrl);

Create a service client

To interact with the various Google APIs you need to create a service client for that particular API. These are immutable objects you use to make API calls.

Example: Creating a urlshortener client with version v1 of the API.

var google = require('googleapis');
var urlshortener = google.urlshortener('v1');

Supported APIs are listed on the Google APIs Explorer.

Authorizing and Authenticating

This client comes with an OAuth2 client that allows you to retrieve an access token and refreshes the token and retry the request seamlessly if token is expired. The basics of Google's OAuth2 implementation is explained on Google Authorization and Authentication documentation.

In the following examples, you may need a CLIENT_ID, CLIENT_SECRET and REDIRECT_URL. You can find these pieces of information by going to the Developer Console, clicking your project --> APIs & auth --> credentials.

For more information about OAuth2 and how it works, see here.

A complete sample application that authorizes and authenticates with the OAuth2 client is available at examples/oauth2.js.

Generating an authentication URL

To ask for permissions from a user to retrieve an access token, you redirect them to a consent page. To create a consent page URL:

var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
// generate a url that asks permissions for Google+ and Google Calendar scopes
var scopes = [
var url = oauth2Client.generateAuthUrl({
  access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
  scope: scopes // If you only need one scope you can pass it as string

Retrieve authorization code

Once a user has given permissions on the consent page, Google will redirect the page to the redirect URL you have provided with a code query parameter.

GET /oauthcallback?code={authorizationCode}

Retrieve access token

With the code returned, you can ask for an access token as shown below:

oauth2Client.getToken(code, function(err, tokens) {
  // Now tokens contains an access_token and an optional refresh_token. Save them.
  if(!err) {

Setting global or service-level auth

You can set the auth as a global or service-level option so you don't need to specify it every request.

Example: Setting a global auth option.

var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
google.options({ auth: oauth2Client }); // set auth as a global default

Example: Setting a service-level auth option.

var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var drive ={ version: 'v2', auth: oauth2Client });

See the Options section for more information.

Making Authenticated Requests

You can start using OAuth2 to authorize and authenticate your requests to Google APIs with the retrieved tokens. If you provide a refresh_token and the access_token has expired, the access_token will be automatically refreshed and the request is replayed.

Following sample retrieves Google+ profile of the authenticated user.

var google = require('googleapis');
var plus ='v1');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
// Retrieve tokens via token exchange explained above or set them:
  access_token: 'ACCESS TOKEN HERE',
  refresh_token: 'REFRESH TOKEN HERE'
plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) {
  // handle err and response

Manually refreshing access token

If you need to manually refresh the access_token associated with your OAuth2 client, make sure you have a refresh_token set in your credentials first and then call:

oauth2Client.refreshAccessToken(function(err, tokens) {
  // your access_token is now refreshed and stored in oauth2Client
  // store these new tokens in a safe place (e.g. database)

Using API keys

You may need to send an API key with the request you are going to make. The following uses an API key to make a request to the Google+ API service to retrieve a person's profile given a userId:

var google = require('googleapis');
var plus ='v1');
var API_KEY = 'ABC123'; // specify your API key here
plus.people.get({ auth: API_KEY, userId: '+google' }, function(err, user) {
  console.log('Result: ' + (err ? err.message : user.displayName));

Alternatively, you can specify the key parameter and it will get used:

plus.people.get({ key: API_KEY, userId: '+google' }, function(err, user) {
  console.log('Result: ' + (err ? err.message : user.displayName));

To learn more about API keys, please see the documentation.

Using JWT (Service Tokens)

The Google Developers Console provides .json file that you can use to configure a JWT auth client and authenticate your requests.

var key = require('path/to/key.json');
var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, [scope1, scope2], null);
jwtClient.authorize(function(err, tokens) {
  if (err) {
  // Make an authorized request to list Drive files.
  drive.files.list({ auth: jwtClient }, function(err, resp) {
    // handle err and response

The parameters for the JWT auth client including how to use it with a .pem file are explained in examples/jwt.js

Choosing the correct credential type automatically

Rather than manually creating an OAuth2 client, JWT client, or Compute client, the auth library can create the correct credential type for you, depending upon the environment your code is running under.

For example, a JWT auth client will be created when your code is running on your local developer machine, and a Compute client will be created when the same code is running on a configured instance of Google Compute Engine.

The code below shows how to retrieve a default credential type, depending upon the runtime environment. The createScopedRequired must be called to determine when you need to pass in the scopes manually, and when they have been set for you automatically based on the configured runtime environment.

google.auth.getApplicationDefault(function(err, authClient) {
  if (err) {
    res.send('Failed to get the default credentials: ' + String(err));
  // The createScopedRequired method returns true when running on GAE or a local developer
  // machine. In that case, the desired scopes must be passed in manually. When the code is
  // running in GCE or a Managed VM, the scopes are pulled from the GCE metadata server.
  // See for more information.
  if (authClient.createScopedRequired && authClient.createScopedRequired()) {
    // Scopes can be specified either as an array or as a single, space-delimited string.
    authClient = authClient.createScoped(['']);
  // Fetch the list of GCE zones within a project.
  // NOTE: You must fill in your valid project ID before running this sample!
  var projectId = 'fill in your project id here!';
  compute.zones.list({ project: projectId, auth: authClient }, function(error, result) {
    console.log(error, result);

Specifying Request Body

The body of the request is specified in the resource parameter object of the request. The resource/body is specified as a JavaScript object with key/value pairs. See the example in the next section below for an example on how it is specified.

Media Uploads

This client supports multipart media uploads. The resource parameters are specified in the resource parameter object, and the media itself is specified in the media.body parameter with mime-type specified in media.mimeType.

Example: Upload a plain text file to Google Drive with the title "Test" and contents "Hello World".

var drive ={ version: 'v2', auth: oauth2Client });
  resource: {
    title: 'Test',
    mimeType: 'text/plain'
  media: {
    mimeType: 'text/plain',
    body: 'Hello World'
}, callback);

You can also upload media by specifying media.body as a Readable stream. This can allow you to upload very large files that cannot fit into memory.

Note: Your readable stream may be unstable. Use at your own risk.

Example: Upload an image to Google Drive from a readable stream.

var fs = require('fs');
var drive ={ version: 'v2', auth: oauth2Client });
  resource: {
    title: 'testimage.png',
    mimeType: 'image/png'
  media: {
    mimeType: 'image/png',
    body: fs.createReadStream('awesome.png') // read streams are awesome!
}, callback);

For more examples of creation and modification requests with media attachments, take a look at the examples/mediaupload.js sample.

Exposing request object

Every request to the API returns a request object, allowing you to track the request's progress or general information about the request.

var req = drive.files.insert(/* ... */);
console.log(req.uri.href); // print out the request's URL.


For more fine-tuned control over how your API calls are made, we provide you with the ability to specify additional options that can be applied directly to the mikeal/request object used in this library to make network calls to the API.

You may specify additional options either in the global google object or on a service client basis.

Available options

The options you specify are attached to the request object so whatever request supports, this library supports. You may also specify global or per-service request parameters that will be attached to all API calls you make.

A full list of supported options can be found here.

Global options

Example: Specifying a default proxy and auth to be used for each request.

var google = require('googleapis');
google.options({ proxy: '', auth: auth });
// All requests made with this object will use these settings unless overridden.

Example: Specifying global request parameters.

var google = require('googleapis');
google.options({ params: { quotaUser: '' } });
// All requests from all services will contain the above query parameter
// unless overriden either in a service client or in individual API calls.

Service-client options

You can also specify options when creating a service client.

Example: Specifying a default auth option (API key or OAuth2 client)

var auth = 'API KEY'; // or you could use oauth2Client
var urlshortener = google.urlshortener({ version: 'v1', auth: auth });
// All requests made with this object will use the specified auth.

By doing this, every API call made with this service client will use 'API KEY' to authenticate.

Note: Created clients are immutable so you must create a new one if you want to specify different options.

Example: Specifying default service client query parameters

var urlshortener = google.urlshortener({
  version: 'v1',
  params: { quotaUser: '' }
// All requests made with this service client will contain the
// quotaUser query parameter unless overriden in individual API calls.
// Calls with this drive client will NOT contain the quotaUser query parameter.
var drive ='v2');

Request-level options

You can specify an auth object to be used per request. Each request also inherits the options specified at the service level and global level.


This library is licensed under Apache 2.0. Full license text is available in COPYING.



Package Sidebar


npm i googleapis-current

Weekly Downloads






Last publish


  • frank-dspeed