Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
googleapis
Advanced tools
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.
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.');
}
});
The aws-sdk package is a client library for Amazon Web Services (AWS). It allows developers to interact with a wide range of AWS services such as Amazon S3, EC2, DynamoDB, and more. While it serves a similar purpose for AWS as googleapis does for Google services, the two are for different ecosystems.
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.
1.0
of this libraryIf you've used this library before 1.0
, see our Migration Guide
to learn about migrating your code from 0.x.x
to 1.0
. It's pretty easy :)
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: '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);
});
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.
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
.
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
});
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) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if(!err) {
oauth2Client.setCredentials(tokens);
}
});
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.
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 = 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
});
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)
});
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.
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 = google.drive({ version: 'v2', auth: oauth2Client });
drive.files.insert({
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 = google.drive({ version: 'v2', auth: oauth2Client });
drive.files.insert({
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.
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.
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.
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
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.
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.
See CONTRIBUTING.
FAQs
Google APIs Client Library for Node.js
The npm package googleapis receives a total of 1,852,037 weekly downloads. As such, googleapis popularity was classified as popular.
We found that googleapis demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
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.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.