Google Image Search API (Deprecated)

JSON Developer's Guide

The Google Image Search API JSON interface can be used to write image query applications in any language that can handle a JSON-encoded result set with embedded status codes.

Note: The Google Image Search API must be used for user-generated searches. Automated or batched queries of any kind are strictly prohibited.

Contents

  1. Audience
  2. Application requirements
  3. Using the JSON interface
    1. Sending a basic query
    2. Using the callback argument
    3. Using the context argument
  4. Code examples
    1. Using Flash
    2. Using Java
    3. Using PHP
    4. Using Python
    5. Using Perl
  1. JSON reference
    1. Request format
      1. URL base address
      2. URL arguments
    2. Response format
      1. Basic query
      2. Callback argument
      3. Context argument

Audience

The Google Image Search JSON interface, and this guide, are provided for Flash developers, and all other developers who need to access Image Search from other Non-JavaScript environments.

Application requirements

Applications that use this interface must abide by all existing Terms of Service. Most importantly, you must correctly identify yourself in your requests.

Query inputs and results must display "Powered by Google" branding, as described by .getBranding.

Requests can only be made on behalf of an end user. All results must be displayed.

Applications MUST always include a valid and accurate HTTP referer header in their requests.

Your application uses the userip parameter (not required, but highly encouraged). This parameter supplies the IP address of the end-user who made the request and validates that you are not making automated requests in violation of the Terms of Service.

Using the JSON interface

The easiest way to start learning about this interface is to try it out. This section shows how to use the curl command line tool to execute sample queries.

Sending a basic query

curl -e http://www.my-ajax-site.com \
'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=fuzzy%20monkey'

This command performs a image search (/ajax/services/search/images) for fuzzy monkey (q=fuzzy%20monkey). The response has a Content-Type of text/javascript; charset=utf-8.

{"responseData": {
 "results": [
  {
   "GsearchResultClass": "GimageSearch",
   "width": "450",
   "height": "450",
   "imageId": "Yt3TRC1vxzhazM",
   "tbWidth": "127",
   "tbHeight": "127",
   "unescapedUrl": "http://www.touchnote.com/files/assets/STAN009.jpg",
   "url": "http://www.touchnote.com/files/assets/STAN009.jpg",
   "visibleUrl": "www.touchnote.com",
   "title": "Touchnote - Personalised \u003cb\u003eFuzzy Monkey\u003c/b\u003e greeting cards design by Dan \u003cb\u003e...\u003c/b\u003e",
   "titleNoFormatting": "Touchnote - Personalised Fuzzy Monkey greeting cards design by Dan ...",
   "originalContextUrl": "http://www.touchnote.com/photo/card-design/Fuzzy+Monkey",
   "content": "Card Design \u003cb\u003eFuzzy Monkey\u003c/b\u003e",
   "contentNoFormatting": "Card Design Fuzzy Monkey",
   "tbUrl": "http://images.google.com/images?q\u003dtbn:Yt3TRC1vxzhazM:www.touchnote.com/files/assets/STAN009.jpg"
  },
  {
   "GsearchResultClass": "GimageSearch",
   "width": "640",
   "height": "480",
   "imageId": "c6093fGTdNvKOM",
   "tbWidth": "137",
   "tbHeight": "103",
   "unescapedUrl": "http://stuff.fuzzymonkeyphotography.com/front_page/NEW_NEW_logo3_480px.jpg",
   "url": "http://stuff.fuzzymonkeyphotography.com/front_page/NEW_NEW_logo3_480px.jpg",
   "visibleUrl": "www.fuzzymonkeyphotography.com",
   "title": "\u003cb\u003eFuzzy Monkey\u003c/b\u003e Photography",
   "titleNoFormatting": "Fuzzy Monkey Photography",
   "originalContextUrl": "http://www.fuzzymonkeyphotography.com/",
   "content": "Welcome to \u003cb\u003eFuzzy Monkey\u003c/b\u003e",
   "contentNoFormatting": "Welcome to Fuzzy Monkey",
   "tbUrl": "http://images.google.com/images?q\u003dtbn:c6093fGTdNvKOM:stuff.fuzzymonkeyphotography.com/front_page/NEW_NEW_logo3_480px.jpg"
  },
  {
   "GsearchResultClass": "GimageSearch",
   "width": "500",
   "height": "375",
   "imageId": "oKdBN2qxw5JJoM",
   "tbWidth": "130",
   "tbHeight": "98",
   "unescapedUrl": "http://farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg?v\u003d0",
   "url": "http://farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg%3Fv%3D0",
   "visibleUrl": "www.flickr.com",
   "title": "http://farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg?v\u003d0",
   "titleNoFormatting": "http://farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg?v\u003d0",
   "originalContextUrl": "http://www.flickr.com/photos/maryelizajade/1434841504/in/set-72157602146748073/",
   "content": "\u003cb\u003efuzzy monkey\u003c/b\u003e",
   "contentNoFormatting": "fuzzy monkey",
   "tbUrl": "http://images.google.com/images?q\u003dtbn:oKdBN2qxw5JJoM:farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg%3Fv%3D0"
  },
  {
   "GsearchResultClass": "GimageSearch",
   "width": "500",
   "height": "375",
   "imageId": "GNgM5anX5NZYPM",
   "tbWidth": "130",
   "tbHeight": "98",
   "unescapedUrl": "http://farm1.static.flickr.com/38/91607831_009166aa41.jpg",
   "url": "http://farm1.static.flickr.com/38/91607831_009166aa41.jpg",
   "visibleUrl": "www.flickr.com",
   "title": "\u003cb\u003eFuzzy monkey\u003c/b\u003e sad face on Flickr - Photo Sharing!",
   "titleNoFormatting": "Fuzzy monkey sad face on Flickr - Photo Sharing!",
   "originalContextUrl": "http://www.flickr.com/photos/ajagendorf25/91607831/",
   "content": "\u003cb\u003eFuzzy monkey\u003c/b\u003e sad face",
   "contentNoFormatting": "Fuzzy monkey sad face",
   "tbUrl": "http://images.google.com/images?q\u003dtbn:GNgM5anX5NZYPM:farm1.static.flickr.com/38/91607831_009166aa41.jpg"
  }
 ],
 "cursor": {
  "pages": [
   {
    "start": "0",
    "label": 1
   },
   {
    "start": "4",
    "label": 2
   },
   {
    "start": "8",
    "label": 3
   },
   {
    "start": "12",
    "label": 4
   },
   {
    "start": "16",
    "label": 5
   },
   {
    "start": "20",
    "label": 6
   },
   {
    "start": "24",
    "label": 7
   },
   {
    "start": "28",
    "label": 8
   }
  ],
  "estimatedResultCount": "578000",
  "currentPageIndex": 0,
  "moreResultsUrl": "http://www.google.com/images?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003dfuzzy+monkey"
 }
}
, "responseDetails": null, "responseStatus": 200}
    
    

Using the callback argument

In addition to this response format, the protocol also supports a classic JSON-P style callback which is triggered by specifying a callback argument. When this argument is present, the JSON object is delivered as an argument to the specified callback.

curl -e http://www.my-ajax-site.com \
'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=fuzzy%20monkey&callback=processResults'

This command performs a Image Search that is identical to the previous search, except that it has been altered to pass callback. With this argument in place, instead of a JSON object being returned, a Javascript call is returned in the response and the JSON object is passed via the results parameter.

processResults({"responseData": {
  "results": [
    ...            // results array
   ]
}});

Using the context argument

Finally, the protocol supports a context argument. When both callback and context are specified, the response is encoded as a direct JavaScript call with a signature of: callback(context, results, status, details, unused). Note the slight difference in the following command and response.

curl -e http://www.your-site-here.com \
'https://ajax.googleapis.com/ajax/services/search/images?v=1.0& \
q=fuzzy%20monkey&callback=processResults&context=foo'

This command performs a Image Search that is identical to the previous search, except that it has been altered to pass both callback and context. With these arguments in place, instead of a JSON object being returned, a JavaScript call is returned in the response and the JSON object is passed via the results parameter.

processResults('foo',{
 "results": [
   ...          // results array
 ]
});

Code examples

The following sections contain code snippets that show how to access the Image Search API from Flash, Java, PHP, Python, and Perl.

Warning: You should include the userip parameter, which supplies the IP address of the end-user who made the request and validates that you are not making automated requests in violation of the Terms of Service.

If you have trouble processing the JSON response, visit the JSON.org site, and pay particular attention to the second half of the page where various JSON libraries are referenced. See the JSON reference section below for details on how the Image Search API is made available through the JSON API.

Using Flash

The following code snippet shows how to make a request to the Google Image Search API using Flash. This example uses JSON from the ActionScript 3.0 (AS3) Core Library.

Note: This example works for Flex and AIR. For Flash, please use HTTP Client for AS3.

var service:HTTPService = new HTTPService();
service.url = 'https://ajax.googleapis.com/ajax/services/search/images';
service.request.v = '1.0';
service.request.q = 'fuzzy%20monkey';
service.resultFormat = 'text';
service.addEventListener(ResultEvent.RESULT, onServerResponse);

// Make sure to set 'allowScriptAccess' to 'sameDomain' or 'always' in your
// HTML include and import flash.external.ExternalInterface in this AS file.
if (ExternalInterface.available) {
try {
  service.headers['Referer'] = ExternalInterface.call("window.location.href.toString");
} catch (ignored:Error) {
  service.headers['Referer'] = "http://www.example.com";
}
}

service.addEventListener(ResultEvent.RESULT, onServerResponse);
service.send();

private function onServerResponse(event:ResultEvent):void {
  try {
    var json:Object = JSON.decode(event.result as String);
    // now have some fun with the results...
  } catch(ignored:Error) {
  }
}

Using Java

The following code snippet shows how to make a request to the Google Image Search API using Java. This example uses the JSON library from json.org.

URL url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" +
                  "v=1.0&q=barack%20obama&userip=INSERT-USER-IP");
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", /* Enter the URL of your site here */);

String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
 builder.append(line);
}

JSONObject json = new JSONObject(builder.toString());
// now have some fun with the results...

Using PHP

The following code snippet shows how to make a request to the Google Image Search API using PHP. This sample assumes PHP 5.2. For older installations of PHP, refer to this comment.

$url = "https://ajax.googleapis.com/ajax/services/search/images?" .
       "v=1.0&q=barack%20obama&userip=INSERT-USER-IP";

// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, /* Enter the URL of your site here */);
$body = curl_exec($ch);
curl_close($ch);

// now, process the JSON string
$json = json_decode($body);
// now have some fun with the results...

Using Python

The following code snippet shows how to make a request to the Google Image Search API using Python. This sample assumes Python 2.4 or higher. You may need to download and install simplejson.

import urllib2
import simplejson

url = ('https://ajax.googleapis.com/ajax/services/search/images?' +
       'v=1.0&q=barack%20obama&userip=INSERT-USER-IP')

request = urllib2.Request(url, None, {'Referer': /* Enter the URL of your site here */})
response = urllib2.urlopen(request)

# Process the JSON string.
results = simplejson.load(response)
# now have some fun with the results...

Using Perl

The following code snippet shows how to make a request to the Google Image Search API using Perl. This sample relies on the LWP::UserAgent and JSON modules which you can obtain from CPAN. You may also want to use the URI::Escape module.

#!/usr/bin/perl

my $url = "https://ajax.googleapis.com/ajax/services/search/images?" +
          "v=1.0&q=barack%20obama&userip=INSERT-USER-IP";

# Load our modules
# Please note that you MUST have LWP::UserAgent and JSON installed to use this
# You can get both from CPAN.
use LWP::UserAgent;
use JSON;

# Initialize the UserAgent object and send the request.
# Notice that referer is set manually to a URL string.
my $ua = LWP::UserAgent->new();
$ua->default_header("HTTP_REFERER" => /* Enter the URL of your site here */);
my $body = $ua->get($url);

# process the json string
my $json = from_json($body->decoded_content);

# have some fun with the results
my $i = 0;
foreach my $result (@{$json->{responseData}->{results}}){
 $i++;
 print $i.". " . $result->{titleNoFormatting} . "(" . $result->{url} . ")\n";
 # etc....
}
if(!$i){
 print "Sorry, but there were no results.\n";
}

JSON reference

Unlike the core JavaScript interface, the JSON interface is exposed through a uniform URL that contains CGI arguments. Your application can use an HTTP stack of its choosing. In order to use the JSON interface:

  • You must construct a properly formatted URL with all necessary CGI arguments.
  • You must send an HTTP referer header that accurately identifies your application.
  • You must process the JSON-encoded response.

Request format

URL base address

The standard URL for the Google Image Search API is:

https://ajax.googleapis.com/ajax/services/search/images

URL arguments

This section describes the arguments that can be used for Image Search requests.

The value of a CGI argument must always be properly escaped. This can be done via the functional equivalent of JavaScript's encodeURIComponent() method.

Required URL arguments

The following table lists the required URL arguments.

Argument

Example

Description

q

q=fuzzy%20monkey

This argument supplies the query, or search expression, that is passed into the searcher.

v

v=1.0

This argument supplies protocol version number. The only valid value at this point in time is 1.0.

Optional URL arguments

The following table lists the optional URL arguments.

Argument Example Description

as_filetype

as_filetype=jpg

Restricts image search to one of the following specific file types:

  • as_filetype=jpg restricts results to JPG images
  • as_filetype=png restricts results to PNG images
  • as_filetype=gif restricts results to GIF images
  • as_filetype=bmp restricts results to BMP images

as_rights

as_rights=cc_publicdomain

This optional argument tells the image search system to restrict the search to images labeled with the given licenses, where rights can be one or more of:

  • as_rights=cc_publicdomain restricts search results to images with the publicdomain label.
  • as_rights=cc_attribute restricts search results to images with the attribute label.
  • as_rights=cc_sharealike restricts search results to images with the sharealike label.
  • as_rights=cc_noncommercial restricts search results to images with the noncomercial label.
  • as_rights=cc_nonderived restricts search results to images with the nonderived label.

These restrictions can be used together, both positively or negatively. For instance, to emulate the commercial use with modification license, set the following:

&as_rights=(cc_publicdomain|cc_attribute|cc_sharealike).-(cc_noncommercial|cc_nonderived)

Note: Images returned with this filter may still have conditions on the license for use. Please remember that violating copyright is strictly prohibited by the API Terms of Service. For more details, see this article.

as_sitesearch

as_sitesearch=photobucket.com

Tells the image search system to restrict the search to images within the specified domain,such as as_sitesearch=photobucket.com.

Note: This method restricts results to images found on pages at the given URL.

callback

callback=foo

This argument alters the standard response format. When supplied, instead of producing a simple JSON-encoded object, the system produces a JavaScript function call response where the value of callback specifies the name of the function called in the response.

callbackFunction(
  {"responseData" : {
      "results" : [],
      "cursor" : {}
    },
    "responseDetails" : null | string-on-error,
    "responseStatus" : 200 | error-code
});

context

context=bar

This argument is related to the callback argument. When both are supplied, the value of context alters the normal response format associated with callback. The new format is:

callbackFunction(
  contextValue,    // the context arg value
  responseObject,  // the collection of results and cursor
  responseStatus,  // 200 on success, non-200 on failure
  errorDetails)    // error string for non-200 response

hl

hl=fr

This argument supplies the host language of the application making the request. If hl is present in the URL, it will be used. Otherwise, if the Accept-Language HTTP header is present, it will be used. If neither is specified, a value of en is assumed.

imgc

imgc=gray

This optional argument tells the image search system to restrict the search to images of the specified colorization, where colorization can be one of:

  • imgc=gray restricts results to grayscale images.
  • imgc=color restricts results to color images.

imgcolor (experimental)

imgcolor=black

Restricts results to images that contain a specified color predominantly:

  • imgcolor=black
  • imgcolor=blue
  • imgcolor=brown
  • imgcolor=gray
  • imgcolor=green
  • imgcolor=orange
  • imgcolor=pink
  • imgcolor=purple
  • imgcolor=red
  • imgcolor=teal
  • imgcolor=white
  • imgcolor=yellow

imgsz

imgsz=icon

Restricts the search to images of the specified size, where size can be one of:

  • imgsz=icon restricts results to small images
  • imgsz=small|medium|large|xlarge restricts results to medium-sized images
  • imgsz=xxlarge restricts results to large images
  • imgsz=huge restricts resykts to extra-large images

imgtype (experimental)

imgtype=face

Restricts the search to one of the following image types:

  • imgtype=face restricts results to images of faces.
  • imgtype=photo restricts results to photographic images.
  • imgtype=clipart restricts results to clipart images.
  • imgtype=lineart restricts results to line drawing images.

restrict

restrict=cc_attribute

This optional argument tells the image search system to restrict the search to images of the specified restriction:

  • restrict=cc_attribute restricts results to Creative Commons-attributed images.

rsz

rsz=4

This argument supplies an integer from 1–8 indicating the number of results to return per page.

safe

safe=active

Specifies the search safety level, which may be one of the following:

  • safe=active enables the highest level of safe search filtering.
  • safe=moderate enables moderate safe search filtering (default).
  • safe=off disables safe search filtering.

start

start=4

This argument supplies the start index of the first search result. Each successful response contains a cursor object (see below) which includes an array of pages. The start property for a page may be used as a valid value for this argument. For reference, a sample cursor object is shown below:

"cursor": {
  "pages": [[
    { "start": "0", "label": 1 },
    { "start": "4", "label": 2 },
    { "start": "8", "label": 3 },
    { "start": "12","label": 4 } ]],
  "estimatedResultCount": "48758",
  "currentPageIndex": 0,
  "moreResultsUrl": "http://www.google.com/search..."
}

userip

userip=192.168.0.1

This argument supplies the IP address of the end-user on whose behalf the request is being made. Requests that include it are less likely to be mistaken for abuse. In choosing to utilize this parameter, please be sure that you're in compliance with any local laws, including any laws relating to disclosure of personal information being sent.

Response format

Basic query

There are two major variations in the response format. When the callback and context arguments are not supplied, the response format is a simple JSON object:

{
  "responseData" : {
    "results" : [],
    "cursor" : {}
  },
  "responseDetails" : null | string-on-error,
  "responseStatus" : 200 | error-code
}

In the JSON fragment above, note that the responseData property contains a results array and an optional cursor.

cursor

.cursor is an optional property that is present once a search completes successfully. When present, the property specifies how an application can request additional search results for the current query term, the estimated result count, the current page, and the URL for a search results page. The property has the following structure:

  • pages[] supplies an array used by start in order to iterate through all available results. Each entry in the array is an object with the following structure:
    • start supplies the value that will be used in the &start URL argument to request a bundle of results
    • label supplies a text label associated with the entry (for example, "1", "2", "3", or "4")
  • estimatedResultCount supplies the estimated number of results that match the current query. This value will not necessarily match the similar value that is visible on the Google.com search properties.
  • currentPageIndex supplies the index into the pages array of the current set of results.
  • moreResultsUrl supplies a URL to a Google-hosted search page that contains additional search results.

Note: The Image Searcher supports a maximum of 8 result pages. When combined with subsequent requests, a maximum total of 64 results are available. It is not possible to request more than 64 results.

results[]

.results[] contains an array of search result objects, one for each result. Each time a search executes, this property is cleared, and each time a search completes, the array is populated. If there are no results to report, the .length property of this array will be set to 0. Therefore, results will never be null, and you can always safely check for results.length == 0.

  • The GimageResult object is produced by google.search.ImageSearch. It is available in that object's .results[] array.
  • This object is indicated by a .GsearchResultClass value of google.search.ImageSearch.RESULT_CLASS.

Results array: guaranteed fields

The results array always contains the parameters listed in this section, even if the value is empty.

Property Description

content

Supplies a brief snippet of information from the page associated with the image result.

contentNoFormatting

Supplies the same information as .content, only stripped of HTML formatting.

GsearchResultClass

Indicates the type of result (for example, google.search.ImageSearch.RESULT_CLASS indicates GimageResult).

height

Supplies the height of the image in pixels.

html

Supplies the root of an HTML element that may be cloned and attached somewhere into the application's DOM hierarchy. We expect that this is the primary property that applications will use, typically by cloning this node and attaching it to the DOM hierarchy.

We expect applications to control styling, as well as which elements are displayed, using CSS. For instance, we expect the following fragment to be common across all applications that wish to copy and paste search results delivered through the Image Search API.

// clone the .html node from the result
var node = result.html.cloneNode(true);

// attach the node into my dom
container.appendChild(node);

originalContextUrl

Supplies the URL of the page containing the image.

tbHeight

Supplies the height, in pixels, of the image thumbnail.

tbUrl

Supplies the URL of a thumbnail image.

tbWidth

Supplies the width, in pixels, of the image thumbnail.

title

Supplies the title of the image, which is usually the base filename (for example, monkey.png.

titleNoFormatting

Supplies the page title associated with the search result, but unlike .title, this property is stripped of HTML markup (e.g., <b>, <i>, etc.).

unescapedUrl

Supplies the raw URL (containing non-alphanumeric characters) to an image in the result set. For example:

http://farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg?v\u003d0

url

Provides the encoded URL to an image file in the result set. For example:

http://farm2.static.flickr.com/1104/1434841504_edc671e65c.jpg%3Fv%3D0

visibleUrl

Supplies a shortened version of the URL associated with the result, typically displayed in green and stripped of a protocol and path.

width

Supplies the width of the image in pixels.

The responseStatus property contains a value of 200 on success and a non-200 HTTP error status code on failure. If there is a failure, responseDetails contains a diagnostic string.

Callback argument

Applications can use the callback argument as follows to request a JavaScript callback.

callback({
  "responseData" : {
    "results" : [],
    "cursor" : {}
  },
  "responseDetails" : null | string-on-error,
  "responseStatus" : 200 | error-code
});

Context argument

The context argument must always be specified in conjunction with the callback argument. If the application supplies both callback and context arguments, the response is encoded as a JavaScript procedure call. In this mode of operation:

  • The value of callback becomes the procedure call target.
  • The value of context is passed as the first argument.
  • The value of responseData from above is passed as the second argument.
  • The response status is passed as the third argument.
  • The final argument is either null or a diagnostic string.
processResults(for',{
 "results": [[
  {
   ...
  },
  {
   ...
  },
  ...
 ]],
 "cursor": {
  "pages": [[
   ...
  ]],
  "estimatedResultCount": "n",
  "currentPageIndex": n,
  "moreResultsUrl": "..."
 }
}
, 200 | error-code, null | string-on-error)

Troubleshooting

If you encounter problems with your code:

  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Use a JavaScript debugger. In Firefox, you can use the JavaScript console or the Firebug. In IE, you can use the Microsoft Script Debugger.
  • If you need to examine the JSON string returned from the server, you can use JSON Lint to make a single, long string human readable.
  • Search the API discussion group. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.