npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

googleapis-plus

v0.8.3

Published

Google APIs Client Library for Node.js

Downloads

97

Readme

google-api-nodejs-client [alpha]

Build Status

google-api-nodejs-client is Google's officially supported node.js client library for accessing Google APIs, it also supports authorization and authentication with OAuth 2.0.

Questions/problems?

  • Ask your development related questions on Ask a question on Stackoverflow
  • If you found a bug, please file a bug.

Note: This library is currently in alpha status, meaning that we can make changes in the future that may not be compatible with the previous versions.

Installation

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

$ npm install googleapis

Guide

Discover APIs

Dynamically load Google APIs and start making requests:

var googleapis = require('googleapis');

googleapis
    .discover('urlshortener', 'v1')
    .discover('plus', 'v1')
    .execute(function(err, client) {
  if (err) {
    console.log('Problem during the client discovery.', err);
    return;
  }
  var params = { shortUrl: 'http://goo.gl/DdUKX' };
  var getUrlReq = client.urlshortener.url.get(params);

  getUrlReq.execute(function (err, response) {
    console.log('Long url is', response.longUrl);
  });

  var getUserReq = client.plus.people.get({ userId: '+burcudogan' });

  getUserReq.execute(function(err, user) {
    console.log('User id is: ' + user.id);
  });
});

Supported APIs are listed on Google APIs Explorer.

Discovery Document Caching

Discovery documents are being cached for 5 minutes locally. You can configure the directory used to store cached discovery files by using the cache.path option.

googleapis
    .discover('plus', 'v3')
    .withOpts({ cache: { path: '<path>' }))
    .execute();

Authorization and Authentication

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

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

Consent Page Url

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

var googleapis = require('googleapis'),
    OAuth2 = googleapis.auth.OAuth2;

var oauth2Client =
    new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

// generates a url that allows offline access and asks permissions
// for Google+ scope.
var scopes = [
  'https://www.googleapis.com/auth/plus.me',
  'https://www.googleapis.com/auth/calendar'
];

var url = oauth2Client.generateAuthUrl({
  access_type: 'offline',
  scope: scopes.join(" ") // space delimited string of scopes
});

Retrieving Tokens

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}

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

oauth2Client.getToken(code, function(err, tokens) {
  // contains an access_token and optionally a refresh_token.
  // save them permanently.
});

API Client

Client libraries are generated during runtime by metadata provided by Google APIs Discovery Service. Metadata provided by Discovery Service is cached, and won't be requested each time you load a client. Below, there is an example of loading a client for URL Shortener API.

googleapis
    .discover('urlshortener', 'v1')
    .execute(function(err, client) {
  // handle discovery errors
  // make requests
});

Requests

The following sample loads a client for URL Shortener and retrieves the long url of the given short url:

googleapis
    .discover('urlshortener', 'v1')
    .execute(function(err, client) {
  // handle discovery errors
  client.urlshortener.url.get({ shortUrl: 'http://goo.gl/DdUKX' })
      .execute(function(err, result) {
    // result.longUrl contains the long url.
  });
});

Alternatively, you may need to send an API key with the request you are going to make. The following creates and executes a request from the Google+ API service to retrieve a person profile given a userId:

googleapis
    .discover('plus', 'v1')
    .execute(function(err, client) {
  // handle discovery errors
  var getUserAuthdReq = client.plus.people.get({ userId: '+burcudogan' })
      .withApiKey(API_KEY);

  getUserAuthdReq.execute(function(err, user) {
    console.log("Result: " + (err ? err.message : user.displayName));
  });
});

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

Making Authenticated Requests

And you can start using oauth2Client to authorize and authenticate your requests to Google APIs with the retrieved tokens. If you provide a refresh_token, the access_token is automatically refreshed and the request is replayed in case the access_token has expired.

Following sample retrieves Google+ profile of the authenticated user.

var oauth2Client =
    new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

// Retrieve tokens via token exchange explaind above.
// Or you can set them.
oauth2Client.credentials = {
  access_token: 'ACCESS TOKEN HERE',
  refresh_token: 'REFRESH TOKEN HERE'
};

client
    .plus.people.get({ userId: 'me' })
    .withAuthClient(oauth2Client)
    .execute(callback);

Batch requests (experimental)

You can combine multiple requests in a single one by using batch requests.

var getUserReq =
    client.plus.people.get({ userId: '+BurcuDogan' });

var insertUrlReq =
    client.urlshortener.url.insert({ longUrl: 'http://google.com' });

client
    .newBatchRequest()
    .add(getUserReq)
    .add(insertUrlReq)
    .execute(function(err, results) {
  // handle results
});

Media Uploads

Client supports basic and multipart media uploads. For creation and modification requests with media attachments, take a look at the examples/mediaupload.js sample.

client
    .drive.files.insert({ title: 'Test', mimeType: 'text/plain' })
    .withMedia('text/plain', 'Hello World')
    .execute();

License

google-api-nodejs-client is licensed with Apache 2.0. Full license text is available on COPYING file.

Contributing

See CONTRIBUTING.