Google Data API with RestSharp on WP7

RestSharp is an open source REST client for .NET. I will use it for consuming Google Data API. You can easily install via the following NuGet command

Install-Package RestSharp

First step is creating an application in API Console and selecting services that you will be using. In this example, we will use the Tasks API. Once you create your project with the appropriate settings, you will need client_id and client_secret which is available on the API Access page.

All requests in RestSharp are made using the RestClient class.

RestClient _clientOAuth = new RestClient("https://accounts.google.com");
RestClient _clientTask = new RestClient("https://www.googleapis.com");

First step is authorizing your application and retrieving the device code. To do that, we will use the following code:

// create the request
request = new RestRequest("/o/oauth2/device/code", Method.POST);
request.AddParameter("client_id", client_id);
request.AddParameter("scope", "https://www.googleapis.com/auth/tasks");

// async execution
_clientOAuth.ExecuteAsync(request, (response) =>
    {
        // convert the JSON object into JObject
        var obj = JObject.Parse(response.Content);
        IsolatedStorageSettings.ApplicationSettings["device_code"] = obj["device_code"].ToString();
        IsolatedStorageSettings.ApplicationSettings["expires_in"] = obj["expires_in"].ToString();
        IsolatedStorageSettings.ApplicationSettings["interval "] = obj["interval"].ToString();
        IsolatedStorageSettings.ApplicationSettings.Save(); // do not forget this 🙂

        // this will help users fill the form
        Clipboard.SetText(obj["user_code"].ToString());

        _device_code = obj["device_code"].ToString();

        // you can also embed the web browser control in one of your pages
        var task = new WebBrowserTask()
        {
            Uri = new Uri(obj["verification_url"].ToString(), UriKind.Absolute)
        };
        task.Show();
    });

Once you have device code, you will forward the user to the authorization page where he will authorize your app. Since user_code is copied on the clipboard, the user can simply paste the code inside the browser (visible on the images below).

Now you need to get access tokens using the retrieved device_code.

request = new RestRequest("/o/oauth2/token", Method.POST);
request.AddParameter("client_id", client_id);
request.AddParameter("client_secret", client_secret);
request.AddParameter("code", _device_code);
request.AddParameter("grant_type", grant_type);

_clientOAuth.ExecuteAsync(request, (response) =>
    {
        Dispatcher.BeginInvoke(() =>
        {
            var obj = JObject.Parse(response.Content);

            _access_token = obj["access_token"].ToString();
            _refresh_token = obj["refresh_token"].ToString();
            IsolatedStorageSettings.ApplicationSettings["access_token"] = _access_token;
            IsolatedStorageSettings.ApplicationSettings["refresh_token"] = _refresh_token;
            IsolatedStorageSettings.ApplicationSettings.Save();
        });
    });

You will now have two tokens:

  • access_token – use to authorize requests.
  • refresh_token – use to refresh token after it expires

Using the access token, we can now retrieve the list of all tasks lists in our account by using the following code:

RestRequest("/tasks/v1/users/@me/lists", Method.GET);
request.AddHeader("Authorization", "Bearer " + _access_token);

_clientTask.ExecuteAsync(request, (response) =>
    {
        Dispatcher.BeginInvoke(() =>
            {
                var obj = JObject.Parse(response.Content);
                var items = obj["items"] as JArray;
                if (items != null)
                {
                    foreach (var item in items)
                    {
                        tbContent.Text += item["title"] + Environment.NewLine;

                        GetTasksFromList(item["id"].ToString());
                    }
                }
            });
    });

Check out the API reference for additional operations exposed by the REST API for Google Tasks.

Advertisements

About programabilan

Profesionalni programer, amaterski programer...

Posted on January 21, 2012, in Development and tagged , , , , . Bookmark the permalink. 2 Comments.

  1. Hi!

    Thanks for writing this. A couple notes on how you’re using it. First, you don’t have to do the Dispatcher.BeginInvoke wrapper, that’s handled automatically on Windows Phone and the callbacks are always executed on the calling thread. Secondly, you should look into the Deserialization features, they make it so you don’t have to do the JSON parsing manually: https://github.com/restsharp/RestSharp/wiki/Deserialization

  2. HI, thanks for the comment.

    I will try using that deserialization and see what I can get. Regarding the Dispatcher, in some other callback scenarios I had to use it since they were not called on the instantiating thread. It was a matter of habit mostly.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s