Glasser
← All posts

Glasser Team8 min read

How to Use a Google Image Search API with Python

Use Python to retrieve Google image results. Check existing-customer access, compare the Glasser path, and retain image URLs, source pages and limits.

An amber magnifying glass stands in front of ceramic and amber picture frames with mountain scenes.

Which Google image search API can you use today?

For an existing Google Custom Search JSON API customer, Python can request image results with searchType=image. New customers cannot join that API, and Google says existing customers must transition by January 1, 2027. Check your eligibility before following a tutorial that tells you to create a new API project. Google's current API overview

For a new workflow that needs Google image results, Glasser's Serper image-search operation provides another access path. It uses the Serper contract through Glasser. Google's cx, pagination and response fields do not transfer to it.

This guide covers text queries that discover images, including their source pages. Image-to-image matching belongs to reverse-image search. Documentation was checked on October 12, 2026. The Python example is tested offline; it has not been sent to a live Google or Glasser account.

Prepare your query and access credentials

Confirm your existing Google access

The direct Google example requires an API key and a Programmable Search Engine ID, cx, configured for image search. It assumes Python 3.10 or later and the requests package. Keep GOOGLE_API_KEY and GOOGLE_CSE_ID in the server environment; supply your text query as IMAGE_QUERY.

Google returns JSON over HTTP. The request uses key, cx, q and searchType=image; without the image search type, the request is for web results. REST usage · Query parameter reference

Prepare a Glasser request for a new project

Open the Serper image endpoint and inspect its current schema, version and price. Its public schema accepts q, optional country/language codes gl and hl, and num between 1 and 20:

{
  "q": "aurora borealis",
  "gl": "us",
  "hl": "en",
  "num": 10
}

The provider/endpoint pair is serper:/images. These fields are the operation's own contract; a Google Custom Search engine ID is not part of this input. Glasser's public page does not publish a stable output schema, so retain the first authorized response before designing a field mapper.

Search for images with Python

Run the direct Google example with existing access

Install the dependency in a virtual environment:

python -m venv .venv
source .venv/bin/activate
python -m pip install requests

Save the following as image_search.py. It retrieves one bounded page and separates a missing result list from a malformed response. Credentials and full request URLs are kept out of printed errors.

import json
import os
import sys
import requests


def search_images(query, key, cx, get=requests.get):
    if not all(isinstance(x, str) and x.strip()
               for x in (query, key, cx)):
        raise ValueError("Query, API key and engine ID are required")
    params = {
        "key": key, "cx": cx, "q": query.strip(),
        "searchType": "image", "num": 10, "safe": "active",
    }
    try:
        response = get(
            "https://customsearch.googleapis.com/customsearch/v1",
            params=params, timeout=(5, 30), allow_redirects=False,
        )
    except requests.RequestException:
        raise RuntimeError("Image search transport failed") from None
    if response.status_code != 200:
        raise RuntimeError(f"Image search HTTP {response.status_code}")
    try:
        payload = response.json()
    except ValueError:
        raise RuntimeError("Image search returned invalid JSON") from None
    if not isinstance(payload, dict) or "error" in payload:
        raise RuntimeError("Unexpected image-search response")
    items = payload.get("items", [])
    if not isinstance(items, list):
        raise RuntimeError("Unexpected items field")
    rows = []
    for item in items:
        if not isinstance(item, dict):
            raise RuntimeError("Unexpected image result")
        details = item.get("image", {})
        if not isinstance(details, dict):
            raise RuntimeError("Unexpected image metadata")
        rows.append({
            "title": item.get("title"),
            "image_url": item.get("link"),
            "source_page": details.get("contextLink"),
            "thumbnail_url": details.get("thumbnailLink"),
            "width": details.get("width"),
            "height": details.get("height"),
        })
    return rows


if __name__ == "__main__":
    try:
        result = search_images(
            os.environ.get("IMAGE_QUERY", ""),
            os.environ.get("GOOGLE_API_KEY", ""),
            os.environ.get("GOOGLE_CSE_ID", ""),
        )
        print(json.dumps(result, ensure_ascii=False, indent=2))
    except (ValueError, RuntimeError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)

Set the three environment variables privately, then run python image_search.py. An empty JSON array means this successful response contained no items. It does not prove that no matching images exist elsewhere. The extracted fields follow Google's Search response reference.

Use the Glasser route from your Python workflow

For serper:/images, inspect the endpoint first, then prepare a Run body using its returned version and the input shown above. Submit it to POST https://api.glasser.ai/v1/runs with Bearer authentication and an Idempotency-Key kept for that intended execution. The body has this structure; replace the version with the value from Inspect:

{
  "provider": "serper",
  "endpoint": "/images",
  "endpoint_version": 2,
  "input": {"q": "aurora borealis", "num": 10}
}

Version 2 is the dated public-page example, not a promise of the current default. Read status, provider_response and charge_usd before using output. The complete inspect/save/run Python pattern in the Google Patents Python guide can be adapted by changing the endpoint and input; do not reuse its task-specific assumptions or invent an image-array field. Glasser Inspect · Run reference

Read image results and adapt the request to other languages

Preserve the image's surrounding page

The direct Google example keeps three separate URLs: the image file, the page containing it and the thumbnail. Use the source page to review context and the applicable reuse conditions before selecting an asset. A thumbnail may be convenient for a review interface but should not silently replace the original image URL.

The normalized names image_url and source_page are fields chosen by this example. Google's original fields are link and image.contextLink. Missing dimensions remain null; the code does not estimate them or download image files.

Keep the provider request in your backend

JavaScript, PHP and C use the same HTTP parameters for the chosen provider. An Android app can call your own backend, which owns the credential and usage controls. This architecture is an application recommendation; Glasser does not automatically create that backend for you.

RuntimeAdaptation point
Server-side JavaScriptUse fetch, encode query parameters with URLSearchParams, check HTTP status before JSON parsing
PHPUse cURL, encode query parameters, set connection and response timeouts, then decode JSON
CUse an HTTP library such as libcurl and a JSON parser; keep transport errors distinct from empty results
AndroidSend the user's query to an authenticated backend; return only the fields the app needs

For Google, retain searchType=image in each implementation. For Glasser, use the inspected Run body and response contract instead. Changing the programming language does not change service eligibility, quota or permitted inputs.

Handle result limits and failed searches

Keep result count separate from query allowance

Google's request reference permits num from 1 to 10. It caps retrieval at 100 results per query and documents a start + num boundary; follow that rule when adding pagination. The example deliberately requests one page. A second page is another API request, and a reported total does not mean every matching image can be downloaded through the API. Google request limits

Existing customers' published allowance is 100 queries per day, with additional billed requests subject to the API's limits and discontinuation date. This allowance belongs to Google Custom Search. Glasser's Serper operation has its own price, result count and empty-result terms. Google pricing and lifecycle

Diagnose the request before retrying

ObservationWhat to check
Google HTTP errorAccount eligibility, key restrictions, engine configuration, quota and the provider's error details
Successful response with no itemsQuery, engine scope and filters; retain the empty result
JSON or schema errorResponse content and current reference; stop mapping until understood
Missing source page or dimensionsPreserve missing values and review the returned item
Glasser Run still in progressGet the same Run by ID
Glasser provider errorInspect the provider response and charge separately

The example avoids automatic retries. If you add them, choose a bounded policy appropriate to the provider; never turn an integration error into an empty image list. A Google billing allowance also does not renew access after the announced shutdown.

Frequently asked questions

Can I start using Google's Custom Search JSON API today?

Google says it is closed to new customers. Existing customers have until January 1, 2027 to transition, so verify your account's access and migration plan before investing in this integration.

It sends a text query and asks for image results. Finding matches for an uploaded image or an image URL requires a separately documented reverse-image operation.

Can I use Google's response fields for Serper through Glasser?

Inspect the selected operation and an authorized sample response first. Glasser's public Serper image endpoint does not guarantee a stable output schema, so Google's items field mapping cannot be assumed.

Does a returned image come with reuse permission?

A search result provides a discovery path and source context. Review the source page and applicable license before reusing the asset; the script does not perform that review.

Where can I compare image-data sources?

The image search API guide covers source selection and access models. Use this article for implementing the chosen Google-oriented query path.