Quickstart: Run a Search Console App in Java

Complete the steps described in the rest of this page, and you'll have a simple Search Console app that fetches a list of sites verified in your Search Console account and lists any sitemap files submitted.

To run a quickstart example you'll need:

  • Access to the internet and a web browser, in order to authorize the sample app.
  • A Google account with at least one website verified in Google Search Console.
  • An environment to run programs in your selected language.

Step 1: Enable the Search Console API

To get started using Google Search Console API, you need to first use the setup tool, which guides you through creating a project in the Google API Console, enabling the API, and creating credentials.

  1. From the Credentials page, click Create credentials > OAuth client ID to create your OAuth 2.0 credentials or Create credentials > Service account key to create a service account.
  2. If you created an OAuth client ID, then select your application type.
  3. Fill in the form and click Create.

Your application's client IDs and service account keys are now listed on the Credentials page. For details, click a client ID; parameters vary depending on the ID type, but might include email address, client secret, JavaScript origins, or redirect URIs.

Take note of the Client ID as you'll need to add it to your code later.

Step 2: Install the Google Client Library

To install the Google API Java Client, you must download two ZIP files, extract them, and then copy the JARs into your Java classpath.

  1. Download the Google Search Console API Java client library, which is bundled as a ZIP file with all the required dependencies.
  2. Extract the ZIP file
  3. Add all of the JARs within the libs directory to your classpath.
  4. Add the google-api-services-webmaster-tools-v3.jar jar to your classpath.

If you are using Eclipse, see here for instructions on adding JARs to your project's classpath.

If you are using NetBeans, see here for instructions on adding JARs to your project's classpath.

If you are using IntelliJ IDEA, see here for instructions on adding JARs to your project's classpath.

If developing from the command line, add -classpath /path/to/directory/with/unzipped/jars to your javac and java command invocations.

Step 3: Set up the sample

The next step is to copy and modify some sample code so that it can authenticate with the unique Client ID and Client Secret you created in the "Enable the Search Console API" step.

  1. After following the directions below to copy source code, replace YOUR_CLIENT_ID with the Client ID you generated in the "Enable the Search Console API" step.
  2. Replace YOUR_CLIENT_SECRET with your Client Secret, also generated previously.

Copy the following source code to WebmastersCommandLine.java. If using an IDE, such as Eclipse, Netbeans, or IntelliJ IDEA, make sure to set up a project first before creating the file.

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;

import com.google.api.services.webmasters.Webmasters;
import com.google.api.services.webmasters.model.SitesListResponse;
import com.google.api.services.webmasters.model.WmxSite;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;


public class WebmastersCommandLine {

  private static String CLIENT_ID = "YOUR_CLIENT_ID";
  private static String CLIENT_SECRET = "YOUR_CLIENT_SECRET";

  private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

  private static String OAUTH_SCOPE = "https://www.googleapis.com/auth/webmasters.readonly";

  public static void main(String[] args) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(OAUTH_SCOPE))
        .setAccessType("online")
        .setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
    System.out.println("Please open the following URL in your browser then type the authorization code:");
    System.out.println("  " + url);
    System.out.println("Enter authorization code:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String code = br.readLine();

    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

    // Create a new authorized API client
    Webmasters service = new Webmasters.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("WebmastersCommandLine")
        .build();

    List<String> verifiedSites = new ArrayList<String>();
    Webmasters.Sites.List request = service.sites().list();

    // Get all sites that are verified
    try {
      SitesListResponse siteList = request.execute();
      for (WmxSite currentSite : siteList.getSiteEntry()) {
        String permissionLevel = currentSite.getPermissionLevel();
        if (permissionLevel.equals("siteOwner")) {
          verifiedSites.add(currentSite.getSiteUrl());
        }
      }
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
    }

    // Print all verified sites
    for (String currentSite : verifiedSites) {
      System.out.println(currentSite);
    }
  }
}

Step 4: Run the sample

After you have Enabled the API in the Google Developers Console, installed the Google API client library, and set up the sample source code, the sample is ready to run. When you run the sample from command-line, it provides a link you'll need to visit in order to authorize.

If you're using an IDE, make sure you have a default run target set that targets the WebmastersCommandLine class. Alternately, run the sample from the command line using the following steps:

  1. Compile the sample using:

    javac -classpath /path/to/google/lib/*:/path/to/google/lib/libs/* WebmastersCommandLine.java
    
  2. Run the sample using:

    java -classpath ./:/path/to/google/lib/*:/path/to/google/lib/libs/* WebmastersCommandLine
    
  3. Browse to the provided URL in your web browser.

  4. If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.
  5. Copy the code you're given after browsing to the link, and paste it into the prompt Enter authorization code:. Click Enter.

When you finish these steps, the sample prints the URLs of all verified sites in your Search Console account.

Next Steps

If your goal is to expand the quickstart sample into something for your own installed application, consult the API Reference. The API Reference discusses all of the features of the Search Console API.