var oAuthConfig1 = UrlFetchApp.addOAuthService("googleProfiles"); oAuthConfig1.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https:// www.google.com/m8/feeds/profiles"); oAuthConfig1.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken"); oAuthConfig1.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken?oauth_callback=https:// spreadsheets.google.com/macros"); oAuthConfig1.setConsumerKey(ScriptProperties.getProperty("Consumer_Key")); oAuthConfig1.setConsumerSecret(ScriptProperties.getProperty("Consumer_Secret")); var options1 = { oAuthServiceName : "googleProfiles", oAuthUseToken : "always", method : "GET", headers : { "GData-Version" : "3.0" }, contentType : "application/x-www-form-urlencoded" };
var theUrl = ""; if (nextUrl == "") { theUrl = "https://www.google.com/m8/feeds/profiles/domain/" + domain + "/full?v=3&max-results=" + profilesPerPass + "&alt=json"; } else { theUrl = nextUrl; }
if (theUrl != "DONE") { var largeString = ""; try { var response = UrlFetchApp.fetch(theUrl, options1); largeString = response.getContentText(); } catch (problem) { recordEvent_(problem.message, largeString, ss); } }
var provisioningJSONObj = null; var jsonObj = JSON.parse(largeString); var entryArray = jsonObj.feed.entry;
for (var i=0; i<entryArray.length; i++) { var rowArray = new Array(); rowArray[0] = ""; rowArray[1] = ""; rowArray[2] = ""; try { rowArray[0] = entryArray[i].gd$name.gd$fullName.$t; } catch (ex) {} //fullname try { rowArray[1] = entryArray[i].gd$name.gd$givenName.$t; } catch (ex) {} //firstname try { rowArray[2] = entryArray[i].gd$name.gd$familyName.$t; } catch (ex) {} //lastname
var updateRow = getNextRowIndexByUNID_(rowArray[3],4,stageSheet); var valueArray = new Array(); valueArray.push(rowArray); var outputRange = stageSheet.getRange(updateRow, 1, 1, 12); outputRange.setValues(valueArray);
} else { // COPY CHANGES TO "PRODUCTION" TAB OF SPREADSHEET var endTime = new Date(); setSettingFromArray_("LastPassEnded",getZeroPaddedDateTime_(endTime),settingsArray,setSheet); if (parseInt(getSettingFromArray_("StagingCopiedToProduction",settingsArray)) == 0) { // THIS DOES A TEST-WRITE, THEN A "WIPE," THEN COPIES STAGING TO // PRODUCTION var copied = copySheet_(ss,"Staging","Employees"); if (copied == "SUCCESS") { var sortRange = empSheet.getRange(2,1,empSheet.getLastRow(),empSheet.getLastColumn()); sortRange.sort([3,2]); // SORT BY COLUMN C, THEN B // RESET SETTINGS setSettingFromArray_("NextProfileLink","",settingsArray,setSheet); setSettingFromArray_("LastRowUpdated",0,settingsArray,setSheet); setSettingFromArray_("StagingCopiedToProduction",1,settingsArray,setSheet); } } } // end if "DONE"
Editor's note: This has been cross-posted from the Google Code blog -- Jan Kleinert
Google Apps Script is a JavaScript cloud scripting language that provides easy ways to automate tasks across Google products and third party services. If you want to learn more about Google Apps Script, collaborate with other developers, and meet the Apps Script team, here’s your chance! We will be holding an Apps Script hackathon in Washington, DC on Wednesday, March 7 from 2pm - 8pm. After we cover the basics of Apps Script, you can code along with us as we build a complete script, or you can bring your own ideas and get some help and guidance from the team. There will be food, power, and Apps Script experts available to help throughout the day. Just bring your laptop, ideas, enthusiasm, and basic knowledge of JavaScript. Check out out the details of the event and be sure to RSVP to let us know you’re coming.
What’s the difference between reality and theory? In theory, there is no difference. But reality often imposes unanticipated constraints on developers. These may come in the form of bandwidth restrictions, memory limits, timeouts, or other requirements of the systems that interact with your application.
My team recently built an application that helps us analyze the scheduling and usage of conference rooms at Google. We use the new Calendar API v3 on Google App Engine to read the rooms’ schedules, which we combine with actual occupancy data to calculate utilization and other metrics.
As you might imagine, Google has a lot of conference rooms (I believe the last official count was “more than twelve.”) And many of the rooms seem to be booked fairly solid. That means we need to read a lot of data from Calendar. So much, in fact, that our queries time out if we try to read an entire calendar at once. But the API team anticipated “Google scale” use and designed a mechanism that allows us to retrieve data in batches.
The idea is simple. When you create a request, you specify the page size: the maximum number of results you’d like Calendar to return in one batch. Calendar returns the data you requested, along with an opaque page token, which you can think of as a bookmark. To retrieve the next batch of data, you ask the API for the next page token and include the new token in your next request. The page token keeps track of the results you’ve already seen, so Calendar can send the next batch each time. You repeat this process until you’ve exhausted all the results.
Here’s how we did this in Java:
public void getRoomEvents(String roomEmail) throws IOException { // Create a request to list this room’s events (see code, below) Calendar.Events.List listRequest = getListRequest(roomEmail); do { // Retrieve one page of events Events events = executeListRequest(listRequest); List eventList = events.getItems(); // Process each event for (Event event : eventList) { processEvent(event); } // Update the page token listRequest.setPageToken(events.getNextPageToken()); // Stop when all results have been retrieved } while (listRequest.getPageToken() != null); } // Create a request to list the events for a room private Calendar.Events.List getListRequest(String roomEmail) throws IOException { return calendarClient.events().list(roomEmail) .setMaxResults(1000) // Limit each response to 1000 events .setPageToken(null) // Start with the first page of results // Return an individual event for each instance occurrence of a // recurring event .setSingleEvents(true); }
We call getRoomEvents() for each room, using the room’s email address to identify it to Calendar. (You can retrieve events from your own calendar by substituting your own email address.) Then getListRequest() creates a request that we will send to Calendar. The request asks for a list of up to 1000 events from the room’s calendar.
getRoomEvents()
getListRequest()
The remainder of getRoomEvents() is a loop that executes the request, processes the results, and updates the page token in preparation for the next request. The loop continues, retrieving and processing each subsequent page of results, until the entire list has been returned. The call to getNextPageToken() indicates the end of the results by returning a null value.
getNextPageToken()
By paginating our requests we avoid timeouts and reduce memory requirements. As an added benefit, each request completes fairly quickly, which means it’s also quick to retry if an error should occur. And finally, a multithreaded application may be able to process one or more pages of results while it retrieves the next, speeding execution. These advantages have led developers at Google to adopt pagination as a best practice. Look for it in our APIs when you need to exchange large amounts of data, and consider adding it to your own services.
If you have questions about our services or APIs, or if you want to see what other developers are doing with Google Calendar, check the discussions and documentation in the Google Apps Calendar API forum.
Our newest set of APIs - Tasks, Calendar v3, Google+ to name a few - are supported by the Google APIs Discovery Service. The Google APIs Discovery service offers an interface that allows developers to programmatically get API metadata such as:
The APIs Discovery Service is especially useful when building developer tools, as you can use it to automatically generate certain features. For instance we are using the APIs Discovery Service in our client libraries and in our APIs Explorer but also to generate some of our online API reference.
Because the APIs Discovery Service is itself an API, you can use features such as partial response which is a way to get only the information you need. Let’s look at some of the useful information that is available using the APIs Discovery Service and the partial response feature.
You can get the list of all the APIs that are supported by the discovery service by sending a GET request to the following endpoint:
GET
https://www.googleapis.com/discovery/v1/apis?fields=items(title,discoveryLink)
Which will return a JSON feed that looks like this:
{ "items": [ … { "title": "Google+ API", "discoveryLink": "./apis/plus/v1/rest" }, { "title": "Tasks API", "discoveryLink": "./apis/tasks/v1/rest" }, { "title": "Calendar API", "discoveryLink": "./apis/calendar/v3/rest" }, … ] }
Using the discoveryLink attribute in the resources part of the feed above you can access the discovery document of each API. This is where a lot of useful information about the API can be accessed.
discoveryLink
Using the API-specific endpoint you can easily get the OAuth 2.0 scopes available for that API. For example, here is how to get the scopes of the Google Tasks API:
https://www.googleapis.com/discovery/v1/apis/tasks/v1/rest?fields=auth(oauth2(scopes))
This method returns the JSON output shown below, which indicates that https://www.googleapis.com/auth/tasks and https://www.googleapis.com/auth/tasks.readonly are the two scopes associated with the Tasks API.
https://www.googleapis.com/auth/tasks
https://www.googleapis.com/auth/tasks.readonly
{ "auth": { "oauth2": { "scopes": { "https://www.googleapis.com/auth/tasks": { "description": "Manage your tasks" }, "https://www.googleapis.com/auth/tasks.readonly": { "description": "View your tasks" } } } } }
Using requests of this type you could detect which APIs do not support OAuth 2.0. For example, the Translate API does not support OAuth 2.0, as it does not provide access to OAuth protected resources such as user data. Because of this, a GET request to the following endpoint:
https://www.googleapis.com/discovery/v1/apis/translate/v2/rest?fields=auth(oauth2(scopes))
Returns:
{}
Using the API-specific endpoints again, you can get the lists of operations and API endpoints, along with the scopes required to perform those operations. Here is an example querying that information for the Google Tasks API:
https://www.googleapis.com/discovery/v1/apis/tasks/v1/rest?fields=resources/*/methods(*(path,scopes,httpMethod))
Which returns:
{ "resources": { "tasklists": { "methods": { "get": { "path": "users/@me/lists/{tasklist}", "httpMethod": "GET", "scopes": [ "https://www.googleapis.com/auth/tasks", "https://www.googleapis.com/auth/tasks.readonly" ] }, "insert": { "path": "users/@me/lists", "httpMethod": "POST", "scopes": [ "https://www.googleapis.com/auth/tasks" ] }, … } }, "tasks": { … } } }
This tells you that to perform a POST request to the users/@me/lists endpoint (to insert a new task) you need to have been authorized with the scope https://www.googleapis.com/auth/tasks and that to be able to do a GET request to the users/@me/lists/{tasklist} endpoint you need to have been authorized with either of the two Google Tasks scopes.
POST
users/@me/lists
users/@me/lists/{tasklist}
You could use this to do some automatic discovery of the scopes you need to authorize to perform all the operations that your applications does.
You could also use this information to detect which operations and which endpoints you can access given a specific authorization token ( OAuth 2.0, OAuth 1.0 or Authsub token). First, use either the Authsub Token Info service or the OAuth 2.0 Token Info Service to determine which scopes your token has access to (see below); and then deduct from the feed above which endpoints and operations requires access to these scopes.
[Access Token] -----(Token Info)----> [Scopes] -----(APIs Discovery)----> [Operations/API Endpoints]
Example of using the OAuth 2.0 Token Info service:
Request:
GET /oauth2/v1/tokeninfo?access_token= HTTP/1.1 Host: www.googleapis.com
Response:
HTTP/1.1 200 OK Content-Type: application/json; charset=UTF-8 … { "issued_to": "1234567890.apps.googleusercontent.com", "audience": "1234567890.apps.googleusercontent.com", "scope": "https://www.google.com/m8/feeds/ https://www.google.com/calendar/feeds/", "expires_in": 1038 }
There is a lot more you can do with the APIs Discovery Service so I invite you to have a deeper look at the documentation to find out more.
Two months ago we announced that a few of us from the Google Apps Developer Relations team would be going around EMEA to meet with developers and talk about Google Apps technologies. We have met great developers from Germany, France, Russia, Czech Republic, Egypt, Switzerland, Israel, and Spain during Google Developer Days, hackathons, developer conferences and GTUG meetings.
This year we are continuing the tour with a series of Google Apps Script hackathons taking place in Vienna, Milan, Madrid, Munich and Dublin over the next few months. These hackathons provide a fun and hands-on way to learn about Google Apps Script and a good opportunity to give us your feedback on this technology.
For more information about the tour and to register for these events, please visit the Google Apps EMEA Developer Tour website.
We plan to organize many other Google Apps events close to you in the near future. Look for updates on the Google Apps EMEA Developer Tour website or keep an eye out for further announcements on this blog.
We recently posted some best practices for working with recurring events in Google Calendar API v3. In this blog post we’ll highlight another improved area in the v3 API: event reminders.
Google Calendar API v3 offers developers flexible control over event reminders, including per-calendar default settings and custom overrides for individual events.
The user’s default reminders for events on a given calendar can be found in the corresponding entry in the Calendar List collection. The Calendar List collection acts a bit like a list of bookmarks, containing entries for the calendars that the user owns or has looked at in the past (it corresponds to the content of the "My Calendars" and "Other Calendars" list on the bottom left in the Web version of Google Calendar). Each entry is annotated with user-specific settings for the individual calendar, such as the preferred color in the UI and the default reminders.
Google Calendar currently supports three ways of reminding its users of events: "popup", prompting a message directly in the browser, mobile phone or desktop client, as well as "email" and "sms" for messages sent through the respective channels. To change the defaults, update the Calendar List entry and include the reminder method and how many minutes in advance the user should be alerted. In the following example, we set an email reminder to be sent 60 minutes before an event, and a popup reminder 10 minutes before.
{ "summary": "Work Calendar", ... "defaultReminders": [ { "method": "email", "minutes": 60 }, { "method": "popup", "minutes": 10 } ] }
The default reminders will be applied to all existing and future events on this calendar, provided they don’t have custom reminders set already. In contrast to earlier versions of the API, newly created events will also have reminders set by default.
Sometimes, there are events that we want a special reminder for, or none at all. To override the defaults for a specific event, switch the useDefault flag in the reminders section to false, and include a set of custom reminders, or leave the list empty. When you define a set of override reminders for a recurring series, they are automatically applied to each of its occurrences, unless they have been overridden explicitly. Like the default reminders on the calendar, these are personal reminders for the user that is logged in, and will not influence the settings others might have for the same calendar or event. Here is an example that overrides the default reminders with a 15 minute SMS reminder for that specific event.
useDefault
reminders
false
{ "summary": "API Office Hours", ... "reminders": { "useDefault": false, "overrides": [ { "method": "sms", "minutes": 15 } ] } }
The defaults for the given calendar are included at the top of any event listing result. This way, reminder settings for all events in the result can be determined by the client without having to make the additional API call to the corresponding entry in the Calendar List collection.
In this post and an earlier post about best practices with recurring events, we have covered some improved areas of the latest version of the Google Calendar API. Have a look at the migration guide for a more complete view of other changes we made in the new version, and let us know what you think.
If you have any questions about handling reminders or other features of the new Calendar API, post them on the Calendar API forum.
Editor’s Note:This is a guest post from John Watkinson. John is a developer and the co-founder of Docracy, a start-up company that hosts crowd-sourced legal documents and provides free e-signing services. He recently attended, and won first place, at the Google Apps Hackathon in NYC. Here's John's story about the event.
Our company is focused on documents in the cloud, so we attended the Google Apps Developer Hackathon on December 1st in New York City to learn more about the various Google Apps APIs, and how we can best integrate with them. During the initial presentations from Ryan Boyd and Saurabh Gupta of the Google Apps team, we were delighted to learn about Apps Script. It provides a powerful JavaScript interface into Google Apps, including Docs, Calendar, Gmail, Maps and many others.
After the tech presentations, we formed teams and started hacking with the technology. I joined a team with Matt Hall (also from Docracy), Nick Siderakis, Jeff Hsin and Scott Thompson. We struck upon the idea of creating a function that would make calls to Wolfram Alpha via their developer API. It took all five of us hacking away for a few hours to parse the Alpha results properly, but eventually we had an Apps Script custom function for Spreadsheet called “wolf”. It had a kind of magic feeling about it, as you could pass simple English-language queries into the function and get back exact numeric results in your Google Spreadsheet. Some example working queries:
=wolf("distance from the earth to the moon in km")
=wolf("population of canada in 1960")
=wolf("average january temperature in buenos aires")
=wolf("9th digit of pi")
=wolf("count of olympic medals won by japan in 2008")
Any function in Apps Script can be used as a spreadsheet function directly, so our main wolf function is the entry point to our script. We use Apps Script’s UrlFetch service to make our API call to Wolfram Alpha (note, the full URL is truncated for brevity):
wolf
UrlFetch
var response = UrlFetchApp.fetch("http://api.wolframalpha.com/..." + encodeURIComponent(input));
The response from Alpha is an XML file that includes a lot of metadata we don’t need. So, we used a recursive function and the XML manipulation tools in Apps Script to track down the element of interest to us (below is a simplified version):
function findText(e) { if (e.getName().getLocalName() == 'plaintext') { return e.getText(); } else { var children = e.getElements(); for (var i = 0; i < children.length; i++) { var result = findText(children[i]); if (result) return result; } return null; } }
A little bit more work is required to parse the result, as sometimes Alpha will report numbers in words (i.e. “40.7 million”), but otherwise that’s it!
For a small script, it definitely feels pretty powerful! Our little invention earned us a first place finish at the hackathon, and the prizes were little indoor RC-controlled helicopters. I managed to irreparably damage mine in a gruesome crash into my refrigerator already, but I hear that many of the others are still serviceable and flying missions daily.
Once we were comfortable with the Apps Script Services (and aware of its capabilities with spreadsheets in particular), a side project emerged that used some of the other integration features available. Apps Script functions can listen for events that are triggered by the editing of a spreadsheet cell (if the user grants the appropriate permissions). Using these onEdit Event Handlers, we wrote an implementation of the classic game Mine Sweeper that is playable right in the spreadsheet!
You can play the game by making a copy of this spreadsheet and then clicking the menu item SheetSweeper > New Game. When you play the game, the script responds to onEdit events that are dispatched from the spreadsheet.
function onOpen() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var menuEntries = [{name: "New Game", functionName: "startGame"}]; ss.addMenu("SheetSweeper", menuEntries); }
Then when the user edits a cell, the script responds and implements the mine sweeper logic:
function onEdit(event) { var ss = event.source.getActiveSheet(); var cell = ss.getActiveCell(); if (cell.getValue() == 'x') { // Flagging a mine flagCell(cell); } else { // Clearing a cell clearCell(cell); } }
We had a great time at the hackathon, and are happy to have been introduced to Apps Script. We believe it has an exciting future ahead of it.
Are you ever at an airport with no internet access, and realize that you forgot to set your "Out of Office" (OOO) message?" I forget regularly, but always remember to block off my calendar. Why not have the calendar automatically update my OOO message? We can! With the Calendar API, we can retrieve calendar events and set a vacation responder for the event duration for any user in the domain using the Email Settings API.
The first step is to authorize the Calendar and Email Settings client to make any call to the APIs respectively. The new Calendar API requires google-api-client library while the Email settings API still works with the gdata-client library in Python. These libraries use different underlying protocols and handle authorization differently.
Fortunately we can use the same code to get an OAuth 2.0 token for both the Calendar API and the Email Settings API.
from oauth2client.file import Storage from oauth2client.client import AccessTokenRefreshError from oauth2client.client import OAuth2WebServerFlow from oauth2client.tools import run SCOPES = ('https://www.googleapis.com/auth/calendar ' 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/') FLOW = flow_from_clientsecrets('client_secrets.json', scope=SCOPES) storage = Storage('vacation.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = run(FLOW, storage)
Now that we have obtained the OAuth 2.0 token from OAuth2WebServerFlow, we can use it in either library. To authorize the Calendar service:
# Create an httplib2.Http object to handle the HTTP # requests and authorize it with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) # Build authorized service for Calendar API service = build('calendar', 'v3', http=http)
Authorizing the Email Settings client requires adapting the credentials:
auth2token = gdata.gauth.OAuth2Token(client_id=client_id, client_secret=client_secret, scope=SCOPE, access_token=credentials.access_token, refresh_token=credentials.refresh_token, user_agent='vacation-responder-sample/1.0') email_client = auth2token.authorize( gdata.apps.emailsettings.client.EmailSettingsClient( domain=domain))
Now its time to update the vacation responder based on calendar event using the authorized client. Lets query for events containing the string ‘vacation’ from the Calendar API. The following code snippet shows the retrieval of events.
# Convert the date to the RFC 3339 timestamp format # for Calendar API. cur_datetime = datetime.datetime.now() cur_date = cur_datetime.strftime('%Y-%m-%dT%H:%M:%SZ') events = service.events().list(calendarId=username, q='vacation', timeMin=cur_date, singleEvents=True, orderBy='startTime').execute()
By specifying a user’s email address as the calendarID, we can query against any primary calendars in our domain that are shared and readable by the administrator. If the user opts to hide their calendar, we won’t find any of their events. For additional details about the query on calendar events, refer to the calendar query parameters from the reference guide.
Next we can obtain the start and end time of the event and update the vacation responder using the Email Settings client if the event’s duration is day long or more.
if 'items' in events: for event in events['items']: startDate = event['start'] endDate = event['end'] # If event is set for the day not just for a time slot. if 'date' in startDate: email_client.UpdateVacation(username=username, enable=True, subject='Out of office', message='If urgent call me.', domain_only=True, start_date=startDate['date'], end_date=endDate['date']) print '\nVacation responder set for the days between %s to %s' % (startDate['date'], endDate['date']) break
You can download the sample and build your own application on top of it. We hope that this sample makes it easier to get started, particularly for apps that need to combine APIs from the two API clients. Please feel free to reach us in the Google Domain Info and Management Forum with any questions you have or write us feedback on this post.
We recently updated the Google Apps Marketplace with several new features to help developers better engage with their customers and improve discoverability of apps in the marketplace.
It’s no secret that engaging your customers and responding to their feedback is critical to success. It’s now possible to engage in conversations with customers based on comments & reviews for your app in the marketplace.
Google Search recently introduced rich snippets for applications several months ago with enhanced search results for applications from marketplaces like Android Market and others. Marketplace apps will soon be appearing as rich snippets with ratings and pricing details.
Lastly, we introduced new home pages for each category in the Marketplace to feature the top installed and newest apps for that category.
We hope that you find value in these changes and wish everyone a happy new year!
2011 was the year of momentum for Google Apps Script. As 2012 dawns upon us, let us take a moment to reflect on the past year.
We started 2011 with a bang! In January we released a cloud-based Debugger into Apps Script’s IDE that proved to be very useful for developers. The Script Editor was upgraded bringing about many features and bug fixes. In March we implemented a very powerful feature of embedding Apps Script in Google Sites pages as Gadgets, making it easy to enhance Sites in amazing ways. We also improved Contacts Services, making it more stable with an improved API.
At Google I/O in May we launched Document Services, Gmail Services and the drag ‘n’ drop GUI Builder. These were major steps forward in making sure that Apps Script provides a full set of APIs to allow developers to build rich workflow and automation solutions.
We were very busy during the summer months preparing for a series of launch for later part of 2011. In September, we launched Charts Services. It allows users to dynamically create Charts and embed them in emails, UiApp or export as images. We also released three Google API services for Prediction, UrlShortener and Tasks APIs.
Lock and Cache Services launched in October. These services are important for building performant and scalable applications. We also improved the Script Editor by adding Project Support and made other UI improvements. November brought about the launch of Client Handlers and Validators. This is only the beginning of our commitment to allow developers to build more advanced UI using Apps Script.
In December we continued to improve the reliability and stability of Apps Script runtime. We capped the year by releasing Groups and Domain Services. And who can forget the very useful AdSense Services for AdSense advertisers!
Throughout the year we expanded our outreach channels. There were Apps Script sessions at Google I/O and Bootcamp, and several attendees got their last minute tickets through the Apps Script I/O challenge. We were at Google Developer Day and DevFest events, met with GTUGs, and hosted hackathons throughout the world. Our blog also featured scripts like Revevol’s Trainer Finder, Corey’s Gmail Snooze, Dave’s Flubaroo, Top Contributor’s Mail Merge, Saqib’s Idea Bank, and Drew’s Calorie Counting that showed the power of Apps Script.
Recently we started Office Hours in G+ hangout. These hangouts proved to be very popular, personal and effective means to share ideas with Apps Script community. Join us some day!
In our efforts to help educators, we worked with a New York city school to help them make most out of Google Apps. We also hosted many EDU focused webinars and workshops. In great Google tradition, Apps Script team participated in CAPE and Google Serve.
2012 is going to be an even more exciting and promising year. Tighten your seat belts because we intend to keep firing on all cylinders!
The recently launched Groups Settings API allows Google Apps domain administrators to write client applications for managing groups in their domain. Once you have created the groups and added members using the Provisioning API, you can use the Groups Settings API to perform actions like:
Let’s have a look at how you can make authorized calls to the Groups Settings API from your client application.
You must enable the Provisioning API to make requests to the Groups Settings API. You can do so by enabling the Provisioning API checkbox in the Domain settings tab of your Google Apps control panel.
Next, ensure that the Google Groups for Business and Email services are added to your domain by going to the Dashboard. If these services are not listed, add them by going to Add more services link next to the Service settings heading.
Now you are set to write client applications. Let's discuss the steps to write an application using the Python client library. You need to install the google-api-python-client library first.
You can register a new project or use an existing one from the APIs console to obtain credentials to use in your application. The credentials (client_id, client_secret) are used to obtain OAuth tokens for authorization of the API requests.
client_id
client_secret
The Groups Settings API supports various authorization mechanisms, including OAuth 2.0. Please see the wiki for more information on using the library’s support for OAuth 2.0 to create a httplib2.Http object. This object is used by the Groups Settings service to make authorized requests.
httplib2.Http
The Python client library uses the Discovery API to build the Groups Settings service from discovery. The method build is defined in the library and can be imported to build the service. The service can then access resources (‘groups’ in this case) and perform actions on them using methods defined in the discovery metadata.
build
The following example shows how to retrieve the properties for the group staff@example.com.
staff@example.com
service = build(“groups”, “v1”, http=http) group = service.groups() g = group.get(groupUniqueId=”staff@example.com”).execute()
This method returns a dictionary of property pairs (name/value):
group_name = g['name'] group_isArchived = g['isArchived'] group_whoCanViewGroup = g['whoCanViewGroup']
The update method can be used to set the properties of a group. Let’s have a look at how you can set the access permissions for a group:
update
body = {'whoCanInvite': ALL_MANAGERS_CAN_INVITE, 'whoCanJoin': ‘INVITED_CAN_JOIN’, 'whoCanPostMessage': ‘ALL_MEMBERS_CAN_POST’, 'whoCanViewGroup': ‘ALL_IN_DOMAIN_CAN_VIEW’ } # Update the properties of group g1 = group.update(groupUniqueId=groupId, body=body).execute()
Additional valid values for these properties, as well as the complete list of properties, are documented in the reference guide. We have recently added a sample in the Python client library that you can refer to when developing your own application. We would be glad to hear your feedback or any queries you have on the forum.
Though developers are quite comfortable thinking in abstractions, we still find a lot of value in code examples and fully developed sample applications. Judging by the volume of comments, tweets, and git checkouts of the Au-to-do sample code we released a few weeks ago, our readers agree.
For Google Apps API developers who want to get started writing mobile apps, here’s a great new resource: a sample application that integrates Google Calendar API v3 with Android and illustrates best practices for OAuth 2.0. This meeting scheduler app built by Alain Vongsouvanh gets the user’s contact list, lets users select attendees, and matches free/busy times to suggest available meeting times. It provides a simple Android UI for user actions such as attendee selection:
The sample code for Meeting Scheduler demonstrates many key aspects of developing with Google Apps APIs. After authorizing all required access using OAuth 2.0, the Meeting Scheduler makes requests to the Calendar API. For example, the class FreeBusyTimesRetriever queries the free/busy endpoint to find available meeting times:
FreeBusyTimesRetriever
FreeBusyRequest request = new FreeBusyRequest(); request.setTimeMin(getDateTime(startDate, 0)); request.setTimeMax(getDateTime(startDate, timeSpan)); for (String attendee : attendees) { requestItems.add(new FreeBusyRequestItem().setId(attendee)); } request.setItems(requestItems); FreeBusyResponse busyTimes; try { Freebusy.Query query = service.freebusy().query(request); // Use partial GET to retrieve only needed fields. query.setFields("calendars"); busyTimes = query.execute(); // ... } catch (IOException e) { // ... }
In this snippet above, note the use of a partial GET request. Calendar API v3, along with many other new Google APIs, provides partial response with GET and PATCH to retrieve or update only the data fields you need for a given request. Using these methods can help you streamline your code and conserve system resources.
For the full context of all calls that Meeting Scheduler makes, including OAuth 2.0 flow and the handling of expired access tokens, see Getting Started with the Calendar API v3 and OAuth 2.0 on Android. The project site provides all the source code and other resources, and there’s a related wiki page with important configuration details.
We hope you’ll have a look at the sample and let us know what you think in the Google Apps Calendar API forum. You’re welcome to create a clone of the source code and do some Meeting Scheduler development of your own. If you find a bug or have an idea for a feature, don’t hesitate to file it for evaluation.
All developers agree that saving bandwidth is a critical factor for the success of a mobile application. Less data usage means faster response times and also lower costs for the users as the vast majority of mobile data plans are limited or billed on a per-usage basis.
When using any of the Google Data APIs in your application, you can reduce the amount of data to be transferred by requesting gzip-encoded responses. On average, the size of a page of users returned by the Provisioning API (100 accounts) is about 100 Kb, while the same data, gzip-encoded, is about 5 Kb -- 20 times smaller! When you can reduce data sizes at this dramatic scale, the benefits of compression will often outweigh any costs in client-side processing for decompression.
Enabling gzip-encoding in your application requires two steps. You have to edit the User-Agent string to contain the value gzip and you must also include an Accept-Encoding header with the same value. For example:
User-Agent
gzip
Accept-Encoding
User-Agent: my application - gzip Accept-Encoding: gzip
Client libraries for the various supported programming languages make enabling gzip-encoded responses even easier. For instance, in the .NET client library it is as easy as setting the boolean UseGZip flag of the RequestFactory object:
service.RequestFactory.UseGZip = true;
For any questions, please get in touch with us in the respective forum for the API you’re using.
Users of the Google Documents List API have traditionally had to perform individual export operations in order to export their documents. This is quite inefficient, both in terms of time and bandwidth for these operations.
To improve latency for these operations, we have added the Archive Feed to the API. Archives allow users to export a large number of items at once, in single ZIP archives. This feature provides a useful optimization for users, greatly increasing the efficiency of export operations. Additionally, users can receive emails about archives, and choose to download them from a link provided in the email.
This feature had a soft release earlier this year, and we think it’s now ready for prime time. For more information, please see the Archive Feed documentation.
Since 1998, when the first doodle was released, they have been one of the most loved features of the Google home page. There have been doodles to celebrate all kinds of events, including national holidays, birthdays of artists and scientists, sports competitions, scientific discoveries and even video games! Also, doodles have evolved from simple static images to complex applications, such as the interactive electric guitar used to celebrate the birthday of Les Paul.
Want your company logo to change for selected events or holidays, just like doodles? The Admin Settings API allows domain administrators to write scripts to programmatically change the logo of their Google Apps domain, and Google App Engine offers the ability to configure regularly scheduled tasks, so that those scripts can run automatically every day.
With these two pieces combined, it is pretty easy to implement a complete solution to change the domain logo on a daily basis (assuming the graphic designers have prepared a doodle for each day), as in the following screenshot:
Let’s start with a Python App Engine script called doodleapps.py:
doodleapps.py
import gdata.apps.adminsettings.service from google.appengine.ext import webapp from google.appengine.ext.webapp import util from datetime import date class DoodleHandler(webapp.RequestHandler): # list of available doodles DOODLES = { '1-1': 'images/newyearsday.jpg', '2-14': 'images/valentinesday.jpg', '10-31': 'images/halloween.jpg', '12-25': 'images/christmas.jpg' } # returns the path to the doodle corresponding to the date # or None if no doodle is available def getHolidayDoodle(self, date): key = '%s-%s' % (date.month, date.day) if key not in self.DOODLES: return None return self.DOODLES[key] # handles HTTP requests by setting today’s doodle def get(self): doodle = self.getHolidayDoodle(date.today()) self.response.out.write(doodle) if doodle: service = gdata.apps.adminsettings.service.AdminSettingsService() // replace domain, email and password with your credentials // or change the authorization mechanism to use OAuth service.domain = 'MYDOMAIN.COM' service.email = 'ADMIN@MYDOMAIN.COM' service.password = 'MYPASSWORD' service.source = 'DoodleApps' service.ProgrammaticLogin() # reads the doodle image and update the domain logo doodle_bytes = open(doodle, "rb").read() service.UpdateDomainLogo(doodle_bytes) # webapp initialization def main(): application = webapp.WSGIApplication([('/', DoodleHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main()
The script uses a set of predefined doodles which can be edited to match your list of images or replaced with more sophisticated logic, such as using the Google Calendar API to get the list of holidays in your country.
Every time the script is triggered by an incoming HTTP request, it will check whether a doodle for the date is available and, if there is one, update the domain logo using the Admin Settings API.
In order for this script to be deployed on App Engine, you need to to configure the application by defining a app.yaml file with the following content:
app.yaml
application: doodleapps version: 1 runtime: python api_version: 1 handlers: - url: .* script: doodleapps.py
We want the script to run automatically every 24 hours, without the need for the administrator to send a request, so we also have to define another configuration file called cron.yaml:
cron.yaml
cron: - description: daily doodle update url: / schedule: every 24 hours
Once the application is deployed on App Engine, it will run the script on a daily basis and update the logo.
The holiday season is upon us. Could there be a better time for your company to start using doodles?
Happy Holidays!
Managing the user accounts in a Google Apps domain can be a daunting task when you have hundreds or thousands of them and you have no tools to automate the process. The Google Apps Provisioning API allows developers to write user management applications in the programming language of their choice, but many system administrators prefer a script-based solution instead. The recently launched UserManager Apps Script service fills the gap, providing Google Apps domain administrators an easy way to automate tasks such as batch user creation or update.
With the new Apps Script service, creating a user will be as easy as writing a single line of code:
var user = UserManager.createUser("newuser", "John", "Smith", "mypassword");
The UserManager service also makes it easy to perform the same task on each account in the domain. The following sample shows how you can force all users to change their passwords at the next login:
var users = UserManager.getAllUsers(); for (var i in users) { users[i].setChangePasswordAtNextLogin(true); }
Calls to the UserManager service can also be scheduled to run hourly or daily, or in response to certain events thanks to Apps Script Triggers.
Interested in what else you can do with the UserManager service? Please check the documentation and get in touch with us on the the forum for any questions about its usage or to share more info about your project with the community.
Google Groups is a great way to foster communication over email and on the web, connecting people and allowing them to participate in and read archived discussions. Today, we are introducing the Google Groups Service in Google Apps Script. Groups Service will allow a script to check if a user belongs to a certain group, or to enumerate the members of a particular group. The Google Groups Service works with groups created through the Google Groups web interface as well as groups created by enterprise customers with their own domain using the control panel and the Google Apps Provisioning API.
This opens a wide range of possibilities, such as allowing a script with Ui Services to show additional buttons to the members of a particular group - for example teachers or managers - and sending customized emails to all the members of a group.
Here are a few sample scripts to help you get started with the new API. To try out these samples, select Create > New Spreadsheet and then Tools > Script Editor from the menu. You can then copy the code into the script editor. The scripts’ output will appear back in the spreadsheet.
The Groups Services can be used to fetch a list of the Google Groups of which you’re a member.
Below is a function which returns all the groups of which you’re a member. Copy and paste it into the script editor and run it. The editor will prompt you to grant READ access to the Google Groups Service before the script can run successfully.
If you receive a message stating that you’re not a member of any group, open up Google Groups and join any of the thousands of groups there.
function showMyGroups() { var groups = GroupsApp.getGroups(); var s; if (groups.length > 0) { s = "You belong to " + groups.length + " groups: "; for (var i = 0; i < groups.length; i++) { var group = groups[i]; if (i > 0) { s += ", "; } s += group.getEmail(); } } else { s = "You are not a member of any group!"; } Browser.msgBox(s); }
Brendan plays trumpet in a band. He also runs the band’s website and updates its Google+ page. He’s created a web application with Google Apps Script and now he wants to add to it some additional features for members of the band. Being a model Google user, he’s already subscribed each band member to a Google Group. Although building a complete UI with Google Apps Script is beyond the scope of this article, Brendan could adapt the following function to help make additional features available only to members of that Google Group.
Of course, this is not just useful for tech-savvy trumpet players: schools may wish to make certain features available just to teachers or others just to students; businesses may need to offer certain functionality to people managers or simply to show on a page or in a UI operations of interest to those in a particular department. Before running this example yourself, replace test@example.com with the email address of any group of which you’re a member.
test@example.com
Note: the group’s member list must be visible to the user running the script. Generally, this means you must yourself be a member of a group to successfully test if another user is a member of that same group. Additionally, group owners and managers can restrict member list access to group owners and managers. For such groups, you must be an owner or manager of the group to query membership.
function testGroupMembership() { var groupEmail = "test@example.com"; var group = GroupsApp.getGroupByName(groupEmail); if (group.hasUser(Session.getActiveUser().getEmail())) { Browser.msgBox("You are a member of " + groupEmail); } else { Browser.msgBox("You are not a member of " + groupEmail); } }
Sending an email to the group’s email address forwards that message to all the members of the group. Specifically, that message is forwarded to all those members who subscribe by email. Indeed, for many users, discussion over email is the principal feature of Google Groups.
Suppose, however, that you want to send a customised message to those same people. Provided you have permission to view a group’s member list, the Google Groups Service can be used to fetch the usernames of all the members of a group. The following script demonstrates how to fetch this list and then send an email to each member.
Before running this script, consider if you actually want to send a very silly message to all the members of the group. It may be advisable just to examine how the script works!
function sendCustomizedEmail() { var groupEmail = "test@example.com"; var group = GroupsApp.getGroupByEmail(groupEmail); var users = group.getUsers(); for (var i = 0; i < users.length; i++) { var user = users[i]; MailApp.sendEmail(user.getEmail(), "Thank you!", "Hello " + user.getEmail() + ", thank you for joining this group!"); } }
The Google Groups Service lets you query a user’s role within a group. One possible role is MANAGER (the other roles are described in detail in the Google Groups Service’s documentation): these users can perform administrative tasks on the group, such as renaming the group and accepting membership requests. Any user’s Role can be queried with the help of the Group class’ getRole() method.
This sample function may be used to fetch a list of a group’s managers. Once again, you must have access to the group’s member list for this function to run successfully:
function getGroupOwners(group) { var users = group.getUsers(); var managers = []; for (var i = 0; i < users.length; i++) { var user = users[i]; if (group.getRole(user) == GroupsApp.Role.MANAGER) { managers.push(user); } } return managers; }
Let us know what you end up building, or if you have any questions about this new functionality, by posting in the Apps Script forum.
Editor's note: this announcement is cross-posted from the Google Ads Developer Blog, which caters to AdWords, AdSense, DoubleClick and AdMob developers. We hope you enjoy this latest addition to Google Apps Script — Ryan Boyd
Starting today, the AdSense Management API is available as part of AdSense Services in Google Apps Script. This means that you’ll be able to do things like:
Accessing the API from Google Apps Scripts is very easy. The following snippet of code shows how to generate a report and populate columns of a spreadsheet with the data retrieved:
function generateReport() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName('Reports'); var startDate = Browser.inputBox( "Enter a start date (format: 'yyyy-mm-dd')"); var endDate = Browser.inputBox( "Enter an end date (format: 'yyyy-mm-dd')"); var args = { 'metric': ['PAGE_VIEWS', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS', 'INDIVIDUAL_AD_IMPRESSIONS'], 'dimension': ['MONTH']}; var report = AdSense.Reports.generate(startDate, endDate, args).getRows(); for (var i=0; i<report.length; i++) { var row = report[i]; sheet.getRange('A' + String(i+2)).setValue(row[0]); sheet.getRange('B' + String(i+2)).setValue(row[1]); sheet.getRange('C' + String(i+2)).setValue(row[2]); sheet.getRange('D' + String(i+2)).setValue(row[3]); sheet.getRange('E' + String(i+2)).setValue(row[4]); } }
function generateLineChart() { var doc = SpreadsheetApp.getActiveSpreadsheet(); var startDate = Browser.inputBox( "Enter a start date (format: 'yyyy-mm-dd')"); var endDate = Browser.inputBox( "Enter an end date (format: 'yyyy-mm-dd')"); var adClientId = Browser.inputBox("Enter an ad client id"); var args = { 'filter': ['AD_CLIENT_ID==' + adClientId], 'metric': ['PAGE_VIEWS', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS', 'INDIVIDUAL_AD_IMPRESSIONS'], 'dimension': ['MONTH']}; var report = AdSense.Reports.generate(startDate, endDate, args).getRows(); var data = Charts.newDataTable() .addColumn(Charts.ColumnType.STRING, "Month") .addColumn(Charts.ColumnType.NUMBER, "Page views") .addColumn(Charts.ColumnType.NUMBER, "Ad requests") .addColumn(Charts.ColumnType.NUMBER, "Matched ad requests") .addColumn(Charts.ColumnType.NUMBER, "Individual ad impressions"); // Convert the metrics to numeric values. for (var i=0; i<report.length; i++) { var row = report[i]; data.addRow([row[0],parseInt(row[1]),parseInt(row[2]), parseInt(row[3]),parseInt(row[4])]); } data.build(); var chart = Charts.newLineChart() .setDataTable(data) .setTitle("Performances per Month") .build(); var app = UiApp.createApplication().setTitle("Performances"); var panel = app.createVerticalPanel() .setHeight('350') .setWidth('700'); panel.add(chart); app.add(panel); doc.show(app); }
Google Apps domain administrators have access to a number of APIs to automate their management activities or to integrate with third-party applications, including the Provisioning API to manage user accounts and groups, the Admin Audit API, Admin Settings API, and the Reporting API.
These APIs were only available in Google Apps for Business, Education and ISP editions but many administrators of the free version of Google Apps also requested access to them. I’m glad to say that we listened to your feedback and, starting today, we made the these APIs available to all Google Apps editions.
Please check the documentation as the starting point to explore the possibilities of the APIs and post on our forum if you have questions or comments.