Skip to content
EN
Get API key
Browse documentation

Get started

SDK account checks and saved results

Check cost, keep a record of each attempt and read saved results without another API call.

On this page

Before you start

Use the project, installed SDK and FLASHDATA_API_KEY from your SDK quickstart. Choose one language below. Each new run directory represents one intended search; reusing an existing directory stops before making any request.

1. Check access and current cost

Save and run the check for your SDK. It reads permissions, balance and the price of one Google Search. Continue only after Access check passed; these checks do not submit a paid query or reserve credits.

check_access.py
import os
import sys
from flashdata import FlashData, APIError

def main():
    key = os.environ.get("FLASHDATA_API_KEY", "").strip()
    if not key:
        raise RuntimeError("Set FLASHDATA_API_KEY in this terminal.")
    with FlashData(api_key=key) as client:
        access = client.account.access()
        if "google_search" not in access["sources"]:
            raise RuntimeError("This key needs google_search permission.")
        balance = client.account.balance()
        pricing = client.account.pricing(source="google_search", request_count=1)
    price = next((p for p in pricing["prices"]
                  if p["source"] == "google_search" and p["available"]), None)
    cost = price.get("estimatedCredits") if price else None
    if cost is None:
        raise RuntimeError("No current price is available; stop here.")
    available = balance["availableCredits"]
    print(f"Available credits: {available}")
    print(f"One search: {cost} credits")
    if available < cost:
        raise RuntimeError("Insufficient credits. Review Billing.")
    print("Access check passed. No paid query submitted.")

if __name__ == "__main__":
    try:
        main()
    except APIError as error:
        print(f"HTTP {error.status_code}; code={error.code}; "
              f"request_id={error.request_id}; Retry-After={error.retry_after}",
              file=sys.stderr)
        sys.exit(1)
    except Exception as error:
        print(f"{type(error).__name__}: {error}", file=sys.stderr)
        sys.exit(1)
Linux / macOS
.venv/bin/python check_access.py
Windows PowerShell
.\.venv\Scripts\python.exe check_access.py

2. Run with a new output directory

Run one of these programs after the check passes. It creates the directory before submitting, records the request, then saves the response. Keep the directory on failure: deleting it or choosing a new one allows another billable query.

archive_search.py
import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from flashdata import FlashData, APIError, SubmissionUnknownError

def main():
    key = os.environ.get("FLASHDATA_API_KEY", "").strip()
    if not key:
        raise RuntimeError("Set FLASHDATA_API_KEY before running.")
    directory = Path(sys.argv[1] if len(sys.argv) > 1 else "runs/research-001")
    directory.mkdir(mode=0o700, parents=True, exist_ok=False)

    def save(name, value):
        with (directory / name).open("x", encoding="utf-8") as output:
            json.dump(value, output, ensure_ascii=False, indent=2)

    request = {"source": "google_search", "query": "battery recycling research",
               "params": {"num": 5}}
    save("request.json", request)
    save("intent.json", {"state": "dispatching",
                         "startedAt": datetime.now(timezone.utc).isoformat()})
    try:
        with FlashData(api_key=key) as client:
            response = client.google.search(request["query"], **request["params"])
    except (APIError, SubmissionUnknownError) as error:
        detail = {"kind": type(error).__name__}
        if isinstance(error, APIError):
            detail.update(code=error.code, httpStatus=error.status_code,
                          requestId=error.request_id, retryAfter=error.retry_after)
        save("error.json", detail)
        raise RuntimeError("Inspect the saved attempt and History before retrying.") from None
    save("result.json", response)
    if response.get("status") != "done":
        raise RuntimeError("Response saved; inspect its status before proceeding.")
    print("Saved:", directory / "result.json")
    print("Usage:", response.get("usage"))

if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(f"{type(error).__name__}: {error}", file=sys.stderr)
        sys.exit(1)
Linux / macOS
.venv/bin/python archive_search.py runs/research-001
Windows PowerShell
.\.venv\Scripts\python.exe archive_search.py runs/research-001

Expected files

Success prints the saved result path and usage. result.json should have status: done; Google results are in results[].organic[]. An empty organic array is valid. A reported API or transport error is saved to error.json; intent.json remains the original pre-submission record.

Successful attempt
runs/research-001/
  request.json   # Source, query and parameters
  intent.json    # Attempt start time
  result.json    # Full response, including results and usage

3. Read saved output

Read result.json for parsing, summaries and UI work. These commands use only local files. Rerunning the search with the same directory stops before a network call; it does not coordinate different machines or recover a lost server response.

Read locally
cat runs/research-001/result.json

Decide what to do after a failure

What you haveNext action
Existing directory / EEXISTInspect its files. No new query was sent by this attempt.
result.json, status: doneRead and process the saved response. Reuse its usage as a receipt of the original charge.
error.json with 401 / 403 / 402Fix access, source permissions or balance before planning a new attempt.
429 / retryAfterWait as instructed and reduce the request rate. Review the failed attempt before selecting a new run directory.
Unknown submission / intent only / write failureWork may already be accepted. Keep the directory and inspect History or a known job ID before sending another query.

Async clients and background jobs

NeedUse
Keep an event loop responsiveThe SDK's async client / await calls. A realtime query still completes in its HTTP response.
Resume after the calling process exitsSubmit a background job once, save its remote ID, then read status and results.
Run on a scheduleUse owner access and durable application run records, or the CLI's existing run journal.