### People API Methods Source: https://context7.com/google/google-api-javascript-client/llms.txt Example demonstrating how to initialize the client with discovery documents and then call methods for the People API, such as getting a user's profile and listing connections. ```APIDOC ## People API Methods ### Description This example shows how to initialize the Google API client with the discovery document for the People API and then make calls to retrieve user profile information and their connections. ### Method `gapi.client.init` for initialization, `gapi.client.people.people.get` for user profile, `gapi.client.people.people.connections.list` for connections. ### Endpoint N/A (methods are dynamically generated) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript // People API methods after loading discovery document gapi.client.init({ apiKey: 'YOUR_API_KEY', discoveryDocs: ['https://people.googleapis.com/$discovery/rest?version=v1'] }).then(function() { // Get authenticated user's profile return gapi.client.people.people.get({ resourceName: 'people/me', personFields: 'names,emailAddresses,phoneNumbers,photos' }); }).then(function(response) { var person = response.result; console.log('Name:', person.names[0].displayName); console.log('Email:', person.emailAddresses[0].value); console.log('Photo:', person.photos[0].url); // Get user's connections return gapi.client.people.people.connections.list({ resourceName: 'people/me', pageSize: 100, personFields: 'names,emailAddresses' }); }).then(function(response) { console.log('Found ' + response.result.totalPeople + ' connections'); response.result.connections.forEach(function(connection) { if (connection.names && connection.names.length > 0) { console.log('Connection:', connection.names[0].displayName); } }); }); ``` ### Response #### Success Response (200) - **person** (object) - The user's profile information. - **connections** (array) - A list of the user's connections. #### Response Example ```json { "names": [{"displayName": "John Doe", ...}], "emailAddresses": [{"value": "john.doe@example.com", ...}], "photos": [{"url": "http://example.com/photo.jpg", ...}] } ``` ``` -------------------------------- ### Install Compass - Gem Installation Source: https://github.com/google/google-api-javascript-client/blob/master/samples/io-2012/slides/README.html Instructions for installing the Compass gem, a CSS preprocessor used for managing SCSS/SASS. This is a prerequisite for compiling SCSS files into CSS. ```shell sudo gem update --system sudo gem install compass ``` -------------------------------- ### Initialize Google API Client and Use People, Drive, Calendar APIs (JavaScript) Source: https://context7.com/google/google-api-javascript-client/llms.txt Demonstrates initializing the Google API client with a discovery document for the People API, then loading discovery documents for Drive and Calendar APIs. It shows examples of listing files in Drive and events in Calendar, along with fetching user profiles and connections from the People API. This snippet requires API keys and proper authentication setup. ```javascript gapi.client.init({ apiKey: 'YOUR_API_KEY', discoveryDocs: ['https://people.googleapis.com/$discovery/rest?version=v1'] }).then(function() { // Get authenticated user's profile return gapi.client.people.people.get({ resourceName: 'people/me', personFields: 'names,emailAddresses,phoneNumbers,photos' }); }).then(function(response) { var person = response.result; console.log('Name:', person.names[0].displayName); console.log('Email:', person.emailAddresses[0].value); console.log('Photo:', person.photos[0].url); // Get user's connections return gapi.client.people.people.connections.list({ resourceName: 'people/me', pageSize: 100, personFields: 'names,emailAddresses' }); }).then(function(response) { console.log('Found ' + response.result.totalPeople + ' connections'); response.result.connections.forEach(function(connection) { if (connection.names && connection.names.length > 0) { console.log('Connection:', connection.names[0].displayName); } }); }); // Drive API methods gapi.client.load('https://www.googleapis.com/discovery/v1/apis/drive/v3/rest') .then(function() { // List files return gapi.client.drive.files.list({ pageSize: 20, fields: 'nextPageToken, files(id, name, mimeType, modifiedTime, size)', q: "mimeType='application/pdf'", orderBy: 'modifiedTime desc' }); }).then(function(response) { console.log('PDF files:', response.result.files); // Get specific file metadata var fileId = response.result.files[0].id; return gapi.client.drive.files.get({ fileId: fileId, fields: 'id, name, description, webViewLink, owners' }); }).then(function(response) { console.log('File details:', response.result); console.log('View link:', response.result.webViewLink); console.log('Owner:', response.result.owners[0].displayName); }); // Calendar API methods gapi.client.load('https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest') .then(function() { // List calendars return gapi.client.calendar.calendarList.list({ maxResults: 10 }); }).then(function(response) { console.log('Calendars:', response.result.items); // Get events from primary calendar return gapi.client.calendar.events.list({ calendarId: 'primary', timeMin: new Date().toISOString(), maxResults: 10, singleEvents: true, orderBy: 'startTime' }); }).then(function(response) { console.log('Upcoming events:', response.result.items); }); ``` -------------------------------- ### Option 1: Load Discovery Document and Assemble Request Source: https://github.com/google/google-api-javascript-client/blob/master/docs/start.md This method demonstrates how to load the API discovery document and then assemble an API request. It requires user sign-in for authorized requests. ```APIDOC ## GET /discovery/rest ### Description This example shows how to initialize the JavaScript client library by loading an API discovery document and then making an authorized API request. It assumes the user has already signed in. ### Method GET (Implicit via client library) ### Endpoint https://people.googleapis.com/$discovery/rest ### Parameters #### Path Parameters None #### Query Parameters - **resourceName** (string) - Required - The name of the resource to retrieve. Example: 'people/me' - **requestMask.includeField** (string) - Required - Specifies which fields to include in the response. Example: 'person.names' #### Request Body None ### Request Example ```html ``` ### Response #### Success Response (200) - **result** (object) - The response from the People API, containing requested person fields. #### Response Example ```json { "result": { "names": [ { "metadata": { "source": { "type": "CONTACT", "id": "..." } }, "displayName": "Your Name", "familyName": "Your Family Name", "givenName": "Your Given Name" } ] } } ``` ``` -------------------------------- ### Option 2: Use gapi.client.request Source: https://github.com/google/google-api-javascript-client/blob/master/docs/start.md This method provides a more general way to make API requests using `gapi.client.request`. It does not require loading the Discovery Document but requires manual filling of REST parameters. ```APIDOC ## POST /discovery/rest ### Description This example demonstrates making a general API request using `gapi.client.request`. This method is more flexible as it does not require loading a Discovery Document, but requires manual specification of the path and parameters. ### Method POST (Implicit via client library) ### Endpoint https://people.googleapis.com/v1/people/me?requestMask.includeField=person.names ### Parameters #### Path Parameters None #### Query Parameters - **requestMask.includeField** (string) - Required - Specifies which fields to include in the response. Example: 'person.names' #### Request Body None ### Request Example ```html ``` ### Response #### Success Response (200) - **result** (object) - The response from the People API, containing requested person fields. #### Response Example ```json { "result": { "names": [ { "metadata": { "source": { "type": "CONTACT", "id": "..." } }, "displayName": "Your Name", "familyName": "Your Family Name", "givenName": "Your Given Name" } ] } } ``` ``` -------------------------------- ### Drive API Methods Source: https://context7.com/google/google-api-javascript-client/llms.txt This example demonstrates loading the discovery document for the Drive API and then performing operations like listing PDF files and getting the metadata of a specific file. ```APIDOC ## Drive API Methods ### Description This example shows how to load the discovery document for the Drive API and then use its methods to list files (specifically PDFs) and retrieve the details of a particular file. ### Method `gapi.client.load` to load discovery document, `gapi.client.drive.files.list` to list files, `gapi.client.drive.files.get` to get file metadata. ### Endpoint N/A (methods are dynamically generated) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript // Drive API methods gapi.client.load('https://www.googleapis.com/discovery/v1/apis/drive/v3/rest') .then(function() { // List files return gapi.client.drive.files.list({ pageSize: 20, fields: 'nextPageToken, files(id, name, mimeType, modifiedTime, size)', q: "mimeType='application/pdf'", orderBy: 'modifiedTime desc' }); }).then(function(response) { console.log('PDF files:', response.result.files); // Get specific file metadata var fileId = response.result.files[0].id; return gapi.client.drive.files.get({ fileId: fileId, fields: 'id, name, description, webViewLink, owners' }); }).then(function(response) { console.log('File details:', response.result); console.log('View link:', response.result.webViewLink); console.log('Owner:', response.result.owners[0].displayName); }); ``` ### Response #### Success Response (200) - **files** (array) - A list of files matching the query. - **nextPageToken** (string) - Token for the next page of results. - **id** (string) - The ID of the file. - **name** (string) - The name of the file. - **mimeType** (string) - The MIME type of the file. - **modifiedTime** (string) - The last modified time of the file. - **size** (string) - The size of the file. - **description** (string) - The description of the file. - **webViewLink** (string) - The web view link for the file. - **owners** (array) - The owners of the file. #### Response Example ```json { "files": [ { "id": "1a2b3c4d5e", "name": "document.pdf", "mimeType": "application/pdf", "modifiedTime": "2023-10-27T10:00:00.000Z", "size": "102400" } ], "nextPageToken": "nextToken" } ``` ``` -------------------------------- ### Initialize and Request Google People API using gapi.client.request (JavaScript) Source: https://github.com/google/google-api-javascript-client/blob/master/docs/start.md This snippet shows how to initialize the Google API JavaScript client and then make a request using the generic `gapi.client.request` method. It bypasses the need to load a specific discovery document, instead constructing the request path and parameters manually. This approach is useful for saving a network request and reducing application size when the full discovery document is not necessary. ```javascript ``` -------------------------------- ### Install and Watch Compass for SCSS Changes Source: https://github.com/google/google-api-javascript-client/blob/master/samples/io-2012/slides/README.md This snippet shows how to install Compass, a CSS preprocessor, and then use the `compass watch` command to automatically recompile SCSS files into CSS when changes are detected. This is useful for managing and updating the project's styling. ```bash sudo gem update --system sudo gem install compass cd io-2012-slides compass watch ``` ```bash compass watch -s expanded ``` -------------------------------- ### Initialize and Request Google People API using Discovery Doc (JavaScript) Source: https://github.com/google/google-api-javascript-client/blob/master/docs/start.md This snippet demonstrates initializing the Google API JavaScript client with an API key and discovery document for the People API. It then makes a request to retrieve specific fields for the authenticated user's profile and logs the response or any errors. This method relies on the API's discovery document to define available methods and parameters. ```javascript ``` -------------------------------- ### JSON-RPC Request Example Source: https://github.com/google/google-api-javascript-client/blob/master/samples/io-2012/slides/jsclient.html Illustrates how to make an API call using the JSON-RPC format with the Google APIs JavaScript Client. ```APIDOC ## JSON-RPC Request ### Description This section demonstrates how to use the JSON-RPC request format for making API calls. The request is sent as a JSON object in the POST body, and the response is also in JSON format. ### Method POST ### Endpoint This is handled internally by the `gapi.client.urlshortener.url.get` method, which abstracts the JSON-RPC communication. ### Parameters #### Request Body (implicit in method call) - The parameters for the API call are passed as an object to the specific `gapi.client` method. ### Request Example ```javascript var rpcRequest = gapi.client.urlshortener.url.get({ 'shortUrl': 'http://goo.gl/fbsS' }); rpcRequest.execute(function(jsonResponse, rawResponse) { // Handle request result console.log(jsonResponse); }); ``` ### Response #### Success Response - The structure of the success response depends on the specific API endpoint being called. #### Response Example ```json { "example": "{ \"jsonrpc\": \"2.0\", \"result\": { \"kind\": \"urlshortener#url\", \"id\": \"http://goo.gl/fbsS\", \"longUrl\": \"https://www.google.com/\", \"status\": \"OK\"\n } }" } ``` ``` -------------------------------- ### Authenticate and Greet with Google People API (JavaScript) Source: https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html This snippet shows how to load the Google API client, initialize authentication with your API key and client ID, and make a call to the People API to retrieve the user's name for a personalized greeting. It handles sign-in and sign-out states. ```javascript var apiKey = 'YOUR_API_KEY'; var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"]; var clientId = 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com'; var scopes = 'profile'; function handleClientLoad() { gapi.load('client:auth2', initClient); } function initClient() { gapi.client.init({ apiKey: apiKey, discoveryDocs: discoveryDocs, clientId: clientId, scope: scopes }).then(function () { gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); }); } function updateSigninStatus(isSignedIn) { if (isSignedIn) { authorizeButton.style.display = 'none'; signoutButton.style.display = 'block'; makeApiCall(); } else { authorizeButton.style.display = 'block'; signoutButton.style.display = 'none'; } } function handleAuthClick(event) { gapi.auth2.getAuthInstance().signIn(); } function handleSignoutClick(event) { gapi.auth2.getAuthInstance().signOut(); } function makeApiCall() { gapi.client.people.people.get({ 'resourceName': 'people/me', 'requestMask.includeField': 'person.names' }).then(function(resp) { var p = document.createElement('p'); var name = resp.result.names[0].givenName; p.appendChild(document.createTextNode('Hello, '+name+'!')); document.getElementById('content').appendChild(p); }); } ``` -------------------------------- ### Making a REST Request Source: https://github.com/google/google-api-javascript-client/blob/master/samples/io-2012/slides/jsclient.html Provides a detailed explanation and example of how to construct and execute a RESTful request using the Google APIs JavaScript Client. ```APIDOC ## Making a REST Request ### Description This section details how to make RESTful requests to Google APIs using the `gapi.client.request` method. It allows for customization of the HTTP method, headers, and body. ### Method POST, GET, PUT, DELETE, etc. (specified in `method` parameter) ### Endpoint Dynamic, specified by the `path` parameter. ### Parameters #### Request Body - **path** (string) - Required - The path to the API endpoint. - **params** (object) - Optional - Key-value pairs for URL parameters. - **method** (string) - Optional - The HTTP method (defaults to GET). - **headers** (object) - Optional - Key-value pairs for HTTP headers. - **body** (string) - Optional - The request body. - **callback** (function) - Optional - A callback function to handle the response. If provided, the request is executed immediately. ### Request Example ```javascript var restRequest = gapi.client.request({ 'path': '/urlshortener/v1/url', 'params' : {'shortUrl' : 'http://goo.gl/fbsS'}, 'method': 'GET', 'callback': function(jsonResponse, rawResponse) { // Handle request result console.log(jsonResponse); } }); ``` ### Response #### Success Response - The structure of the success response depends on the specific API endpoint being called. #### Response Example ```json { "example": "{ \"kind\": \"urlshortener#url\", \"id\": \"http://goo.gl/fbsS\", \"longUrl\": \"https://www.google.com/\", \"status\": \"OK\"\n}" } ``` ``` -------------------------------- ### Loading an API and Making a Request (Translate API) Source: https://github.com/google/google-api-javascript-client/blob/master/docs/samples.md This example demonstrates how to load the Google Translate API using an API key and make a simple translation request. It showcases the basic structure for initializing the client and executing a method discovered via the API's discovery document. ```APIDOC ## Load API and Make Request (Translate API) ### Description This snippet shows how to load an API and make a request to the Google Translate API using an API key. It demonstrates the process of initializing the Google API client and executing a method like `language.translations.list`. ### Method N/A (JavaScript client-side execution) ### Endpoint N/A (Client-side execution) ### Parameters #### Request Body (for `gapi.client.init`) - **apiKey** (string) - Required - Your Google API key. - **discoveryDocs** (array of strings) - Required - An array containing the discovery document URL for the API (e.g., Google Translate API v2). #### Request Body (for `gapi.client.language.translations.list`) - **q** (string) - Required - The text to translate. - **source** (string) - Required - The source language code (e.g., 'en'). - **target** (string) - Required - The target language code (e.g., 'de'). ### Request Example ```html
``` ### Response #### Success Response (200) - **result.data.translations** (array) - An array containing the translation results. Each element has a `translatedText` field. #### Response Example ```json { "result": { "data": { "translations": [ { "translatedText": "Hallo Welt" } ] } } } ``` #### Error Response - **result.error.message** (string) - A message describing the error that occurred. ``` -------------------------------- ### Calendar API Methods Source: https://context7.com/google/google-api-javascript-client/llms.txt This example demonstrates loading the discovery document for the Calendar API and then listing the user's calendars and retrieving upcoming events from the primary calendar. ```APIDOC ## Calendar API Methods ### Description This example shows how to load the discovery document for the Calendar API and then use its methods to list the user's calendars and retrieve a list of upcoming events from the primary calendar. ### Method `gapi.client.load` to load discovery document, `gapi.client.calendar.calendarList.list` to list calendars, `gapi.client.calendar.events.list` to list events. ### Endpoint N/A (methods are dynamically generated) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript // Calendar API methods gapi.client.load('https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest') .then(function() { // List calendars return gapi.client.calendar.calendarList.list({ maxResults: 10 }); }).then(function(response) { console.log('Calendars:', response.result.items); // Get events from primary calendar return gapi.client.calendar.events.list({ calendarId: 'primary', timeMin: new Date().toISOString(), maxResults: 10, singleEvents: true, orderBy: 'startTime' }); }).then(function(response) { console.log('Upcoming events:', response.result.items); }); ``` ### Response #### Success Response (200) - **items** (array) - A list of calendars or events. - **calendarId** (string) - The ID of the calendar. - **summary** (string) - The summary/name of the calendar. - **timeMin** (string) - The start time for events. - **singleEvents** (boolean) - Whether to return only single events. - **orderBy** (string) - How to order the events. #### Response Example ```json { "items": [ { "kind": "calendar#calendarListEntry", "id": "primary", "summary": "My Calendar" } ] } ``` ``` -------------------------------- ### JavaScript: Expand Short URL using Google API Client Source: https://github.com/google/google-api-javascript-client/blob/master/samples/io-2012/demos/quickDemoIO.html This snippet demonstrates how to expand a short URL using the Google API JavaScript client. It requires an API key and the URLshortener API to be loaded. The function takes a short URL as input and outputs the corresponding long URL. ```javascript var apiKey = 'AIzaSyCVVXgYgW9lsEIVT_B83TF1t6jGE2Ghckk'; function load() { gapi.client.setApiKey(apiKey); gapi.client.load('urlshortener', 'v1', showInputs); } function showInputs() { document.getElementById('requestFields').style.display = ''; } function makeRequest() { function writeResponse(resp) { var responseText; if (resp.code && resp.data[0].debugInfo == 'QuotaState: BLOCKED') { responseText = 'Invalid API key provided. Please replace the "apiKey" value with your own.'; } else { responseText = 'Short URL ' + shortUrl + ' expands to ' + resp.longUrl; } var infoDiv = document.getElementById('info'); infoDiv.innerHTML = ''; infoDiv.appendChild(document.createTextNode(responseText)); } var shortUrl = document.getElementById('shortUrl').value; var request = gapi.client.urlshortener.url.get({ 'shortUrl': shortUrl }); request.execute(writeResponse); } ``` -------------------------------- ### Initialize API Key and Check Authorization Source: https://github.com/google/google-api-javascript-client/blob/master/samples/io-2012/slides/jsclient.html Initializes the Google API client with an API key and schedules a check for user authorization. This is a common setup for accessing Google APIs, especially unprotected resources. ```javascript function init() { gapi.client.setApiKey(apiKey); window.setTimeout(checkAuth,1); } ``` ```javascript function handleClientLoad() { gapi.client.setApiKey(apiKey); window.setTimeout(checkAuth,1); } ``` -------------------------------- ### Run Core Reporting API Demo Source: https://github.com/google/google-api-javascript-client/blob/master/samples/analytics/v3/core_reporting_api_v3_reference.html This JavaScript snippet shows how to execute a request to the Google Analytics Core Reporting API v3 after successful authorization. It specifies the API method, parameters, and handles the response. ```javascript function runDemo() { gapi.client.analytics.data.ga.get({ 'ids': 'ga:' + TableId.value, 'start-date': StartDate.value, 'end-date': EndDate.value, 'metrics': 'ga:sessions,ga:pageviews', 'dimensions': 'ga:source,ga:medium,ga:keyword', 'sort': '-ga:sessions,-ga:pageviews', 'filters': 'ga:medium==(none)', 'max-results': '10' }).then(function(response) { // Handle the API response var formattedJson = new JSONFormatter(response.result, 1); // Adjust indentation level output.innerHTML = ""; output.appendChild(formattedJson.render()); }, function(reason) { console.log('Error: ' + reason.result.error.message); }); } ``` -------------------------------- ### Generate AdSense Report and Draw Pie Chart (JavaScript) Source: https://github.com/google/google-api-javascript-client/blob/master/samples/adsense/v1.1/PieChart.html This snippet demonstrates how to load the AdSense API, generate a report with specified metrics and dimensions, and then render this data as a pie chart using Google Visualization. It includes helper functions for date formatting, data conversion, and chart rendering. Dependencies include the Google API client library and Google Visualization library. ```javascript var endDate = new Date(); // Six months ago. var startDate = new Date(endDate.getTime() - 1000 * 60 * 60 * 24 * 180); // Gets and renders the data. function makeApiCall() { gapi.client.load('adsense', 'v1.1', function() { var request = gapi.client.adsense.reports.generate({ 'startDate': formatDate(startDate), 'endDate': formatDate(endDate), 'metric': ['AD_REQUESTS'], 'dimension': ['AD_CLIENT_ID'], 'sort': ['AD_CLIENT_ID'] }); request.execute(function(resp) { var data = new google.visualization.DataTable(); data.addColumn('string', 'Ad client id'); data.addColumn('string', 'AD_REQUESTS'); data.addRows(resp.rows); var view = new google.visualization.DataView(data); view.setColumns([0, {calc:adReqToNumber, type:'number', label:'Ads requests'}]); drawVisualization(view); }); }); } // Converts the ad request field to numeric values. function adReqToNumber(dataTable, rowNum){ return parseInt(dataTable.getValue(rowNum, 1)); } // Draws the pie chart. function drawVisualization(view) { var wrapper = new google.visualization.ChartWrapper({ chartType: 'PieChart', dataTable: view, options': {'title': 'Ads requests per ad client id - Year 2011'}, containerId: 'vis_div' }); wrapper.draw(); } ``` -------------------------------- ### Initialize and Use URL Shortener API with JavaScript Source: https://github.com/google/google-api-javascript-client/blob/master/samples/simpleRequest.html This snippet initializes the Google API client with the URL Shortener API and demonstrates how to expand a short URL. It requires an API key and handles responses, including potential errors like an invalid API key. The input is a short URL, and the output is the expanded long URL or an error message. ```javascript var apiKey = 'AIzaSyAdjHPT5Pb7Nu56WJ_nlrMGOAgUAtKjiPM'; function handleClientLoad() { gapi.load('client', initClient); } function initClient() { gapi.client.init({ apiKey: apiKey, discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/urlshortener/v1/rest'] }).then(showInputs); } function showInputs() { document.getElementById('requestFields').style.display = ''; } function makeRequest() { function writeResponse(resp) { var responseText; if (resp.code && resp.data[0].debugInfo == 'QuotaState: BLOCKED') { responseText = 'Invalid API key provided. Please replace the "apiKey" value with your own.'; } else { responseText = 'Short URL ' + shortUrl + ' expands to ' + resp.longUrl; } var infoDiv = document.getElementById('info'); infoDiv.innerHTML = ''; infoDiv.appendChild(document.createTextNode(responseText)); } var shortUrl = document.getElementById('shortUrl').value; var request = gapi.client.urlshortener.url.get({ 'shortUrl': shortUrl }); request.execute(writeResponse); } ``` -------------------------------- ### Authorize and Greet with Google People API (JavaScript) Source: https://github.com/google/google-api-javascript-client/blob/master/samples/loadedDiscovery.html This JavaScript code snippet demonstrates how to load the Google API client library, authenticate with Google's People API using OAuth 2.0, and then make a call to retrieve the user's basic profile information (name) to display a personalized greeting. It requires API key and client ID configuration and handles sign-in status changes. ```javascript var apiKey = 'YOUR_API_KEY'; var clientId = 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com'; var scopes = 'profile'; var authorizeButton = document.getElementById('authorize-button'); var signoutButton = document.getElementById('signout-button'); var peopleApiDiscovery; function handleClientLoad() { var loadGapiClient = new Promise(function(resolve, reject) { gapi.load('client:auth2', resolve); }); var fetchPeopleApiDiscovery = fetch('people/people_rest_v1.json').then( function(resp){ return resp.json(); }).then(function(json) { peopleApiDiscovery = json; return Promise.resolve(); }); Promise.all([loadGapiClient, fetchPeopleApiDiscovery]).then(initClient); } function initClient() { gapi.client.init({ apiKey: apiKey, discoveryDocs: [peopleApiDiscovery], clientId: clientId, scope: scopes }).then(function () { gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); authorizeButton.onclick = handleAuthClick; signoutButton.onclick = handleSignoutClick; }); } function updateSigninStatus(isSignedIn) { if (isSignedIn) { authorizeButton.style.display = 'none'; signoutButton.style.display = 'block'; makeApiCall(); } else { authorizeButton.style.display = 'block'; signoutButton.style.display = 'none'; } } function handleAuthClick(event) { gapi.auth2.getAuthInstance().signIn(); } function handleSignoutClick(event) { gapi.auth2.getAuthInstance().signOut(); } function makeApiCall() { gapi.client.people.people.get({ resourceName: 'people/me' }).then(function(resp) { var p = document.createElement('p'); var name = resp.result.names[0].givenName; p.appendChild(document.createTextNode('Hello, '+name+'!')); document.getElementById('content').appendChild(p); }); } ``` -------------------------------- ### Serve Project Locally - Basic Source: https://github.com/google/google-api-javascript-client/blob/master/samples/io-2012/slides/README.html Launches a simple local web server from the project's root directory and opens the default browser to the main template file. ```shell $ cd io-2012-slides $ ./serve.sh ``` -------------------------------- ### Run Local Web Server for Slides Source: https://github.com/google/google-api-javascript-client/blob/master/samples/io-2012/slides/README.md This provides instructions for running a local web server to serve the presentation slides. The `./serve.sh` script launches a simple server and opens the default browser to `http://localhost:8000/template.html`. A custom port can also be specified. ```bash cd io-2012-slides ./serve.sh ``` ```bash ./serve.sh 8080 ``` -------------------------------- ### gapi.client.init Source: https://github.com/google/google-api-javascript-client/blob/master/docs/reference.md Initializes the Google API client library. This is typically the first step before loading any APIs. ```APIDOC ## gapi.client.init ### Description Initializes the Google API client library, including setting up authentication and loading discovery documents. ### Method `gapi.client.init(args) ### Endpoint N/A (Client-side initialization) ### Parameters #### Request Body - **clientId** (string) - Required - The app's client ID, found and created in the Google Developers Console. - **scope** (string) - Required - The scopes to request, as a space-delimited string. ### Request Example ```json { "clientId": "YOUR_CLIENT_ID", "scope": "https://www.googleapis.com/auth/calendar.readonly" } ``` ### Response #### Success Response (Promise) - **Promise** (`goog.Thenable`) - Resolves when all initializations are complete. #### Response Example (Returns a Promise-like object) ```javascript gapi.client.init({ clientId: 'YOUR_CLIENT_ID', scope: 'https://www.googleapis.com/auth/calendar.readonly' }).then(function() { // API client is ready }, function(error) { // Handle initialization error }); ``` ``` -------------------------------- ### Generate AdSense Report and Render Table Chart (JavaScript) Source: https://github.com/google/google-api-javascript-client/blob/master/samples/adsense/v1.1/TableChart.html This snippet fetches AdSense report data, processes it into a format suitable for Google Visualization, and then renders a table chart. It requires the gapi client library and Google Visualization API. The function takes start and end dates to define the reporting period and specifies metrics and dimensions for the report. ```javascript var endDate = new Date(); var startDate = new Date(endDate.getTime() - 1000 * 60 * 60 * 24 * 180); function makeApiCall() { gapi.client.load('adsense', 'v1.1', function() { var request = gapi.client.adsense.reports.generate({ 'startDate': formatDate(startDate), 'endDate': formatDate(endDate), 'metric': ['AD_REQUESTS', 'MATCHED_AD_REQUESTS', 'INDIVIDUAL_AD_IMPRESSIONS'], 'dimension': ['AD_CLIENT_ID'], 'sort': ['AD_CLIENT_ID'] }); request.execute(function(resp) { var data = new google.visualization.DataTable(); data.addColumn('string', 'Month'); data.addColumn('string', 'AD_REQUESTS'); data.addColumn('string', 'MATCHED_AD_REQUESTS'); data.addColumn('string', 'INVIDUAL_AD_IMPRESSIONS'); data.addRows(resp.rows); var view = new google.visualization.DataView(data); view.setColumns([ 0, {calc:adReqToNumber, type:'number', label:'Ad requests'}, {calc:matchedAdReqToNumber, type:'number', label:'Matched ad requests'}, {calc:indAdImpressionsToNumber, type:'number', label:'Individual ad impressions'} ]); drawVisualization(view); }); }); } function adReqToNumber(dataTable, rowNum){ return parseInt(dataTable.getValue(rowNum, 1)); } function matchedAdReqToNumber(dataTable, rowNum){ return parseInt(dataTable.getValue(rowNum, 2)); } function indAdImpressionsToNumber(dataTable, rowNum){ return parseInt(dataTable.getValue(rowNum, 3)); } function drawVisualization(view) { var wrapper = new google.visualization.ChartWrapper({ chartType: 'Table', dataTable: view, containerId: 'vis_div' }); wrapper.draw(); } ``` -------------------------------- ### Initialize Google API Client and Load Libraries Source: https://context7.com/google/google-api-javascript-client/llms.txt This snippet demonstrates how to load the Google API client library and initialize it with authentication. It uses the `gapi.load` method to specify the required modules ('client' and 'auth2') and then calls `initClient` to set up the client. Error handling for the initialization process is also included. ```javascript function initClient() { gapi.client.init({ apiKey: 'YOUR_API_KEY', clientId: 'YOUR_CLIENT_ID.apps.googleusercontent.com', discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"], scopes: 'email', }).then(function() { // Listen for sign-in state changes. gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); // Handle the initial sign-in state. updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); listUpcomingEvents(); }, function(error) { statusSpan.textContent = 'Error initializing client'; resultsDiv.innerHTML += '

Error: ' + JSON.stringify(error) + '

'; }); } // Load the library gapi.load('client:auth2', initClient); ``` -------------------------------- ### gapi.client.init Source: https://github.com/google/google-api-javascript-client/blob/master/docs/reference.md Initializes the JavaScript client with API key, OAuth client ID, scope, and API discovery document(s). ```APIDOC ## gapi.client.init ### Description Initializes the JavaScript client with API key, OAuth client ID, scope, and API discovery document(s). ### Method `gapi.client.init(args)` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body * **args** (object) - Optional - An object encapsulating the various arguments for this method. * **apiKey** (string) - The API Key to use. * **discoveryDocs** (array) - An array of discovery doc URLs or discovery doc JSON objects. ``` -------------------------------- ### Get AdSense Ad Units List - JavaScript Source: https://github.com/google/google-api-javascript-client/blob/master/samples/adsense/v1/GetAllAdUnits.html This function retrieves a list of ad units from the Google AdSense API using the provided ad client ID. It requires the gapi client library to be loaded. The output is an ordered list of ad units appended to an element with the ID 'content'. ```javascript var adClientId = 'INSERT_THE_AD_CLIENT_ID_HERE'; // Gets and renders the data. function makeApiCall() { gapi.client.load('adsense', 'v1', function() { var request = gapi.client.adsense.adunits.list({ 'adClientId': adClientId, 'maxResults': '5000' }); request.execute(function(resp) { var unitsList = document.createElement('ol'); var itemsTotal = resp.items.length; for (var key = 0; key < itemsTotal; key++) { var unit = resp.items[key] addUnit(unitsList, unit) } document.getElementById('content').appendChild(unitsList); }); }); } // Formats one line of the ad units list. function addUnit(unitsList, unit) { var label = document.createElement('li'); var labelString = document.createTextNode( 'Ad unit with code ``` -------------------------------- ### Loading and Registering an API Surface Source: https://github.com/google/google-api-javascript-client/blob/master/samples/io-2012/slides/jsclient.html Demonstrates how to asynchronously load and register an entire API surface, such as the Google+ API, before use. The gapi.client.load function takes the API name, version, and a callback function that executes once the API is ready. This pre-registration makes all supported methods available under the gapi.client namespace. ```javascript gapi.client.load('plus', 'v1', function onReady() { // Executes when the requested API is ready to use }); ``` -------------------------------- ### Client Initialization - gapi.client.init() Source: https://context7.com/google/google-api-javascript-client/llms.txt Initializes the JavaScript client with API key, OAuth credentials, discovery documents, and authorization scopes. Returns a Promise that resolves when initialization completes. ```APIDOC ## gapi.client.init() ### Description Initializes the JavaScript client with API key, OAuth credentials, discovery documents, and authorization scopes. Returns a Promise that resolves when initialization completes. ### Method `gapi.client.init(config)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **apiKey** (string) - Required - Your Google API key. - **clientId** (string) - Optional - Your OAuth 2.0 client ID. - **discoveryDocs** (array of strings) - Optional - URLs or parsed objects of API discovery documents. - **scope** (string) - Optional - The OAuth 2.0 scopes required for the request. ### Request Example ```javascript // Initialize with API key only (for public APIs) gapi.client.init({ apiKey: 'AIzaSyAdjHPT5Pb7Nu56WJ_nlrMGOAgUAtKjiPM', discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/translate/v2/rest'] }).then(function() { console.log('Client initialized with API key'); return gapi.client.language.translations.list({ q: 'hello world', source: 'en', target: 'es' }); }).then(function(response) { console.log('Translation:', response.result.data.translations[0].translatedText); // Output: "hola mundo" }, function(error) { console.error('Error:', error.result.error.message); }); // Initialize with OAuth for authenticated requests gapi.client.init({ apiKey: 'YOUR_API_KEY', clientId: 'YOUR_CLIENT_ID.apps.googleusercontent.com', discoveryDocs: ['https://people.googleapis.com/$discovery/rest?version=v1'], scope: 'profile email' }).then(function() { console.log('Client initialized with OAuth'); // Check if user is already signed in if (gapi.auth2.getAuthInstance().isSignedIn.get()) { return gapi.client.people.people.get({ resourceName: 'people/me', 'requestMask.includeField': 'person.names,person.emailAddresses' }); } }).then(function(response) { if (response) { console.log('Name:', response.result.names[0].displayName); console.log('Email:', response.result.emailAddresses[0].value); } }); ``` ### Response #### Success Response (Promise resolves) - **Initialization Status** (boolean) - Indicates if initialization was successful. #### Response Example (A Promise that resolves with no specific value upon successful initialization, error is thrown on failure.) ```