FastAPI / nuse_modules /google_search.py
raghavNCI
roll back
8121f99
raw
history blame
850 Bytes
# nuse_modules/google_search.py
import os
import requests
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
GOOGLE_CX_ID = os.getenv("GOOGLE_CX_ID")
def search_google_news(keywords: list[str], num_results: int = 5):
query = " ".join(keywords)
url = (
f"https://www.googleapis.com/customsearch/v1"
f"?key={GOOGLE_API_KEY}&cx={GOOGLE_CX_ID}"
f"&q={query}&num={num_results}"
)
try:
res = requests.get(url, timeout=10)
res.raise_for_status()
data = res.json()
results = []
for item in data.get("items", []):
results.append({
"title": item.get("title"),
"link": item.get("link"),
"snippet": item.get("snippet"),
})
return results
except Exception as e:
return {"error": str(e)}