Google+ API Search with C# 5


GooglePlusLarge

Have you been trying to connect your website or application to Google+? Do you want to show a search for users or postson Google Plus?   If you are you trying to work with the Google+ api in C# .net I might be able to help.   Lets have a look all at that now.

Three part Tutorial Series

  1. Google+ API List with C# –  List (Articles, People, comments)
  2. Google+ API Get with C#  – Get (Article, Person, comment)
  3. Google+ API Search with C#  – Search (Articles and People)

Restringing your application.

Like with most of the Google APIs you need to be authenticated in order to connect to them. To do that you must first register your application on Google Developer console.   Under APIs be sure to enable the Google+ API, as always don’t forget to add a product name and email address on the  consent screen form.

Project Setup

Make sure your project is at least set to .net 4.0.

Add the following NuGet Package

PM> Install-Package Google.Apis.Plus.v1

You will probably need most of these using’s

using System;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Plus.v1;
using System.Threading;
using Google.Apis.Util.Store;
using Google.Apis.Services;
using Google.Apis.Plus.v1.Data;
using System.Collections.Generic;
using System.Linq;

Authentication

Authentication is the key to everything here. If you want to be able to access data you will need to be authenticated. The code for authentication simply displays a webpage for your user asking them to give you permission to access there data. If the user gives you permission a file is then stored on the machine in the %AppData% directory containing all the information you will need in the future to access there data.

That’s just fine but how does Google know what kind of permission you want to ask the user for? That’s where scopes come in, with scopes you define what permissions you need.

In the code below we ask the user to give us access to some basic information about there user-profile, there email address and the standard stuff for login.

string[] scopes = new string[] {PlusService.Scope.PlusLogin,
 PlusService.Scope.UserinfoEmail,
 PlusService.Scope.UserinfoProfile};
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = 
        GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets {ClientId = _client_id,
                                                                  ClientSecret = _client_secret },
                                                    scopes,
                                                    Environment.UserName,
                                                    CancellationToken.None,
                                                new FileDataStore("Daimto.GooglePlus.Auth.Store")
                                                    ).Result;

Assuming the user clicks Accept and gives you permission you will then have a valid user credential you can build upon.

Google plus Service

The service is where all of the magic is. It is though the service that all of the calls will be made to the Google plus API.

// Now we create a Google service. All of our requests will be run though this.
PlusService service = new PlusService(new BaseClientService.Initializer(){
                                      HttpClientInitializer = credential,
                                      ApplicationName = "Google Plus Sample",
                                       });

Notice how we pass our credential to it.

Requesting Data

Activities

An Activity on Google+ is basically a post.   When you search activities a list of all of the posts that match your query string is returned.

When you search for Google+ activities you can max return 100 Google+ posts at a time.    If you want to see more then 100 Google+ activities from the API,  you must get the next batch in the list until you have fetched all of the Google+ posts available for a person.    It can take some time to get all of the activities returned to you, it is best to really only return the most resent ones unless for some reason you want to see everything they have posted.

//List all of the activities in the specified collection for the current user.  
// Documentation: https://developers.google.com/+/api/latest/activities/list
ActivitiesResource.SearchRequest list = service.Activities.Search(_query);
list.MaxResults = 100;
ActivityFeed activitesFeed = list.Execute();
IList Activites = new List();
//// Loop through until we arrive at an empty page
while (activitesFeed.Items != null)
{
  // Adding each item  to the list.
  foreach (Activity item in activitesFeed.Items)
    {
       Activites.Add(item);
    }

  // We will know we are on the last page when the next page token is
  // null.
  // If this is the case, break.
  if (activitesFeed.NextPageToken == null)
    {
       break;
    }

   // Prepare the next page of results
   list.PageToken = activitesFeed.NextPageToken;

   // Execute and process the next page request
   activitesFeed = list.Execute();

}

People

Now people are basically just that people with accounts on Google plus.   You can search on people in Google plus, this will return a list of people.

Like when you search for Google+ activities on a person you can max return 50 Google+ people at a time.    If you want to see more then 50 Google+ people from the API,  you must get the next batch in the list until you have fetched all of the Google+ people available for a person.

PeopleResource.SearchRequest list = service.People.Search(_query);
list.MaxResults = 50;
PeopleFeed peopleFeed = list.Execute();
IList people = new List();

//// Loop through until we arrive at an empty page
while (peopleFeed.Items != null)
   {
   // Adding each item  to the list.
    foreach (Person item in peopleFeed.Items)
       {
         people.Add(item);
        }

   // We will know we are on the last page when the next page token is
   // null.
   // If this is the case, break.
   if (peopleFeed.NextPageToken == null)
      {
         break;
      }

    // Prepare the next page of results
    list.PageToken = peopleFeed.NextPageToken;

    // Execute and process the next page request
    peopleFeed = list.Execute();

}

Comments

The API doesn’t allow us to search on Comments. Can you think of how many results we would get back if we could?

Concision

You should now understand how to access the Google+ API with an authenticated user. You should also understand the idea behind using NextPageToken to get the next set of results back. I hope you will also agree that working with the Google APIs is quite easy once you get the authentication down.

Blog authors who like to make people happy and help them enjoy working with the Google APIs.   Release the code to go along with this tutorial on GitHub


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

5 thoughts on “Google+ API Search with C#

  • Prince

    I had problem implementing the code.
    GoogleWebAuthorizationBroker when using this it always return redirect_uri_mismatch and also random port everytime.

    What if the user is already authenticate thru OWIN how to configure the credential?

    Thanks !

  • Bikram

    Hi,

    Is it possible to just use oAuth Access Token in order to use client API?, user will already be authenticated and have access token.
    I couldn’t find a way to call API using access token.

    I am working on .net web api 2, and trying to access other information about user.

    • Linda Lawton Post author

      calling any API with an access token you should just be able to add &access_token={the token} it works with most of the API endpoints. Documentation says &key={access token} its lying trust me 🙂