Gathering detailed insights and metrics for googleapis
Gathering detailed insights and metrics for googleapis
Gathering detailed insights and metrics for googleapis
Gathering detailed insights and metrics for googleapis
Google's officially supported Node.js client library for accessing Google APIs. Support for authorization and authentication with OAuth 2.0, API Keys and JWT (Service Tokens) is included.
npm install googleapis
Typescript
Module System
Min. Node Version
Node Version
NPM Version
70.2
Supply Chain
98.4
Quality
83.3
Maintenance
100
Vulnerability
99.5
License
firebasedataconnect: v0.1.0
Published on 30 Oct 2024
oracledatabase: v0.1.0
Published on 30 Oct 2024
css: v0.2.0
Published on 30 Oct 2024
airquality: v0.1.1
Published on 30 Oct 2024
merchantapi: v2.0.0
Published on 30 Oct 2024
developerconnect: v0.2.0
Published on 30 Oct 2024
Total
326,438,010
Last Day
114,934
Last Week
2,055,135
Last Month
8,607,214
Last Year
91,214,187
11,474 Stars
8,833 Commits
1,919 Forks
361 Watching
13 Branches
225 Contributors
Updated on 08 Dec 2024
Minified
Minified + Gzipped
TypeScript (99.48%)
JavaScript (0.5%)
Nunjucks (0.01%)
Cumulative downloads
Total Downloads
Last day
0%
114,934
Compared to previous day
Last week
4.7%
2,055,135
Compared to previous week
Last month
1.4%
8,607,214
Compared to previous month
Last year
23.9%
91,214,187
Compared to previous year
2
38
Node.js client library for using Google APIs. Support for authorization and authentication with OAuth 2.0, API Keys and JWT tokens is included.
The full list of supported APIs can be found on the Google APIs Explorer. 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.
When utilizing Google Cloud Platform APIs like Datastore, Cloud Storage, or Pub/Sub, it is advisable to leverage the @google-cloud client libraries. These libraries are purpose-built, idiomatic Node.js clients designed for specific Google Cloud Platform services. We recommend installing individual API packages, such as @google-cloud/storage
. To explore a comprehensive list of Google Cloud Platform API-specific packages, please refer to https://cloud.google.com/nodejs/docs/reference.
These client libraries are officially supported by Google. However, these libraries are considered complete and are in maintenance mode. This means that we will address critical bugs and security issues but will not add any new features. For Google Cloud Platform APIs, we recommend using google-cloud-node which is under active development.
This library supports the maintenance LTS, active LTS, and current release of node.js. See the node.js release schedule for more information.
This library is distributed on npm
. In order to add it as a dependency, run the following command:
1$ npm install googleapis
If you need to reduce startup times, you can alternatively install a submodule as its own dependency. We make an effort to publish submodules that are not in this list. In order to add it as a dependency, run the following sample command, replacing with your preferred API:
1$ npm install @googleapis/docs
You can run this search on npm
, to find a list of the submodules available.
This is a very simple example. This creates a Blogger client and retrieves the details of a blog given the blog Id:
1const {google} = require('googleapis'); 2 3// Each API may support multiple versions. With this sample, we're getting 4// v3 of the blogger API, and using an API key to authenticate. 5const blogger = google.blogger({ 6 version: 'v3', 7 auth: 'YOUR API KEY' 8}); 9 10const params = { 11 blogId: '3213900' 12}; 13 14// get the blog details 15blogger.blogs.get(params, (err, res) => { 16 if (err) { 17 console.error(err); 18 throw err; 19 } 20 console.log(`The blog url is ${res.data.url}`); 21});
Instead of using callbacks you can also use promises!
1blogger.blogs.get(params) 2 .then(res => { 3 console.log(`The blog url is ${res.data.url}`); 4 }) 5 .catch(error => { 6 console.error(error); 7 });
Or async/await:
1async function runSample() { 2 const res = await blogger.blogs.get(params); 3 console.log(`The blog url is ${res.data.url}`); 4} 5 6runSample().catch(console.error);
Alternatively, you can make calls directly to the APIs by installing a submodule:
1const docs = require('@googleapis/docs')
2
3const auth = new docs.auth.GoogleAuth({
4 keyFilename: 'PATH_TO_SERVICE_ACCOUNT_KEY.json',
5 // Scopes can be specified either as an array or as a single, space-delimited string.
6 scopes: ['https://www.googleapis.com/auth/documents']
7});
8const authClient = await auth.getClient();
9
10const client = await docs.docs({
11 version: 'v1',
12 auth: authClient
13});
14
15const createResponse = await client.documents.create({
16 requestBody: {
17 title: 'Your new document!',
18 },
19});
20
21console.log(createResponse.data);
There are a lot of samples 🤗 If you're trying to figure out how to use an API ... look there first! If there's a sample you need missing, feel free to file an issue.
This library has a full set of API Reference Documentation. This documentation is auto-generated, and the location may change.
There are multiple ways to authenticate to Google APIs. Some services support all authentication methods, while others may only support one or two.
OAuth2 - This allows you to make API calls on behalf of a given user. In this model, the user visits your application, signs in with their Google account, and provides your application with authorization against a set of scopes. Learn more.
API Key - With an API key, you can access your service from a client or the server. Typically less secure, this is only available on a small subset of services with limited scopes. Learn more.
Application default credentials - Provides automatic access to Google APIs using the Google Cloud SDK for local development, or the GCE Metadata Server for applications deployed to Google Cloud Platform. Learn more.
Service account credentials - In this model, your application talks directly to Google APIs using a Service Account. It's useful when you have a backend application that will talk directly to Google APIs from the backend. Learn more.
To learn more about the authentication client, see the Google Auth Library.
This module comes with an OAuth2 client that allows you to retrieve an access token, refresh it, and retry the request seamlessly. 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.
Web Application
for the application typehttp://localhost:3000/oauth2callback
(or applicable value for your scenario)Create
, and Ok
on the following screenDownload
icon next to your newly created OAuth2 Client IdMake sure to store this file in safe place, and do not check this file into source control!
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 samples/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:
1const {google} = require('googleapis'); 2 3const oauth2Client = new google.auth.OAuth2( 4 YOUR_CLIENT_ID, 5 YOUR_CLIENT_SECRET, 6 YOUR_REDIRECT_URL 7); 8 9// generate a url that asks permissions for Blogger and Google Calendar scopes 10const scopes = [ 11 'https://www.googleapis.com/auth/blogger', 12 'https://www.googleapis.com/auth/calendar' 13]; 14 15const url = oauth2Client.generateAuthUrl({ 16 // 'online' (default) or 'offline' (gets refresh_token) 17 access_type: 'offline', 18 19 // If you only need one scope, you can pass it as a string 20 scope: scopes 21});
IMPORTANT NOTE - The refresh_token
is only returned on the first authorization. More details here.
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:
1// This will provide an object with the access_token and refresh_token.
2// Save these somewhere safe so they can be used at a later time.
3const {tokens} = await oauth2Client.getToken(code)
4oauth2Client.setCredentials(tokens);
With the credentials set on your OAuth2 client - you're ready to go!
Access tokens expire. This library will automatically use a refresh token to obtain a new access token if it is about to expire. An easy way to make sure you always store the most recent tokens is to use the tokens
event:
1oauth2Client.on('tokens', (tokens) => { 2 if (tokens.refresh_token) { 3 // store the refresh_token in my database! 4 console.log(tokens.refresh_token); 5 } 6 console.log(tokens.access_token); 7});
This tokens event only occurs in the first authorization, and you need to have set your access_type
to offline
when calling the generateAuthUrl
method to receive the refresh token. If you have already given your app the requisite permissions without setting the appropriate constraints for receiving a refresh token, you will need to re-authorize the application to receive a fresh refresh token. You can revoke your app's access to your account here.
To set the refresh_token
at a later time, you can use the setCredentials
method:
1oauth2Client.setCredentials({ 2 refresh_token: `STORED_REFRESH_TOKEN` 3});
Once the client has a refresh token, access tokens will be acquired and refreshed automatically in the next call to the API.
Refresh tokens may stop working after they are granted, either because:
As a developer, you should write your code to handle the case where a refresh token is no longer working.
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 Blogger API service to retrieve a blog's name, url, and its total amount of posts:
1const {google} = require('googleapis'); 2const blogger = google.blogger_v3({ 3 version: 'v3', 4 auth: 'YOUR_API_KEY' // specify your API key here 5}); 6 7const params = { 8 blogId: '3213900' 9}; 10 11async function main(params) { 12 const res = await blogger.blogs.get({blogId: params.blogId}); 13 console.log(`${res.data.name} has ${res.data.posts.totalItems} posts! The blog url is ${res.data.url}`) 14}; 15 16main().catch(console.error);
To learn more about API keys, please see the documentation.
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.
To use Application default credentials locally with the Google Cloud SDK, run:
1$ gcloud auth application-default login
When running in GCP, service authorize is automatically provided via the GCE Metadata server.
1const {google} = require('googleapis');
2const compute = google.compute('v1');
3
4async function main () {
5 const auth = new google.auth.GoogleAuth({
6 // Scopes can be specified either as an array or as a single, space-delimited string.
7 scopes: ['https://www.googleapis.com/auth/compute']
8 });
9 const authClient = await auth.getClient();
10
11 // obtain the current project Id
12 const project = await auth.getProjectId();
13
14 // Fetch the list of GCE zones within a project.
15 const res = await compute.zones.list({ project, auth: authClient });
16 console.log(res.data);
17}
18
19main().catch(console.error);
Service accounts allow you to perform server-to-server, app-level authentication using a robot account. You will create a service account, download a keyfile, and use that to authenticate to Google APIs. To create a service account:
New Service Account
in the drop downCreate
buttonSave the service account credential file somewhere safe, and do not check this file into source control! To reference the service account credential file, you have a few options.
GOOGLE_APPLICATION_CREDENTIALS
env varYou can start process with an environment variable named GOOGLE_APPLICATION_CREDENTIALS
. The value of this env var should be the full path to the service account credential file:
1$ GOOGLE_APPLICATION_CREDENTIALS=./your-secret-key.json node server.js
keyFile
propertyAlternatively, you can specify the path to the service account credential file via the keyFile
property in the GoogleAuth
constructor:
1const {google} = require('googleapis');
2
3const auth = new google.auth.GoogleAuth({
4 keyFile: '/path/to/your-secret-key.json',
5 scopes: ['https://www.googleapis.com/auth/cloud-platform'],
6});
You can set the auth
as a global or service-level option so you don't need to specify it every request. For example, you can set auth
as a global option:
1const {google} = require('googleapis'); 2 3const oauth2Client = new google.auth.OAuth2( 4 YOUR_CLIENT_ID, 5 YOUR_CLIENT_SECRET, 6 YOUR_REDIRECT_URL 7); 8 9// set auth as a global default 10google.options({ 11 auth: oauth2Client 12});
Instead of setting the option globally, you can also set the authentication client at the service-level:
1const {google} = require('googleapis'); 2const oauth2Client = new google.auth.OAuth2( 3 YOUR_CLIENT_ID, 4 YOUR_CLIENT_SECRET, 5 YOUR_REDIRECT_URL 6); 7 8const drive = google.drive({ 9 version: 'v2', 10 auth: oauth2Client 11});
See the Options section for more information.
The body of the request is specified in the requestBody
parameter object of the request. The body is specified as a JavaScript object with key/value pairs. For example, this sample creates a watcher that posts notifications to a Google Cloud Pub/Sub topic when emails are sent to a gmail account:
1const res = await gmail.users.watch({ 2 userId: 'me', 3 requestBody: { 4 // Replace with `projects/${PROJECT_ID}/topics/${TOPIC_NAME}` 5 topicName: `projects/el-gato/topics/gmail` 6 } 7}); 8console.log(res.data);
This client supports multipart media uploads. The resource parameters are specified in the requestBody
parameter object, and the media itself is specified in the media.body
parameter with mime-type specified in media.mimeType
.
This example uploads a plain text file to Google Drive with the title "Test" and contents "Hello World".
1const drive = google.drive({ 2 version: 'v3', 3 auth: oauth2Client 4}); 5 6const res = await drive.files.create({ 7 requestBody: { 8 name: 'Test', 9 mimeType: 'text/plain' 10 }, 11 media: { 12 mimeType: 'text/plain', 13 body: 'Hello World' 14 } 15});
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.
1const fs = require('fs'); 2 3const drive = google.drive({ 4 version: 'v3', 5 auth: oauth2Client 6}); 7 8async function main() { 9 const res = await drive.files.create({ 10 requestBody: { 11 name: 'testimage.png', 12 mimeType: 'image/png' 13 }, 14 media: { 15 mimeType: 'image/png', 16 body: fs.createReadStream('awesome.png') 17 } 18 }); 19 console.log(res.data); 20} 21 22main().catch(console.error);
For more examples of creation and modification requests with media attachments, take a look at the samples/drive/upload.js
sample.
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 'gaxios' 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 gaxios
object so whatever gaxios
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.
You can choose default options that will be sent with each request. These options will be used for every service instantiated by the google client. In this example, the timeout
property of GaxiosOptions
will be set for every request:
1const {google} = require('googleapis'); 2google.options({ 3 // All requests made with this object will use these settings unless overridden. 4 timeout: 1000, 5 auth: auth 6});
You can also modify the parameters sent with each request:
1const {google} = require('googleapis'); 2google.options({ 3 // All requests from all services will contain the above query parameter 4 // unless overridden either in a service client or in individual API calls. 5 params: { 6 quotaUser: 'user123@example.com' 7 } 8});
You can also specify options when creating a service client.
1const blogger = google.blogger({ 2 version: 'v3', 3 // All requests made with this object will use the specified auth. 4 auth: 'API KEY'; 5});
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.
Similar to the examples above, you can also modify the parameters used for every call of a given service:
1const blogger = google.blogger({ 2 version: 'v3', 3 // All requests made with this service client will contain the 4 // blogId query parameter unless overridden in individual API calls. 5 params: { 6 blogId: '3213900' 7 } 8}); 9 10// Calls with this drive client will NOT contain the blogId query parameter. 11const drive = google.drive('v3'); 12... 13
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.
For example:
1const {google} = require('googleapis'); 2const bigquery = google.bigquery('v2'); 3 4async function main() { 5 6 // This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS 7 // environment variables. 8 const auth = new google.auth.GoogleAuth({ 9 scopes: ['https://www.googleapis.com/auth/cloud-platform'] 10 }); 11 const authClient = await auth.getClient(); 12 13 const projectId = await auth.getProjectId(); 14 15 const request = { 16 projectId, 17 datasetId: '<YOUR_DATASET_ID>', 18 19 // This is a "request-level" option 20 auth: authClient 21 }; 22 23 const res = await bigquery.datasets.delete(request); 24 console.log(res.data); 25 26} 27 28main().catch(console.error);
You can also override gaxios options per request, such as url
, method
, and responseType
.
For example:
1const res = await drive.files.export({ 2 fileId: 'asxKJod9s79', // A Google Doc 3 mimeType: 'application/pdf' 4}, { 5 // Make sure we get the binary data 6 responseType: 'stream' 7});
You can use the following environment variables to proxy HTTP and HTTPS requests:
HTTP_PROXY
/ http_proxy
HTTPS_PROXY
/ https_proxy
When HTTP_PROXY / http_proxy are set, they will be used to proxy non-SSL requests that do not have an explicit proxy configuration option present. Similarly, HTTPS_PROXY / https_proxy will be respected for SSL requests that do not have an explicit proxy configuration option. It is valid to define a proxy in one of the environment variables, but then override it for a specific request, using the proxy configuration option.
You can programmatically obtain the list of supported APIs, and all available versions:
1const {google} = require('googleapis'); 2const apis = google.getSupportedAPIs();
This will return an object with the API name as object property names, and an array of version strings as the object values;
This library is written in TypeScript, and provides types out of the box. All classes and interfaces generated for each API are exported under the ${apiName}_${version}
namespace. For example, the Drive v3 API types are all available from the drive_v3
namespace:
1import { 2 google, // The top level object used to access services 3 drive_v3, // For every service client, there is an exported namespace 4 Auth, // Namespace for auth related types 5 Common, // General types used throughout the library 6} from 'googleapis'; 7 8// Note: using explicit types like `Auth.GoogleAuth` are only here for 9// demonstration purposes. Generally with TypeScript, these types would 10// be inferred. 11const auth: Auth.GoogleAuth = new google.auth.GoogleAuth(); 12const drive: drive_v3.Drive = google.drive({ 13 version: 'v3', 14 auth, 15}); 16 17// There are generated types for every set of request parameters 18const listParams: drive_v3.Params$Resource$Files$List = {}; 19const res = await drive.files.list(listParams); 20 21// There are generated types for the response fields as well 22const listResults: drive_v3.Schema$FileList = res.data;
This library has support for HTTP/2. To enable it, use the http2
option anywhere request parameters are accepted:
1const {google} = require('googleapis'); 2google.options({ 3 http2: true, 4});
HTTP/2 is often more performant, as it allows multiplexing of multiple concurrent requests over a single socket. In a traditional HTTP/2 API, the client is directly responsible for opening and closing the sessions made to make requests. To maintain compatibility with the existing API, this module will automatically re-use existing sessions, which are collected after idling for 500ms. Much of the performance gains will be visible in batch style workloads, and tight loops.
You can find a detailed list of breaking changes and new features in our Release Notes. If you've used this library before 25.x
, see our Release Notes to learn about migrating your code from 24.x.x
to 25.x.x
. It's pretty easy :)
This library is licensed under Apache 2.0. Full license text is available in LICENSE.
We love contributions! Before submitting a Pull Request, it's always good to start with a new issue first. To learn more, see CONTRIBUTING.
Stable Version
1
0/10
Summary
Improper Authorization in googleapis
Affected Versions
< 39.1.0
Patched Versions
39.1.0
Reason
30 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
all changesets reviewed
Reason
security policy file detected
Details
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
no binaries found in the repo
Reason
SAST tool is not run on all commits -- score normalized to 2
Details
Reason
dependency not pinned by hash detected -- score normalized to 1
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Score
Last Scanned on 2024-12-02
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More