listing-radar/test_search_api.py

61 lines
1.8 KiB
Python

"""Quick smoke test that hits Google Custom Search API directly.
Reads GEMINI_API_KEY and SEARCH_ENGINE_ID from .env and confirms credentials
work without going through the FastAPI service.
"""
import os
import sys
import requests
from dotenv import load_dotenv
load_dotenv()
GOOGLE_CSE_ENDPOINT = "https://www.googleapis.com/customsearch/v1"
API_KEY = os.getenv("GEMINI_API_KEY")
CX = os.getenv("SEARCH_ENGINE_ID")
QUERY = sys.argv[1] if len(sys.argv) > 1 else "lectures"
NUM = int(sys.argv[2]) if len(sys.argv) > 2 else 5
def main():
if not API_KEY:
print("[FAIL] GEMINI_API_KEY not set in .env")
sys.exit(1)
if not CX:
print("[FAIL] SEARCH_ENGINE_ID not set in .env")
sys.exit(1)
params = {"key": API_KEY, "cx": CX, "q": QUERY, "num": NUM}
print(f"GET {GOOGLE_CSE_ENDPOINT}?q={QUERY}&num={NUM} (key/cx hidden)\n")
try:
r = requests.get(GOOGLE_CSE_ENDPOINT, params=params, timeout=30)
except requests.RequestException as e:
print(f"[FAIL] Could not reach Google CSE: {e}")
sys.exit(1)
print(f"Status: {r.status_code}")
if r.status_code != 200:
print(f"Body: {r.text}")
sys.exit(1)
data = r.json()
info = data.get("searchInformation", {}) or {}
items = data.get("items", []) or []
print(f"Query: {QUERY}")
print(f"Total results: {info.get('totalResults')}")
print(f"Search time: {info.get('searchTime')}s")
print(f"Items returned: {len(items)}\n")
for i, item in enumerate(items, 1):
print(f"{i}. {item.get('title')}")
print(f" {item.get('link')}")
snippet = (item.get("snippet") or "").replace("\n", " ")
print(f" {snippet[:120]}{'...' if len(snippet) > 120 else ''}\n")
if __name__ == "__main__":
main()