Connect to Google API with Powershell

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.

Google API Powershell

 

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 864312357012-ftkcasd2f23123plh0tfivvsvasd32123k6b.apps.googleusercontent.com , paste it in the following URL and open it in your browser:

# Replace <CLIENT_ID_HERE> with your client id
https://accounts.google.com/o/oauth2/auth?redirect_uri=<CLIENT_ID_HERE>&scope=https://www.googleapis.com/auth/analytics.readonly&approval_prompt=force&access_type=offline

# In the comments below, Phani mentioned that the above url is wrong and should be:
https://accounts.google.com/o/oauth2/auth?client_id=<replacemewithclientid>&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code&redirect_uri=<replacemewithredirecturi>&access_type=offline&approval_prompt=force

# 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 https://www.googleapis.com/oauth2/v4/token.  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

$requestUri = "https://www.googleapis.com/oauth2/v4/token"

$body = @{
	code=<authcode>;
	client_id=<clientId>;
	client_secret=<clientSecret>;
	redirect_uri=<redirectUrl>;
	grant_type="authorization_code"; # Fixed value
};

$tokens = Invoke-RestMethod -Uri $requestUri -Method POST -Body $body;

# Store refreshToken
Set-Content $PSScriptRoot"\refreshToken.txt" $tokens.refresh_token

# Store accessToken
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:

$refreshTokenParams = @{
	client_id=$clientId;
  	client_secret=$clientSecret;
	refresh_token=$refreshToken;
	grant_type="refresh_token"; # Fixed value
}

$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 https://developers.google.com/oauthplayground/ and https://developers.google.com/apis-explorer/

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

# Request URL for Analytics Realtime and requesting the activeUsers
$viewId = 12345678 (Get it from the analytics admin page > view settings)
$requestUri = "https://www.googleapis.com/analytics/v3/data/realtime?ids=ga:$viewId&metrics=rt:activeUsers"

Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $requestUri -Method GET -ContentType 'application/json'

Update: Check this Google Api Explorer: https://ga-dev-tools.appspot.com/query-explorer/. It generates an API Query URI for you.

Get more stuff like this

IT, Office365, Smart Home, PowerShell and Blogging Tips

I hate spam to, so you can unsubscribe at any time.

6 thoughts on “Connect to Google API with Powershell”

  1. I was continually getting bad requests using the methods given, including after using the corrected url. The following worked for me to get the access and refresh tokens

    $clientID = “”
    $clientSecret = “”
    $redirectUrl = “”
    $scope = “”

    # Replace with your client id
    $authUrl = “https://accounts.google.com/o/oauth2/auth?redirect_uri=$redirectUrl&client_id=$clientID&scope=$scope&approval_prompt=force&access_type=offline&response_type=code”

    $authUrl | clip
    # Copy the generated url into your browser
    PAUSE

    $responseCode = “

    $requestUri = “https://www.googleapis.com/oauth2/v3/token”

    $body = “code=$([System.Web.HttpUtility]::UrlEncode($responseCode))&redirect_uri=$([System.Web.HttpUtility]::UrlEncode($redirectUrl))&client_id=$clientID&client_secret=$clientSecret&scope=$scope&grant_type=authorization_code”

    $tokens = Invoke-RestMethod -Uri $requestUri -Method POST -Body $body -ContentType “application/x-www-form-urlencoded”

  2. Great, thank you.

    Can you please take the answer from “phani kumar yelisetty” into the document. It take me a long time testing with errors bevor i found it ūüôā

  3. I’m in the middle of implementing this guidance. This has clearly shortened my time to follow the instructions @ https://developers.google.com/youtube/v3/guides/auth/installed-apps

    One pitfall, that I did hit was that the -requestUri in the “Refreshing the access token” section is NOT the same as in “Getting the access and refresh tokens”. When obtaining the new access token using the refresh token, one must use https://www.googleapis.com/oauth2/v4/token as the value for -requestUri

  4. hi rudy, thank you for the great article. it sure did help me. but the url mentioned to get the initial code didn’t work for me. what worked was

Leave a Comment