Skip to main content

We are going to connect to the Google API with OAuth2.0 and the Powershell Invoke-RestMethod cmdlet. Before we can start scripting in Powershell we first need to get a ClientId, ClientSecret, AuthCode and finally the Access and Refresh tokens. It took me half a day to figure out how to connect to where to get what, so I hope you guys (and girls) can get up and running within 10 minutes.

Getting the Google API access and refresh tokens

Go to Google Developers Console and create a new project by clicking on the top bar on API Project and then the + to create a new project. Give your project a name and click create. When you are done, click again on API Project, click all and select your newly created project.

You will see the empty dashboard, we need to select which API we want to interact with, I want to get Real Time Analytics data so I selected the Analytics API. Click Enable after which you will be redirected back to the dashboard.

As stated on the dashboard, click on Create Credentials and enter the following:

  • Which API are you using?  > The one you have chosen earlier
  • Where will you be calling the API from? > Webbrowser (Javascript)
  • What data will you be accessing? > User data
  • Authorized redirect URIs > http://localhost/oauth2callback  ! Important
  • Fill in a name for you  OAuth 2.0 client ID, does not matter what.
  • Create the OAuth 2.0 consent screen and click done. We will get the credentials from the credentials page.

Getting an Authorization code

With the authorization code, we can get the access and refresh tokens. We only need these ones, so I have taken the easy way by just opening the endpoint in the browser, authenticate and crap the code from the address bar.

First, we need the ClientId, so go to the Credential page and copy the clientId. It looks like , paste it in the following URL and open it in your browser:

1.  # Replace <CLIENT_ID_HERE> with your client id
4.  # In the comments below, Phani mentioned that the above url is wrong and should be:
7.  # I have no time to test it, but if you get an error with the original URL, then check the one mentioned by Phani.

Make sure you use the same redirect URL’s which we set when we created the credentials. http://localhost/oauth2callback

After you authenticated, you will be redirected to http://localhost/oauth2callback?code=4/QhUXhB*********_***********u8jKZkjhsd2# . Copy the code without the # at the end and store it somewhere, we will need it later.
This code is only one hour valid and if the access token request later fails somehow, you will need to get a new authentication code. So keep that in mind.

Getting the access and refresh tokens

To exchange the Authorization code for the tokens, we will use Powershell to do make a call to  Fill in Authorization code, ClienId, Client Secret and redirect Uri from the Google Developer Console and run the script. It will store the two tokens in the text files so you can use them later on

1.  $requestUri = ""
3.  $body = @{
4.    code=<authcode>;
5.    client_id=<clientId>;
6.    client_secret=<clientSecret>;
7.    redirect_uri=<redirectUrl>;
8.    grant_type="authorization_code"; # Fixed value
9.  };
11. $tokens = Invoke-RestMethod -Uri $requestUri -Method POST -Body $body;
13. # Store refreshToken
14. Set-Content $PSScriptRoot"\refreshToken.txt" $tokens.refresh_token
16. # Store accessToken
17. Set-Content $PSScriptRoot"\accessToken.txt" $tokens.access_token

Refreshing the access token

The access token is only valid for one hour, so you will need get a new one with the refresh token. The refresh token from Google does not expire so store it in a secure place. Use the call below to get a new accesstoken:

1.  $refreshTokenParams = @{
2.    client_id=$clientId;
3.      client_secret=$clientSecret;
4.    refresh_token=$refreshToken;
5.    grant_type="refresh_token"; # Fixed value
6.  }
8.  $tokens = Invoke-RestMethod -Uri $requestUri -Method POST -Body $refreshTokenParams

Retrieving data from Google API

So now we have the tokens we can get data from Google. To get started take a look at and

To give you an example, this is how to retrieve the current (real time) users from Analytics:

1.  # Request URL for Analytics Realtime and requesting the activeUsers
2.  $viewId = 12345678 (Get it from the analytics admin page > view settings)
3.  $requestUri = "$viewId&metrics=rt:activeUsers"
5.  Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $requestUri -Method GET -ContentType 'application/json'

Update: Check this Google Api Explorer: It generates an API Query URI for you.