Integrating Grails with Oauth plugin and Google Calendar API

Hello everyone! Here comes another tutorial, and this time, I'll be experimenting with the following:
Please take note of the versions that I have used. As I know, Google updates very often and so what's written here may become deprecated in later versions. In order for us to use the Google Calendar API, we will first need to authenticate users with the use of the Oauth handshake. Basically, what happens during this handshake is simplified for us by the plugin. Have you seen those "Connect via Google" type of buttons? Well, when a user clicks on it, it will take the user to an authentication page that looks like this:

Yes, something like this happens. Once, the user clicks on "Allow access" that's the only time we can fully utilize the Google Calendar API.

Step 1:
Install the plugin. Simply type in the following commands on the terminal:
grails install-plugin oauth
Step 2:
Next, while waiting for the oauth plugin to be fully installed, we have to register our app. Google requires this so that they can monitor the statistics of the apps that use their APIs, or so, that's how I see it. If you have already registered your app, then there is no sense going through this. Just skip this step. For those who are newbies, we can register our app in the Google API's Console. If this is your first app to be registered ever, then the Google API Console page would look something like this:
Obviously, click on "Create Project" and you will be taken to a list full of Google APIs. Don't be overwhelmed yet. It looks something like this:
Click on "Overview" on the top left corner of the page. Then click on "Register" as shown in the picture below:
After clicking on "Register" a pop-up box will appear where Google will ask you for a project ID. A project ID is a unique, DNS-compatible label similar to a hostname that is used by certain services to locate your project and access its resources. A project ID is only required when a service you use depends on it. Your ID will be globally unique. Once a project ID has been registered, it cannot be changed so be creative and choose wisely. 
After specifying your project ID, click on "Choose this ID". Next, we will have to choose the different services that we will use for the project. Click on "Services" on the top left corner of the page and it will take you to the list of services. For this tutorial, we will use Google Calendar. You can use other APIs as your app requires. Click on the "off" button near the Calendar API Service to activate the aforementioned. Refer to the screenshot below.
Once the "off" button switches to an "on" button, the page will redirect you to a series of User Agreements. Be sure to read them to be aware of what you're getting into. Certain APIs require payment once a certain limit has been reached. Anyhow, click on "agree" and we are set! Click on "API Access" then "Create an Oauth 2.0 client ID". Refer to the image below.
A pop-up box will appear. Be sure to fill up the necessary details and click on next. See the screenshot below:
Since, our project is Grails, I chose "Web Application" and on the hostname, I used localhost for the mean time, since I can't afford a host for testing yet. lol. Click on "Create Client ID".
Take a look at the values given above. The values I have encircled above are the ones that we need for the oauth plugin to work, so don't close that tab just yet.

Step 3:
Up next, we modify our Config.groovy. Go back to Google API console and copy and paste your client ID, Client secret, and callback url as seen on the code below.  
oauth {
providers {
google {
api = org.scribe.builder.api.GoogleApi
key = '749579488156.apps.googleusercontent.com'
secret = 'NwMcVdSUeCR5kOiHEC7hnWzb'
scope = ' https://www.googleapis.com/auth/calendar'
successUri = '/calendar/show'
failureUri = '/login/denied'
callback = "http://localhost:8080/myApp/oauth/google/callback"
}
}

debug = true
connectTimeout = 5000
receiveTimeout = 5000
}
I shall provide a little info regarding the values above:
  • Provider - refers to the name of the giver of the API. lol. Anyhow, in this case it's Google since we are using their Calendar API. If you wanted to use Oauth for other providers, you may in fact do so. Example of other providers are Twitter, Linkedin and Facebook. You can also add multiple providers if that's your kind of thing.
  • Key - The key actually refers to the Client ID. If you thought it was the API key, you're wrong! Google duped me! It's the Client ID folks! For those using other providers, check your provider's API docs on how to obtain the key.
  • Secret - Simply equivalent to "Client Secret".
  • Scope - Google requires that we state the scope of our access. For instance, if we need to access the google calendar then we add the scope for the calendar. The complete list of scopes can be found here. If you want to access more than 1 google service, then you just separate the scopes by a space.
  • SuccessUri - The user will be redirected to this page if authentication was successful. Change the value with your desired URI.
  • FailureUri - If the authentication failed, then obviously the user will have to be taken to a page stating that the process failed. Change this option to your desired URI.
  • Debug - setting this to "true" can be helpful when testing out the oauth feature especially when you recieve an error. The errors displayed on the terminal will be verbose.
Step 4:
Next we use a taglib to generate a link that will redirect the user to the Google authentication page. We simply insert the following code to our desired view.  
<oauth:connect provider="google">Connect to Google</oauth:connect>
Step 5:
Next, we decide what we want to do with the API. Would you like to fetch a list of calendars from a particular user? Would you like to insert a new event to a calendar etc? Google has a very helpful interactive documentation for us to test and follow through. Click here for the reference. For this experiment, I shall try to fetch a list of calendars. I didn't want to use the java client libraries because I found it inconsistent and a little hard to control. For some reason I couldn't get it to work. Anyhow, we are fortunate enough because the oauth plugin has a service that will enable us to interact with the APIs without the hot mess of putting jars in our lib folder. But first, let's learn how to interact with amazing docs that google provided us. Click here and you shall be redirected to the said page.
Scroll down, and you shall see a section that looks like the stuff above. Be sure to turn on the Oauth 2 request button, then hit on "Execute" button.

If the request was a success, the page will give you a URL that you can use for fetching the said calendar list. The response is right below the request URL. It is actually in JSON format, which pretty much does what we want. 

Copy the url that you have generated and add this somewhere in your controller. Notice that I used "getGoogleResource()" in retrieving a list of calendars. If I wanted to insert a new calendar, then I would use "postGoogleResource()". I will discuss postGoogleResource() on step 6.
import uk.co.desirableobjects.oauth.scribe.OauthService
import grails.converters.*
class CalendarController {
OauthService oauthService 
def grailsApplication


def getGoogleAccessToken() {
String sessionKey = oauthService.findSessionKeyForAccessToken('google')
return session[sessionKey]
}


def show(){
def calendars = oauthService.getGoogleResource(getGoogleAccessToken(), 'https://www.googleapis.com/calendar/v3/users/me/calendarList?key=${grailsApplication.config.oauth.providers.google.key}')
def calendarsJSON = JSON.parse(calendars.body)
render calendarsJSON
}

}
So, that's it! If all goes well, you shall see a page with the list of calendars and all the data associated with it. It is now up to you on how to manipulate the retrieved data! I've scoured google for tutorials regarding the manipulation of JSON responses. Click here to see the results!

Step 6:
This actually shouldn't be step 6. Lol, but I didn't know what to call it, so here it goes! If you wanted to perform inserts into Google's database, then we use "postGoogleResource()". In this example, I will insert a new calendar to the users array of calendars.

For me to find out the URL that I will supply, I went to this section of google reference site.


Here is a sample code on how to create a new calendar. Simply copy the url from above and create a new method for it. Of course, use "postGoogleResource()".
def createSSCMCalendar(){
String calendarSummary = "JJang Calendar"
String calendarTimeZone = "America/Los_Angeles"

oathService.postGoogleResource(getGoogleAccessToken(), 'https://www.googleapis.com/calendar/v3/calendars?fields=Csummary=${calendarSummary}%2CtimeZone=${calendarTimeZone}&key=${grailsApplication.config.oauth.providers.google.key}')
}

Alright! So that's just about it! You're welcome! If I have helped you, then please do like icodeya on facebook! It would mean a lot to me. :*

Written by

I am a software developer with 2 years of experience. I like cats. I like going to hackathons for free food and temporary lodging. I want to be a polyglot. Currently, I can speak languages like English, Korean, Java (it counts right?), Groovy, Ruby and C#. I aim to learn German as well.

 

© 2013 icodeya. All rights resevered.Designed by Templateism

Back To Top