Set Up Your Application

Before you can make requests to the API, you must set up authorization. If you are using a client library, you must also create a Service object.

The following code demonstrates how to configure your client and authorize requests using OAuth 2.0 for installed applications.

For a brief overview of authorization, read about how to authorize requests and identify your application to Google.

Java

import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

...

  public void setUp() throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();

    // Go to the Google API Console, open your application's
    // credentials page, and copy the client ID and client secret.
    // Then paste them into the following code.
    String clientId = "YOUR_CLIENT_ID";
    String clientSecret = "YOUR_CLIENT_SECRET";

    // Or your redirect URL for web based applications.
    String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";
    String scope = "";

    // Step 1: Authorize -->
    String authorizationUrl = new GoogleAuthorizationRequestUrl(clientId, redirectUrl, scope)
        .build();

    // Point or redirect your user to the authorizationUrl.
    System.out.println("Go to the following link in your browser:");
    System.out.println(authorizationUrl);

    // Read the authorization code from the standard input stream.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("What is the authorization code?");
    String code = in.readLine();
    // End of Step 1 <--

    // Step 2: Exchange -->
    AccessTokenResponse response = new GoogleAuthorizationCodeGrant(httpTransport, jsonFactory,
        clientId, clientSecret, code, redirectUrl).execute();
    // End of Step 2 <--

    GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
        response.accessToken, httpTransport, jsonFactory, clientId, clientSecret,
        response.refreshToken);

     service = new (httpTransport, accessProtectedResource, jsonFactory);
    service.setApplicationName("YOUR_APPLICATION_NAME");
    ...
  }
...

Python

import gflags
import httplib2

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

FLAGS = gflags.FLAGS

# Set up a Flow object to be used if we need to authenticate. This
# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
# the information it needs to authenticate. Note that it is called
# the Web Server Flow, but it can also handle the flow for
# installed applications.
#
# Go to the Google API Console, open your application's
# credentials page, and copy the client ID and client secret.
# Then paste them into the following code.
FLOW = OAuth2WebServerFlow(
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    scope='',
    user_agent='YOUR_APPLICATION_NAME/YOUR_APPLICATION_VERSION')

# To disable the local server feature, uncomment the following line:
# FLAGS.auth_local_webserver = False

# If the Credentials don't exist or are invalid, run through the
# installed application flow. The Storage object will ensure that,
# if successful, the good Credentials will get written back to a
# file.
storage = Storage('info.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
  credentials = run(FLOW, storage)

# Create an httplib2.Http object to handle our HTTP requests and
# authorize it with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)

# Build a service object for interacting with the API. To get an API key for
# your application, visit the Google API Console
# and look at your application's credentials page.
service = build(serviceName='', version='v1', http=http,
       apiKey='YOUR_API_KEY')

PHP

Edit the src/config.php file to add information about your application.

global $apiConfig;

$apiConfig = array(
  // Site name to show in Google's OAuth authentication screen
  'site_name' => 'www.example.org',

  // OAuth 2.0 setting.
  //
  // Go to the Google API Console, open your application's
  // credentials page, and copy the client ID, client secret,
  // redirect URI, and API key. Then paste them into the
  // following code.
  'oauth2_client_id' => 'YOUR_CLIENT_ID',
  'oauth2_client_secret' => 'YOUR_CLIENT_SECRET',
  'oauth2_redirect_uri' => 'YOUR_REDIRECT_URL',

  'api_key' => 'YOUR_API_KEY',
  ...

  // Which Authentication, Storage, and HTTP IO classes to use.
  'authClass' => 'apiOAuth2',
  ....

  // Definition of service-specific values such as scopes, OAuth
  // token URLs, etc.
  'services' => array(
      '' => array('scope' => ''),
  )
);

Invoke the Google Ad Experience Report API service and authenticate:

<?php
session_start();

require_once "../src/apiClient.php";


$apiClient = new apiClient();
$service = new ($apiClient);

if (isset($_SESSION['oauth_access_token'])) {
  $apiClient->setAccessToken($_SESSION['oauth_access_token']);
} else {
  $token = $apiClient->authenticate();
  $_SESSION['oauth_access_token'] = $token;
}
...

.NET

using System;
using System.Diagnostics;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;

using Google.Apis.Util;

...

  public static void Main(string[] args)
  {
    // Register the authenticator.
    //
    // Go to the Google API Console, open your application's
    // credentials page, and copy the client ID and client secret.
    // Then paste them into the following code.
    var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
    provider.ClientIdentifier = "YOUR_CLIENT_ID";
    provider.ClientSecret = "YOUR_CLIENT_SECRET";
    var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication);

    // Create the service and register the previously created
    // OAuth2Authenticator.
    var service = new (auth);

      ...
  }

  private static IAuthorizationState GetAuthentication(NativeApplicationClient arg)
  {
    // Get the auth URL:
    IAuthorizationState state = new AuthorizationState(new[] { .Scopes..GetStringValue() });
    state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
    Uri authUri = arg.RequestUserAuthorization(state);

    // Request authorization from the user (by opening a browser
    // window):
    Process.Start(authUri.ToString());
    Console.Write("  Authorization Code: ");
    string authCode = Console.ReadLine();
    Console.WriteLine();

    // Retrieve the access token by using the authorization code:
    return arg.ProcessUserAuthorization(authCode, state);
  }
...