Categories
Web Development

How do I access Google API data using ASP.NET?

Want to Support Me?
Get two free stocks valued up to $1,850 when you open a new Webull investment account through my referral link and fund the account with at least $100!

Have you tried to access your Google Analytics data (or other Google data) using ASP.NET? After hours of research, I finally figured out how, and it’s very simple!

I just want to say that Google’s documentation for using their APIs with .NET was not very user-friendly. I found myself clicking from article to article, and they all explain a small piece of the puzzle, but none of them put the whole puzzle together. It was an exercise in frustration.

Take the Analytics Reporting API Overview page. There are no .NET examples, even though they provide entire libraries just for .NET. Finally, I found the Google Analytics Reporting API Client Library for .NET. From there, click to go to the Developer’s guide for the Google API Client Library for .NET.

Feel free to read all their content, as it will give a lot of extra detail. But in this post, I’m going to focus specifically on getting connected to Google’s API using .NET.

Connection

It’s helpful to start by reading through the information at OAuth 2.0 page for .NET. You can connect to Google’s API in two ways:

  1. OAuth2 (via a UserCredential)
  2. Service account (via a ServiceAccountCredential)

You should use OAuth2 if you are accessing someone else’s account, or use a service account if you are accessing an account you own.

In my case, I wanted to access an account I own, so a service account is what I needed. They include a .NET code sample on that page for connecting with a service account, but let’s first go over how to create the service account.

Service Account

To create a Service Account that can access your data via the API, go to the Google APIs Credentials page and click Create Credentials, then choose Service account key.

Click Create Credentials to create a new service account key

Once there, select New service account, and give it a name and role (Project -> Owner if you don’t know what roles are). The Service account ID should be auto-filled out for you based on the name you gave. Use JSON for the Key type, and that should do it.

It should immediately try to save the JSON key file, so save that to your computer. If you need to manage your service account later, go back to the Credentials page and click Manage service accounts.

If you open the JSON key file, it will look something like this:

{
  "type": "service_account",
  "project_id": "foo-1250",
  "private_key_id": "foobar669foo7e7bar776foo4a4baref3afoobar",
  "private_key": "-----BEGIN PRIVATE KEY-----\n[LONG KEY GOES HERE]\n-----END PRIVATE KEY-----\n",
  "client_email": "foobar@foo-1250.iam.gserviceaccount.com",
  "client_id": "123456789071965638796",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/foobar%40foo-1250.iam.gserviceaccount.com"
}

Nuget Packages

Next, get the Google API Nuget packages. I was interested in the Google Analytics API, so I searched for Google.Apis.AnalyticsReporting.v4. Once you click to install that, it should download all necessary dependencies.

.NET Code

We’re finally to the code! The first thing you need to do is put the JSON key file in a location accessible by your project. I placed mine in the ~/App_Data folder.

We also need to get the text out of that JSON file into a format we can use. The easiest way I found to do this was to create a simple class that mimics the structure of the key’s JSON, and let Newtonsoft’s Json.NET do the deserialization.

Include this class in your project:

public class PersonalServiceAccountCred
{
    public string type { get; set; }
    public string project_id { get; set; }
    public string private_key_id { get; set; }
    public string private_key { get; set; }
    public string client_email { get; set; }
    public string client_id { get; set; }
    public string auth_uri { get; set; }
    public string token_uri { get; set; }
    public string auth_provider_x509_cert_url { get; set; }
    public string client_x509_cert_url { get; set; }
}

Once you’ve got that in place, let’s go ahead and look at a full example!

string keyFilePath = Server.MapPath("~/App_Data/Your-API-Key-Filename.json");
string json = System.IO.File.ReadAllText(keyFilePath);
 
var cr = JsonConvert.DeserializeObject(json);

var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
{
    Scopes = new[] {
        AnalyticsReportingService.Scope.Analytics
    }
}.FromPrivateKey(cr.private_key));
                
using (var svc = new AnalyticsReportingService(
    new BaseClientService.Initializer
    {
        HttpClientInitializer = xCred,
        ApplicationName = "[Your Application Name]"
    })
)
{
    // Create the DateRange object.
    DateRange dateRange = new DateRange() { StartDate = "2017-05-01", EndDate = "2017-05-31" };
 
    // Create the Metrics object.
    Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };
 
    //Create the Dimensions object.
    Dimension browser = new Dimension { Name = "ga:browser" };
 
    // Create the ReportRequest object.
    ReportRequest reportRequest = new ReportRequest
    {
        ViewId = "[A ViewId in your account]",
        DateRanges = new List() { dateRange },
        Dimensions = new List() { browser },
        Metrics = new List() { sessions }
    };
 
    List requests = new List();
    requests.Add(reportRequest);
 
    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };
 
    // Call the batchGet method.
    GetReportsResponse response = svc.Reports.BatchGet(getReport).Execute();
}

You can see that we used JsonConvert to convert from the raw JSON to our PersonalServiceAccount class, so the cr object will contain all information about your service account key. It then creates a ServiceAccountCredential, initializes the connection, and voila! You can continue with preparing the API request to get the data you want. I included some sample code to get data from Google Analytics just to get you started.

Your Turn!

Have you tried connecting to a Google API with .NET before? How was your experience? Let me know in the comments below!

Please let me know if you have any questions or comments or if this post was helpful to you. Thanks for reading!

Want to Support Me?
Get two free stocks valued up to $1,850 when you open a new Webull investment account through my referral link and fund the account with at least $100!