Socket
Socket
Sign inDemoInstall

googleapis

Package Overview
Dependencies
118
Maintainers
1
Versions
254
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    googleapis

Google APIs Client Library for Node.js


Version published
Maintainers
1
Install size
4.62 MB
Created

Package description

What is googleapis?

The googleapis npm package is a client library for accessing various Google APIs. It provides an easy way to integrate Google services into applications, allowing developers to interact with a wide range of Google services, including Google Drive, Gmail, Google Calendar, YouTube, and many more.

What are googleapis's main functionalities?

Google Drive API

This code sample demonstrates how to list files in a user's Google Drive using the Google Drive API.

const { google } = require('googleapis');
const drive = google.drive({ version: 'v3', auth });
// List files in Google Drive
drive.files.list({}, (err, res) => {
  if (err) throw err;
  const files = res.data.files;
  if (files.length) {
    console.log('Files:');
    files.map((file) => {
      console.log(`${file.name} (${file.id})`);
    });
  } else {
    console.log('No files found.');
  }
});

Gmail API

This code sample shows how to send an email using the Gmail API.

const { google } = require('googleapis');
const gmail = google.gmail({ version: 'v1', auth });
// Send an email using the Gmail API
gmail.users.messages.send({
  userId: 'me',
  requestBody: {
    raw: emailMessage
  }
}, (err, res) => {
  if (err) throw err;
  console.log('Email sent:', res.data);
});

Google Calendar API

This code sample illustrates how to create a new event in a user's Google Calendar.

const { google } = require('googleapis');
const calendar = google.calendar({ version: 'v3', auth });
// Insert a new calendar event
calendar.events.insert({
  calendarId: 'primary',
  resource: event,
}, (err, event) => {
  if (err) throw err;
  console.log('Event created: %s', event.htmlLink);
});

YouTube API

This code sample demonstrates how to search for videos on YouTube using the YouTube API.

const { google } = require('googleapis');
const youtube = google.youtube({ version: 'v3', auth });
// Search for videos on YouTube
youtube.search.list({
  part: 'snippet',
  q: 'Node.js on Google Cloud',
  maxResults: 10
}, (err, response) => {
  if (err) throw err;
  const videos = response.data.items;
  if (videos.length) {
    console.log('Search results:');
    videos.forEach((video) => {
      console.log(`${video.snippet.title}`);
    });
  } else {
    console.log('No search results found.');
  }
});

Other packages similar to googleapis

Changelog

Source

132.0.0 (2024-02-02)

⚠ BREAKING CHANGES

  • vmwareengine: This release has breaking changes.
  • storage: This release has breaking changes.
  • script: This release has breaking changes.
  • sasportal: This release has breaking changes.
  • prod_tt_sasportal: This release has breaking changes.
  • discoveryengine: This release has breaking changes.
  • dataflow: This release has breaking changes.
  • compute: This release has breaking changes.
  • blockchainnodeengine: This release has breaking changes.
  • bigtableadmin: This release has breaking changes.
  • bigquery: This release has breaking changes.
  • alloydb: This release has breaking changes.
  • aiplatform: This release has breaking changes.

Features

  • aiplatform: update the API (cba6496)
  • alertcenter: update the API (4149165)
  • alloydb: update the API (46e2226)
  • analyticsadmin: update the API (88bd2db)
  • androidmanagement: update the API (80c827b)
  • androidpublisher: update the API (990f7dc)
  • apphub: update the API (93e48d3)
  • artifactregistry: update the API (19c744c)
  • batch: update the API (afcbf80)
  • bigquery: update the API (489bf2f)
  • bigtableadmin: update the API (05611d8)
  • blockchainnodeengine: update the API (ec5ff13)
  • calendar: update the API (70b4f02)
  • chat: update the API (9025eed)
  • chromepolicy: update the API (57109aa)
  • cloudasset: update the API (c1e4ab0)
  • clouddeploy: update the API (862139c)
  • cloudfunctions: update the API (608ff76)
  • cloudidentity: update the API (1217ce4)
  • cloudsupport: update the API (663b770)
  • composer: update the API (e4d1687)
  • compute: update the API (014e200)
  • connectors: update the API (102625b)
  • contactcenteraiplatform: update the API (076984f)
  • contactcenterinsights: update the API (c4aa133)
  • container: update the API (ac3a11c)
  • dataflow: update the API (83ba2b6)
  • dataform: update the API (ba04837)
  • datastore: update the API (8287f11)
  • datastream: update the API (a5d1c9c)
  • dialogflow: update the API (e8db16f)
  • discoveryengine: update the API (ce0ec76)
  • displayvideo: update the API (d50a81a)
  • dlp: update the API (c32baf0)
  • documentai: update the API (24d2893)
  • drive: update the API (3862e92)
  • firebaseappcheck: update the API (34aea86)
  • firestore: update the API (ccbb1f0)
  • gkehub: update the API (c7e634b)
  • healthcare: update the API (f968248)
  • logging: update the API (ce04723)
  • migrationcenter: update the API (d374bff)
  • networkmanagement: update the API (48d5fd8)
  • notebooks: update the API (f0fd05d)
  • paymentsresellersubscription: update the API (78e1410)
  • policysimulator: update the API (499a27d)
  • prod_tt_sasportal: update the API (869d102)
  • pubsub: update the API (a84da31)
  • recaptchaenterprise: update the API (abe83f6)
  • recommender: update the API (0879e9a)
  • regenerate index files (d69ca14)
  • retail: update the API (a681493)
  • sasportal: update the API (c979d58)
  • script: update the API (1c78889)
  • secretmanager: update the API (74282ab)
  • securitycenter: update the API (1f28c20)
  • spanner: update the API (7c371a3)
  • speech: update the API (d77180a)
  • sqladmin: update the API (a80b25a)
  • storagetransfer: update the API (43173f6)
  • storage: update the API (5bc62e5)
  • texttospeech: update the API (1464272)
  • tpu: update the API (02ec90d)
  • vmwareengine: update the API (8f0ad46)
  • walletobjects: update the API (47a7c9a)
  • workflowexecutions: update the API (22dabc5)
  • workloadmanager: update the API (a399523)
  • workstations: update the API (5d55518)
  • youtube: update the API (dc515e2)

Bug Fixes

  • accesscontextmanager: update the API (aa12f37)
  • analyticsdata: update the API (5847c48)
  • analyticshub: update the API (7df077f)
  • apigateway: update the API (6bb703f)
  • beyondcorp: update the API (4cd4b2c)
  • bigqueryconnection: update the API (9a7ce77)
  • bigquerydatapolicy: update the API (7b84678)
  • binaryauthorization: update the API (e242588)
  • cloudbilling: update the API (576eded)
  • cloudbuild: update the API (7c89f36)
  • cloudchannel: update the API (6dbfcbe)
  • cloudprofiler: update the API (effed14)
  • cloudresourcemanager: update the API (c2fba36)
  • cloudtasks: update the API (4099041)
  • containeranalysis: update the API (478d5c9)
  • content: update the API (6715e9e)
  • datacatalog: update the API (6f7a6cc)
  • datafusion: update the API (5d11c89)
  • datamigration: update the API (d4a6afd)
  • dataplex: update the API (2ed8677)
  • dataportability: update the API (f7f9bae)
  • dataproc: update the API (d983519)
  • deploymentmanager: update the API (3a175ff)
  • dns: update the API (fde40df)
  • domains: update the API (3ab647b)
  • doubleclicksearch: update the API (22efec1)
  • eventarc: update the API (da2e5a6)
  • gkebackup: update the API (55025a0)
  • iam: update the API (c67391f)
  • iap: update the API (8bcea17)
  • identitytoolkit: update the API (9b113bd)
  • looker: update the API (f9609d8)
  • managedidentities: update the API (8136966)
  • memcache: update the API (7c5efc3)
  • metastore: update the API (b720258)
  • ml: update the API (5fb7d7c)
  • networkconnectivity: update the API (9cc489f)
  • networksecurity: update the API (d16ebd1)
  • networkservices: update the API (e97d268)
  • osconfig: update the API (aaaf733)
  • places: update the API (14129bb)
  • policytroubleshooter: update the API (820160f)
  • privateca: update the API (5b06ea2)
  • redis: update the API (1b34fef)
  • run: update the API (d6e4c9e)
  • servicedirectory: update the API (f3bec00)
  • servicemanagement: update the API (01229e3)
  • sourcerepo: update the API (3dad20b)
  • sts: update the API (b0d4b75)
  • translate: update the API (dd89550)
  • vmmigration: update the API (5ae80ff)
  • workflows: update the API (57e6cd8)
  • workspaceevents: update the API (ef0420c)

Readme

Source

Google APIs NodeJS Client Build Status

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

Migrating to version 1.0.0 of this library

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

Questions/problems?

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

Installation

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

$ npm install googleapis

Usage

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: 'http://goo.gl/xKbRu3' };

// get the long url of a shortened url
urlshortener.url.get(params, function (err, response) {
  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 = [
  'https://www.googleapis.com/auth/plus.me',
  'https://www.googleapis.com/auth/calendar'
];

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) {
    oauth2Client.setCredentials(tokens);
  }
});
Settings 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 = google.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, 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 google = require('googleapis');
var plus = google.plus('v1');
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

// Retrieve tokens via token exchange explained above or set them:
oauth2Client.setCredentials({
  access_token: 'ACCESS TOKEN HERE',
  refresh_token: 'REFRESH TOKEN HERE'
});

plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) {
  // handle err and response
});
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 = google.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.

Media Uploads

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

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

var drive = google.drive({ version: 'v2', auth: oauth2Client });

drive.files.insert({
  resource: {
    title: 'Test',
    mimeType: 'text/plain'
  },
  media: 'Hello World'
}, callback);

You can also upload media by specifying media 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 = google.drive({ version: 'v2', auth: oauth2Client });

drive.files.insert({
  resource: {
    title: 'testimage.png',
    mimeType: 'image/png'
  },
  media: 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.

Options

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.

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: 'http://proxy.example.com', auth: auth });

// all requests made with this object will use these settings unless overridden

Service-client options

You can also specify options when creating a service client. For example, to specify a default auth option (API key or OAuth2 client), simply pass it in like so:

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.

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.

License

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

Contributing

See CONTRIBUTING.

Keywords

FAQs

Last updated on 22 Jul 2014

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc