How to Search Google Images Programmatically (Python and Node.js)
Michael Carter · · 21 min read

Key takeaways
- One BestSERP /images request returned 100 Google Images results for 1 credit on November 18, 2026, each with the full-size imageUrl, its width and height, Google's thumbnail, the site name, the domain and the hosting page.
- There is no size, color or usage-rights parameter, so filter in code: of 100 results for "lighthouse", 42 were at least 1,200 px wide and 16 were also at least 1.5 times as wide as tall.
- A Google Images result tells you nothing about an image's license: Google's own help page tells you to confirm the license before reusing an image, and the license lives with the image's owner.
- Keeping only results that link to a Wikimedia Commons file page, then reading each license with the Commons API, turned 200 results into 51 candidates and 50 files under public domain, CC0, CC BY or CC BY-SA.
- Google's Custom Search JSON API, the official route with an image search mode and a rights filter, is closed to new customers and ends for existing ones on January 1, 2027.
To search Google Images programmatically, send the query to an image search API and read the results as JSON. One BestSERP /images request returns about 100 images, each with the full-size image URL, its width and height, a thumbnail and the page that shows it. No result tells you an image's license, so check that separately before reusing anything.
This tutorial is for developers who need image results in code, for research, datasets, SEO checks or pictures they may publish. You get tested Python and Node.js clients with error handling, real output, size and site filters, and a license check that ends with one photo we could credit and use. Everything ran on November 18, 2026; for the other result types, see our guide to local search data.
What you get back from a Google Images search
Each image is one JSON object with nine fields. BestSERP, a Google SERP API, runs a live Google Images search for your query, country (gl) and language (hl) and returns images[] (/images reference, Google Images API page). The first of 100 results for "lighthouse":

| Field | What it is | Use it for |
|---|---|---|
imageUrl |
The full-size file on the host's server | Downloading only what you are allowed to use |
imageWidth, imageHeight |
Pixel size of that file | Filtering by size and shape |
thumbnailUrl |
Google's small copy (gstatic.com in all 100 results) | Previews in internal tools |
title, source |
Title of the image or its page, and the site name | Labels, grouping |
domain, link |
Host name and URL of the page that shows the image | Context, credit, the license check |
position |
Rank in Google Images, from 1 | Image SEO tracking |
What we measured on November 18, 2026:
- All nine fields on all 100 results, for 1 credit in 4.2 seconds, and every
linkalready a final URL. domainkeptwww.on 65 of the 100, although the docs say it comes without it. Strip it before comparing sites.- Page 2 lacked the image fields. With
pages: 2, two requests returned 200 results for 2 credits, but results 101 to 200 had onlytitle,source,domainandlink. Use page 1 for image URLs and sizes.
Google's own image search options
Google has no API for Google Images results that new customers can sign up for in November 2026. Its Custom Search JSON API had an image mode: the `cse.list` method takes searchType=image, size filters such as imgSize and a rights filter (cc_publicdomain, cc_attribute...), with 10 results per call. But its overview page says "The Custom Search JSON API is closed to new customers", and existing customers "have until January 1, 2027 to transition to an alternative solution" (last updated 2026-02-18, checked 2026-11-18). For new projects it suggests Vertex AI Search "for searching up to 50 domains", or contacting Google about full web search.
Our Custom Search JSON API migration guide maps searchType=image to /images; our overview of official Google search APIs covers the rest.
In the browser, Google Images has a Usage rights filter. Google's help page Find images you can use & share says it filters "based on information provided by the sites that host those images" and asks you to "make sure that its license is legitimate and check the exact terms of reuse". BestSERP has no such filter, so this guide filters in code and checks licenses at the source.
Prerequisites
- Python 3.12 with
pip install requests pillow, or Node.js 18+ for the built-infetch. We tested Python 3.12.10 (requests 2.34.2, Pillow 13.0.0) and Node.js 22.17.1. - An API key: sign up for 3,000 free searches (valid 30 days), then $0.50 per 1,000 (pricing). The quickstart shows where to create it.
- The key in an environment variable, never in code:
export BESTSERP_API_KEY=YOUR_API_KEY(macOS, Linux) or$env:BESTSERP_API_KEY = "YOUR_API_KEY"(PowerShell).
Every example below costs 6 credits in total; refused requests (400) are free.
Search Google Images programmatically with Python
Send a POST with the query and read images from the JSON. The function below also polls 202 answers and retries the errors worth retrying, so you can call it from a batch job. Save it as images.py:
# images.py: tested 2026-11-18 with Python 3.12.10 and requests 2.34.2
import json
import os
import sys
import time
import requests
API = "https://api.bestserp.com"
RETRY = {429, 502, 503} # rate limited (not charged), search failed or busy (both refunded)
session = requests.Session()
session.headers["X-API-KEY"] = os.environ["BESTSERP_API_KEY"]
class ImageSearchError(Exception):
def __init__(self, r):
try:
error = r.json().get("error", {})
except ValueError: # an HTML page from a gateway, not the API's JSON
error = {"code": "gateway", "message": r.reason}
super().__init__(f"{r.status_code} {error.get('code')}: {error.get('message')}")
self.status = r.status_code
def search_images(q, gl="us", hl="en", pages=1, tries=3, **params):
"""POST /images. Polls 202, retries 429/502/503, raises ImageSearchError otherwise."""
body = {"q": q, "gl": gl, "hl": hl, "pages": pages, **params}
for attempt in range(1, tries + 1):
r = session.post(f"{API}/images", json=body, timeout=130)
if r.status_code == 202: # still running: poll (free, not rate limited)
request_id = r.json()["requestId"]
print(f"202, polling /requests/{request_id}", file=sys.stderr)
while r.status_code == 202:
time.sleep(2)
r = session.get(f"{API}/requests/{request_id}", timeout=130)
if r.status_code == 200:
return r.json()
error = ImageSearchError(r)
if r.status_code in RETRY and attempt < tries:
wait = float(r.headers.get("Retry-After", 2 ** attempt))
print(f"{error}; retry {attempt} in {wait:.0f} s", file=sys.stderr)
time.sleep(wait)
continue
raise error
if __name__ == "__main__":
query = sys.argv[1] if len(sys.argv) > 1 else "lighthouse"
pages = int(sys.argv[2]) if len(sys.argv) > 2 else 1
data = search_images(query, pages=pages)
if len(sys.argv) > 3: # keep the raw JSON: filter it later without paying again
with open(sys.argv[3], "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=1)
images = data["images"]
print(f"{len(images)} images | credits: {data['credits']} | cached: {data['cached']}"
f" | ipCountry: {data.get('ipCountry')} | {data['durationMs']} ms")
for img in images[:5]:
size = f"{img.get('imageWidth', '?')}x{img.get('imageHeight', '?')}"
print(f"{img['position']:>3} {size:>9} {img.get('domain', '-'):<24} {img['title'][:44]}")
Run python images.py "lighthouse" 1 lighthouse.json. Our output:
100 images | credits: 1 | cached: False | ipCountry: us | 4198 ms
1 4843x3217 en.wikipedia.org Pigeon Point Lighthouse - Wikipedia
2 720x960 www.beaverdamwoodworks.com What Do Lighthouses Symbolize? 13 Things Lig
3 640x793 www.visitrhodeisland.com Rhode Island Lighthouses | Historic Landmark
4 1200x674 www.bbc.co.uk Five incredible lighthouses from around the
5 1600x1098 www.britannica.com Lighthouse | Definition, History, Equipment,
Save the raw JSON: you will filter the same results several ways, and a repeated request costs credits even when it comes from cache. Our Python guide to Google search results explains the requests patterns used here.
The same search in Node.js
Node.js 18 and newer ship fetch, so the client needs no packages. Same structure: POST, poll 202, retry 429, 502 and 503, throw on anything else. Save it as images.mjs:
// images.mjs: tested 2026-11-18 with Node.js 22.17.1, no packages
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
const API = "https://api.bestserp.com";
const RETRY = new Set([429, 502, 503]); // rate limited (not charged), search failed or busy (both refunded)
const headers = { "X-API-KEY": process.env.BESTSERP_API_KEY, "Content-Type": "application/json" };
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function errorOf(res) {
const text = await res.text();
try {
const { error = {} } = JSON.parse(text);
return `${res.status} ${error.code}: ${error.message}`;
} catch {
return `${res.status} gateway: ${res.statusText || "not JSON"}`; // an HTML page from a gateway, not the API's JSON
}
}
export async function searchImages(q, { gl = "us", hl = "en", pages = 1, tries = 3, ...params } = {}) {
const body = JSON.stringify({ q, gl, hl, pages, ...params });
for (let attempt = 1; attempt <= tries; attempt++) {
let res = await fetch(`${API}/images`, { method: "POST", headers, body, signal: AbortSignal.timeout(130_000) });
if (res.status === 202) { // still running: poll (free, not rate limited)
const { requestId } = await res.json();
console.error(`202, polling /requests/${requestId}`);
while (res.status === 202) {
await sleep(2000);
res = await fetch(`${API}/requests/${requestId}`, { headers, signal: AbortSignal.timeout(130_000) });
}
}
if (res.ok) return res.json();
const error = await errorOf(res);
if (RETRY.has(res.status) && attempt < tries) {
const wait = Number(res.headers.get("retry-after") ?? 2 ** attempt);
console.error(`${error}; retry ${attempt} in ${wait} s`);
await sleep(wait * 1000);
continue;
}
throw new Error(error);
}
}
if (process.argv[1] === fileURLToPath(import.meta.url)) { // run as a script, not imported
const [query = "lighthouse", pages = "1", out] = process.argv.slice(2);
const data = await searchImages(query, { pages: Number(pages) });
if (out) writeFileSync(out, JSON.stringify(data, null, 1)); // keep the raw JSON for later filtering
const { images, credits, cached, ipCountry, durationMs } = data;
console.log(`${images.length} images | credits: ${credits} | cached: ${cached} | ipCountry: ${ipCountry} | ${durationMs} ms`);
for (const img of images.slice(0, 5)) {
const size = `${img.imageWidth ?? "?"}x${img.imageHeight ?? "?"}`;
console.log(`${String(img.position).padStart(3)} ${size.padStart(9)} ${(img.domain ?? "-").padEnd(24)} ${img.title.slice(0, 44)}`);
}
}
We ran it with two pages, node images.mjs "lighthouse" 2 lighthouse-2.json, 40 seconds after the Python run:
200 images | credits: 2 | cached: false | ipCountry: us | 8919 ms
1 4843x3217 en.wikipedia.org Pigeon Point Lighthouse - Wikipedia
2 720x960 www.beaverdamwoodworks.com What Do Lighthouses Symbolize? 13 Things Lig
3 640x793 www.visitrhodeisland.com Rhode Island Lighthouses | Historic Landmark
4 1200x674 www.bbc.co.uk Five incredible lighthouses from around the
5 1600x1098 www.britannica.com Lighthouse | Definition, History, Equipment,
The count says 200, but only the first 100 results had imageUrl, imageWidth, imageHeight and thumbnailUrl, which is why the code reads them with ?? instead of assuming they exist. The Node.js integration page has the minimal request if you only need one call.
Handling errors: 202, 429, 502 and 503
Both clients treat each status the way the errors page recommends:
| Status | Meaning | What the code does | Charged? |
|---|---|---|---|
202 |
Not finished within the request's timeout |
Polls GET /requests/{requestId} every 2 s (async requests) |
Reserved; refunded if it fails |
429 |
More than 60 searches in a minute | Waits Retry-After, retries |
No |
502 |
Google blocked the search or it timed out | Waits Retry-After or 2 s, then 4 s, retries |
Refunded |
503 |
No capacity right now | Waits Retry-After, retries |
Refunded |
400, 401, 402 |
Your parameters, key or balance | Raises at once | No |
One trap is specific to images: Google Images filters are not parameters. We sent four refused requests (free) and forced a real 202 by setting the API's timeout to 1 second:
from images import ImageSearchError, search_images
for bad in ({"imgSize": "large"}, {"rights": "cc_publicdomain"}, {"num": 20}, {"pages": 6}):
try:
search_images("lighthouse", **bad)
except ImageSearchError as e: # 400s are never charged and never retried
print(f"{bad} -> {e}")
# timeout is the API's parameter (1-120 s): answer 202 if the search is not done after 1 second
data = search_images("fresnel lens", timeout=1)
print(f"{len(data['images'])} images | credits: {data['credits']} | durationMs: {data['durationMs']}")
{'imgSize': 'large'} -> 400 unknown_parameter: Unknown parameter: imgSize
{'rights': 'cc_publicdomain'} -> 400 unknown_parameter: Unknown parameter: rights
{'num': 20} -> 400 unsupported_parameter: num is not supported for images; use pages (1-5)
{'pages': 6} -> 400 invalid_request: pages must be between 1 and 5
202, polling /requests/336b95dd-aaec-47b8-bb23-33ba088737b9
100 images | credits: 1 | durationMs: 5331
A real 429 needs more than 60 searches in a minute and a 502 cannot be ordered, so we tested those branches against a local stub with scripted answers (no credits). Both clients logged this for "429, 503, 202 twice, then 200", and both gave up after three 502 answers, waiting 2 and 4 seconds:
429 rate_limited: Too many requests; retry 1 in 1 s
503 busy: No capacity right now; retry 2 in 1 s
202, polling /requests/req-1
Filtering by size and source
Filter after the search: there is no size or usage-rights parameter, but every page-1 result has the pixel size and the host site. This runs on the saved JSON, so it costs nothing:
# filter_images.py: tested 2026-11-18 with Python 3.12.10 (standard library only)
import json
import sys
from collections import Counter
STOCK = {"shutterstock.com", "istockphoto.com", "gettyimages.com", "alamy.com", "dreamstime.com",
"stock.adobe.com", "123rf.com", "depositphotos.com"}
def site(img):
return img.get("domain", "").removeprefix("www.") # image results often keep www.
def wide_enough(img, min_width=1200, min_ratio=1.5):
"""At least 1200 px wide and landscape (1.5:1 or wider), e.g. for a wide page header."""
w, h = img.get("imageWidth", 0), img.get("imageHeight", 0)
return w >= min_width and h > 0 and w / h >= min_ratio
def pick(images, block=STOCK, per_site=1):
seen_urls, per = set(), Counter()
for img in images:
url = img.get("imageUrl")
if not url or url in seen_urls or not wide_enough(img) or site(img) in block:
continue
if per[site(img)] >= per_site: # one image per site keeps the list varied
continue
seen_urls.add(url)
per[site(img)] += 1
yield img
if __name__ == "__main__":
images = json.load(open(sys.argv[1], encoding="utf-8"))["images"]
with_url = [i for i in images if i.get("imageUrl")]
print(f"{len(images)} results, {len(with_url)} with an image URL")
print(f"at least 1200 px wide: {sum(i.get('imageWidth', 0) >= 1200 for i in with_url)}")
print(f"landscape 1.5:1 or wider and 1200+ px: {sum(wide_enough(i) for i in with_url)}")
print("top sites:", ", ".join(f"{s} {n}" for s, n in Counter(map(site, images)).most_common(4)))
picked = list(pick(images))
print(f"picked {len(picked)} (no stock sites, one per site):")
for img in picked[:8]:
print(f"{img['position']:>3} {img['imageWidth']}x{img['imageHeight']:<5} {site(img):<22} {img['title'][:40]}")
100 results, 100 with an image URL
at least 1200 px wide: 42
landscape 1.5:1 or wider and 1200+ px: 16
top sites: en.wikipedia.org 4, tripadvisor.com 4, nps.gov 3, britannica.com 2
picked 15 (no stock sites, one per site):
1 4843x3217 en.wikipedia.org Pigeon Point Lighthouse - Wikipedia
4 1200x674 bbc.co.uk Five incredible lighthouses from around
6 1600x1015 britannica.com Lighthouse | Definition, History, Equipm
12 2009x524 thecopperhouse.com Lighthouses – The Copper House
14 2000x1333 latimes.com Can this historic California lighthouse
23 2000x1331 uslhs.org USA Stars & Lights | United States Light
38 1605x1070 montereyboats.com National Lighthouse Day | Monterey Boats
46 3840x1920 history.com What Destroyed the Lighthouse of Alexand
The same rule applied to the first 12 results, drawn as data cards (no images reproduced):

Source filters work the same way: block or allow sites with site(img), or group by site to see which domains own the image results for a keyword. In Node.js, Object.groupBy (Node 21+) does the grouping:
// filter.mjs: tested 2026-11-18 with Node.js 22.17.1
import { readFileSync } from "node:fs";
const { images } = JSON.parse(readFileSync(process.argv[2], "utf8"));
const site = (img) => (img.domain ?? "").replace(/^www\./, "");
const usable = images.filter((img) => img.imageUrl); // check: not every result carries the image fields
const large = usable.filter((img) => img.imageWidth >= 1200 && img.imageWidth / img.imageHeight >= 1.5);
const bySite = Object.groupBy(large, site); // Node.js 21+
console.log(`${images.length} results, ${usable.length} with imageUrl, ${large.length} landscape and 1200+ px wide`);
for (const [name, list] of Object.entries(bySite).slice(0, 5)) {
console.log(`${name.padEnd(22)} ${list.map((i) => `${i.imageWidth}x${i.imageHeight}`).join(", ")}`);
}
200 results, 100 with imageUrl, 18 landscape and 1200+ px wide
en.wikipedia.org 4843x3217, 8155x5436
bbc.co.uk 1200x674
britannica.com 1600x1015
thecopperhouse.com 2009x524
latimes.com 2000x1333
Using images legally: licenses and attribution
A search result tells you nothing about an image's license. It says where a file is, how big it is and which page shows it; the right to reuse it belongs to whoever owns it. So when you search Google Images programmatically, treat every result as a lead to check, not as permission. This is general information, not legal advice.
Where license information exists, the publisher supplies it. Sites can add image license metadata (license, creditText, creator and more), which can earn a Licensable badge in Google Images (page last updated 2025-12-10), and the Usage rights filter relies on the same kind of information. The /images response does not include it.
Licenses you can work with
The Creative Commons licenses differ in what they require. For a company blog, we accept four and skip the rest:
| License | What it allows | What you must do | Our rule |
|---|---|---|---|
| Public domain, CC0 | Any use, even commercial, without asking | Nothing; a credit gives provenance | Accept (check which countries the page names) |
| CC BY | Reuse and adapt, commercially too | Credit the creator | Accept |
| CC BY-SA | The same as CC BY | Credit; share adaptations alike | Accept |
| CC BY-NC (and NC-SA, NC-ND) | Noncommercial use only | Credit | Skip |
| CC BY-ND | Unadapted copies only | Credit | Skip |
| Fair use, non-free, no license | Nothing you can rely on | Ask the owner | Skip |
Copyright is not the only right in a picture. The CC0 deed notes that it does not affect publicity or privacy rights, so we also skip photos with identifiable people.
Step by step: a license check with Wikimedia Commons
Wikimedia Commons states each file's license on its file page in a form code can read, which makes it a good source to search through:
- Search
/imageswith a query that favors Commons, such as "lighthouse wikimedia commons". - Keep only results whose
linkis acommons.wikimedia.org/wiki/File:page. Gallery and category pages show many files under different licenses. - Read each license with the Commons API:
prop=imageinfowithiiprop=extmetadatareturns "formatted metadata combined from multiple sources" (API:Imageinfo), for up to 50 titles per call. - Keep allowed licenses, and drop files with a
Restrictionsvalue (such as personality rights) or aDeletionReason(CommonsMetadata fields). - Open the file page of the image you will use and read its license and credit instruction yourself.
- Download the original from
upload.wikimedia.org, resize if needed, and put the credit line directly under it.
Steps 2 to 4 in Python. The script's main block calls search_images(query, pages=2), passes the results to commons_files, sends the titles to licenses and prints each verdict:
# commons_licenses.py: tested 2026-11-18 with Python 3.12.10 and requests 2.34.2
import re
from urllib.parse import unquote, urlparse
import requests
COMMONS_API = "https://commons.wikimedia.org/w/api.php"
# Wikimedia refuses generic User-Agents: name your tool and give a contact.
UA = {"User-Agent": "BestSERP-blog-license-check/1.0 (https://bestserp.com/blog; bot)"}
ALLOWED = re.compile(r"^(public domain|cc0( 1\.0)?|cc by(-sa)? \d\.\d( [a-z]{2})?)$", re.I)
def commons_files(images):
"""Yield (File: title, result) for results whose page is a Commons file page."""
for img in images:
url = urlparse(img.get("link", ""))
if url.netloc == "commons.wikimedia.org" and url.path.startswith("/wiki/File:"):
yield unquote(url.path[len("/wiki/"):]).replace("_", " "), img
def licenses(titles):
"""License metadata for Commons files, read from the file pages by the Commons API (50 titles per call)."""
titles, found = list(dict.fromkeys(titles)), {}
for i in range(0, len(titles), 50):
batch = titles[i:i + 50]
r = requests.get(COMMONS_API, headers=UA, timeout=30, params={
"action": "query", "format": "json", "formatversion": 2, "titles": "|".join(batch),
"prop": "imageinfo", "iiprop": "url|size|extmetadata",
"iiextmetadatafilter": "LicenseShortName|LicenseUrl|Artist|AttributionRequired|Restrictions|DeletionReason",
})
r.raise_for_status()
data = r.json()["query"]
renamed = {n["from"]: n["to"] for n in data.get("normalized", [])}
pages = {p["title"]: p for p in data["pages"]}
found.update({t: pages.get(renamed.get(t, t)) for t in batch})
return found
def text(html):
return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", html or "")).strip()
def verdict(page):
"""(ok, reason, info) for one Commons file page."""
if not page or page.get("missing") or not page.get("imageinfo"):
return False, "no such file", {}
info = page["imageinfo"][0]
meta = {k: v.get("value", "") for k, v in info.get("extmetadata", {}).items()}
name = text(meta.get("LicenseShortName"))
if meta.get("DeletionReason"):
return False, "nominated for deletion", info
if meta.get("Restrictions"): # e.g. personality rights, trademarks
return False, f"restriction: {meta['Restrictions']}", info
if not ALLOWED.match(name):
return False, f"license not on our list: {name or 'none'}", info
return True, name, info
The User-Agent line is required: with requests' default agent (python-requests/2.34.2) the Commons API answered 403 "Please set a user-agent and respect our robot policy", as Wikimedia's User-Agent policy warns. Our run, python commons_licenses.py "lighthouse wikimedia commons" 2 (trimmed):
200 images, 81 on commons.wikimedia.org, 51 of them file pages
KEEP #2 Pigeon Point Lighthouse (2016).jpg CC BY-SA 4.0
KEEP #3 Louisbourg Lighthouse.jpg CC BY-SA 2.0
KEEP #6 Victoria fisgard lighthouse.jpg Public domain
KEEP #7 Lighthouse at night (Unsplash).jpg CC0
...
SKIP #66 Brant Point Lighthouse 1940.jpg license not on our list: No restrictions
...
kept 50 of 51: 14 CC BY-SA 3.0, 11 CC BY-SA 4.0, 10 Public domain, 7 CC BY-SA 2.0, 3 CC BY 3.0, 2 CC0, 2 CC BY 2.0, 1 CC BY 1.0

The metadata is a filter, not a guarantee. CommonsMetadata notes that its license values "are currently unreliable" for multi-licensed images, and Commons says the Wikimedia Foundation "does not provide any warranty regarding the copyright status or correctness of licensing terms" (Reusing content outside Wikimedia). That is why step 5 is a person reading the file page.
We picked the first result, File:Pigeon Point Lighthouse (2016).jpg. Its file page says CC BY-SA 4.0, own work by Frank Schulenburg, asks for the credit "© Frank Schulenburg / CC BY-SA 4.0" and lists no restriction; the photo shows no people. It is the same picture Google showed first for plain "lighthouse" through a Wikipedia article, where the result said nothing about its author or license. This script downloads the original and resizes it without cropping:
# fetch_commons_photo.py: tested 2026-11-18 with Python 3.12.10, requests 2.34.2 and Pillow 13.0.0
import io
import json
import sys
import requests
from PIL import Image
UA = {"User-Agent": "BestSERP-blog-license-check/1.0 (https://bestserp.com/blog; bot)"}
saved, title, out = sys.argv[1], sys.argv[2], sys.argv[3]
kept = {k["title"]: k for k in json.load(open(saved, encoding="utf-8"))["kept"]}
photo = kept[title] # only a file that passed the license check
assert photo["original"].startswith("https://upload.wikimedia.org/"), photo["original"]
r = requests.get(photo["original"], headers=UA, timeout=120)
r.raise_for_status()
img = Image.open(io.BytesIO(r.content))
print(f"original: {img.width}x{img.height}, {len(r.content):,} bytes")
img.thumbnail((1600, 1600)) # resizing only, aspect ratio kept
img.convert("RGB").save(out, "JPEG", quality=85)
print(f"saved {out}: {img.width}x{img.height}")
print(f"*Photo: [{photo['author']}]({photo['page']}), [{photo['license']}]({photo['licenseUrl']}), via Wikimedia Commons.*")
It read the 4843 × 3217 original (14.7 MB) and saved a 1600 × 1063 JPEG, shown here with its credit line:

Photo: © Frank Schulenburg, CC BY-SA 4.0, via Wikimedia Commons. Resized, otherwise unchanged.
Limits
What to plan around, as of November 18, 2026:
- No image filters (size, color, type, usage rights); only the recency filter
tbs. - About 100 images per page, up to 5 pages at 1 credit each, with the page-2 gap described above.
- Files stay on their owners' servers: an
imageUrlcan move or refuse downloads, so keeplink. - Country and language only (how gl and hl work), desktop results;
ipCountrysays where the search ran. - 60 searches per minute by default (rate limits), and cached repeats cost the normal price: ours answered
cached: truein 33 ms for 2 credits.
Common problems and fixes
| Problem | Cause | Fix |
|---|---|---|
400 unknown_parameter: imgSize or rights |
Image filters are not parameters | Filter on imageWidth, imageHeight and domain in code |
400 unsupported_parameter: num |
/images pages with pages, not num |
Send pages from 1 to 5 |
KeyError: 'imageUrl' or undefined sizes |
Results past the first 100 lacked the image fields | Read fields with .get() or ??, and use page 1 for image URLs |
| Commons API answers 403 | Generic or missing User-Agent | Send a User-Agent that names your tool and a contact |
KeyError on a Commons title |
More than 50 titles: the API takes 50 per call | Send batches of 50 (our first version stopped at 50 and crashed on result 51) |
Download of imageUrl fails |
The host blocks hotlinking or moved the file | Link to the page instead; download only files you may use |
Next steps
You can now search Google Images programmatically, filter the results by size and site, and keep only images whose license you have read. Next:
- The Google Images API page for the endpoint at a glance, and the /images reference for every parameter.
- Our guide to local search data for the shopping, places, maps and news endpoints that share this client.
- Google search results in Python to turn the same client into a batch job with CSV export.