Search Console URL Testing Tools API Samples

Sample code is often the easiest way to learn how to use an API. For links to Search Console URL Testing Tools API samples, select a programming language below.

The samples use the Google API client libraries.

If a library's samples page does not yet include a sample for the Search Console URL Testing Tools API, you can still use that library, and you might be able to adapt samples that are provided for a different Google API.

Go

There are no Go samples specifically for this version of the Search Console URL Testing Tools API.

However, you may be able to adapt one of the other Go samples.

Java

package codesamples;

import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;

/** Example of Java client calling Search Console URL Testing Tools API */
public final class MftExample {
  public static void main(String[] args) {
    try {
      HttpTransport httpTransport = new NetHttpTransport();
      HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
      GenericUrl url = new GenericUrl(
          "https://searchconsole.googleapis.com/v1/urlTestingTools/mobileFriendlyTest:run"
          + "?key={YOUR_API_KEY}");
      JSONObject json = new JSONObject();
      json.put("url", "https://www.google.com/");
      String requestBody = json.toString();
      HttpRequest request = requestFactory.buildPostRequest(
          url, ByteArrayContent.fromString("application/json", requestBody));
      System.out.println("request was: " + requestBody);
      HttpResponse httpResponse = request.setReadTimeout(70000).execute();

      String content = httpResponse.parseAsString();
      System.out.println(content);
    } catch (IOException | JSONException ex) {
      ex.printStackTrace();
    }
  }
}

JavaScript

<!DOCTYPE html>
<html>
<head>
<script>
function listMobileFriendlyIssues(responseJson) {
  var resultEl = document.getElementById('result');
  if (responseJson.mobileFriendlyIssues) {
    resultEl.innerHTML += "Mobile friendly issues:<br>";
    responseJson.mobileFriendlyIssues.forEach(function(issue) {
        resultEl.innerHTML += "<li>" + issue.rule + "</li>"});
  } else {
    resultEl.innerHTML += "No mobile friendliness issues found!";
  }
}
function runInspection() {
  var apiUrl = 'https://searchconsole.googleapis.com/v1/urlTestingTools/mobileFriendlyTest:run?key={YOUR_API_KEY}';
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST", apiUrl);
  xmlhttp.setRequestHeader("Content-Type", "application/json");
  xmlhttp.send(
      '{"url": "' + document.getElementById("url").value + '", "requestScreenshot": true}');
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4) {
      var responseJson = JSON.parse(this.responseText);
      if (this.status == 200) {
        listMobileFriendlyIssues(responseJson);
        document.getElementById('image').src =
            "data:" + responseJson.screenshot.mimeType + ';base64,' + responseJson.screenshot.data;
      } else {
        document.getElementById('result').innerHTML += "An error occured!<br>Error code: "
            + responseJson.error.code + "<br>Error message: " + responseJson.error.message;
      }
    }
  };
};
</script>
</head>
<body>
<br>URL: <input type="text" id="url" size="40">
<br><br><button onclick="runInspection();">Fetch</button>
<br><br>Result:
<div id="result" style="border: solid thin black; height:5em; overflow:auto;"></div>
Screenshot:
<img id="image" style="border: solid thin black;"/>
</body>
</html>

PHP

There are no PHP samples specifically for this version of the Search Console URL Testing Tools API.

However, you may be able to adapt one of the other PHP samples.

Python

"""Example of Python client calling Search Console URL Testing Tools API."""
import urllib
import urllib2

api_key = '{YOUR_API_KEY}'
request_url = 'http://www.google.com/'
service_url = 'https://searchconsole.googleapis.com/v1/urlTestingTools/mobileFriendlyTest:run'
params = {
    'url': request_url,
    'key': api_key,
}
data = urllib.urlencode(params)
content = urllib2.urlopen(url=service_url, data=data).read()
print content

Ruby

There are no Ruby samples specifically for this version of the Search Console URL Testing Tools API.

However, you may be able to adapt one of the other Ruby samples.