# Use Google Ad Details API with Python

SocialScraper Engineering · 2026-11-28

Inspect a Google ad creative's identity, format and public variation fields.

Use the selected Google ad as a source record in a creative-research library. Keep its identity with the creative and destination fields so reviewers can trace the example.

## Before you begin

Use Python 3.10 or newer, a terminal and a customer API key. The script uses urllib, json and pathlib from the standard library. Save the Python file and its JSON input file in the same directory.

## Configure your API key

Replace YOUR_API_KEY privately with your customer key. Keep the variable in the environment used by the script; the source code reads it without storing the key in the file.

```sh
export SOCIALSCRAPER_API_KEY="YOUR_API_KEY"
```

## Prepare the endpoint inputs

`GET /v1/google/ad`

```json
{
  "url": "https://adstransparency.google.com/advertiser/AR07541154843046445057/creative/CR17778900238552006657"
}
```

### url

string · Required

Public google content or profile URL to retrieve. Paste the complete URL, including https://.



### cache_max_age

string · Optional

Maximum accepted age of a cached result. The allowed values below express days.

Allowed values: "1d", "3d", "7d", "14d", "30d"

## Complete implementation

```python
#!/usr/bin/env python3
"""Google Ad Details API: GET /v1/google/ad"""
import argparse
import json
import os
import uuid
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError

DEFAULT_INPUT = json.loads("{\"url\":\"https://adstransparency.google.com/advertiser/AR07541154843046445057/creative/CR17778900238552006657\"}")
parser = argparse.ArgumentParser(description="Google Ad Details API")
parser.add_argument("--input", type=Path, help="JSON file containing endpoint inputs")
parser.add_argument("--request-key", help="Original key for one identical retry")
parser.add_argument("--output", type=Path, default=Path("result.json"))
parser.add_argument("--pages", type=int, default=1, help="Maximum number of pages, 1 to 20")
args = parser.parse_args()
if not 1 <= args.pages <= 20:
    parser.error("--pages must be between 1 and 20")
if args.request_key and args.pages != 1:
    parser.error("--request-key requires --pages 1")
key = os.environ["SOCIALSCRAPER_API_KEY"]
base = os.environ.get("SOCIALSCRAPER_BASE_URL", "https://socialmediascraper.org").rstrip("/")
inputs = json.loads(args.input.read_text(encoding="utf-8")) if args.input else DEFAULT_INPUT.copy()
if not isinstance(inputs, dict):
    parser.error("--input must contain a JSON object")
responses = []
for page in range(args.pages):
    request_key = args.request_key or str(uuid.uuid4())
    headers = {"x-api-key": key, "Idempotency-Key": request_key}
    query = {name: (str(value).lower() if isinstance(value, bool) else value)
             for name, value in inputs.items()}
    request = Request(base + "/v1/google/ad" + "?" + urlencode(query), headers=headers)
    try:
        with urlopen(request, timeout=45) as response:
            result = json.load(response)
    except HTTPError as error:
        detail = error.read().decode("utf-8", errors="replace")
        retry_after = error.headers.get("Retry-After", "")
        raise RuntimeError(f"HTTP {error.code}; request key={request_key}; Retry-After={retry_after}; {detail}") from error
    except (URLError, TimeoutError) as error:
        raise RuntimeError(f"Uncertain request outcome; retain request key={request_key}; {error}") from error
    responses.append(result)
    args.output.write_text(json.dumps({"operation": "google.ad", "requests": responses},
                                     ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"page": page + 1, "request_id": result["request_id"]}))
    break
print(f"Saved {len(responses)} request response(s) to {args.output}")

```

## Run the script

```sh
python3 google.ad.py --input google.ad.input.json --output result.json --pages 1
```

## Read and use the result

The saved file has an operation label and a requests array. Each requests entry contains the original request_id, data and meta envelope. The JSON below shows one response; use the field table to choose what your application stores.

```json
{
  "request_id": "example-request-id",
  "data": {
    "platform": "google",
    "resource": "ad",
    "id": "123456789",
    "advertiser_id": "123456789",
    "format": "Example text",
    "first_shown": "Example text",
    "last_shown": "Example text",
    "impressions": {
      "min": "Example text",
      "max": "Example text"
    },
    "variations": [
      {
        "title": "Example text",
        "text": "Example text",
        "destination_url": "https://example.com/public-fixture"
      }
    ]
  },
  "meta": {
    "platform": "google",
    "fetched_at": "2026-11-28T00:00:00.000Z",
    "cached": false,
    "schema_version": "2026-11-23.2",
    "route_version": 1,
    "billing": {
      "capability": "google.ad",
      "version": "2026-11-23.retail-1",
      "currency": "USD",
      "unit_scale": 1000000000,
      "amount_units": 2444000,
      "amount_usd": "0.002444000",
      "billing_basis": "request"
    }
  }
}
```

- `data.platform`: Source platform identifier.

- `data.resource`: Operation resource identifier.

- `data.id`: Source identity preserved as text.

- `data.advertiser_id`: Source advertiser identifier.

- `data.format`: Content or advertisement format label.

- `data.first_shown`: First display value returned for an advertisement.

- `data.last_shown`: Last display value returned for an advertisement.

- `data.impressions`: Display impressions reported by the source.

- `data.impressions.min`: Minimum value in the reported interval.

- `data.impressions.max`: Maximum value in the reported interval.

- `data.variations`: Product variants associated with the listing.

- `data.variations[].title`: Title or display label associated with the record.

- `data.variations[].text`: Content text, biography or transcript text associated with this record.

- `data.variations[].destination_url`: Public destination linked from an advertisement or listing.

## Plan requests and pagination

Use the returned record or result set directly, then choose a related operation when your task needs additional data.

A new page is a new logical request. If the same request must be retried, keep its original Idempotency-Key and identical inputs. When the outcome is uncertain, query GET /v1/requests/:id before starting a replacement. The examples stop on an error rather than silently creating another request.

Published request price: $0.002444 USD. Each additional page is a separate request.

## Troubleshooting

400: Review the target URL, parameter types and identifier-combination rules.

401: Check SOCIALSCRAPER_API_KEY and the x-api-key header.

402: Check your USD balance and the selected operation’s price.

429: Read Retry-After and your current limits before retrying the same request.

[Open endpoint reference](https://socialmediascraper.org/apis/google/ad/)

[Python](https://socialmediascraper.org/tutorial-code/python/google.ad.py)
