Repository navigation
Expand file tree
/
Copy pathclient.py
More file actions
73 lines (62 loc) · 2.29 KB
/
Copy pathclient.py
File metadata and controls
73 lines (62 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Single-file lightweight Python client for APINEED Google Search API.
Requires: pip install requests
"""
import json
import os
from typing import Any, Dict, Generator, List, Optional, Union
import requests
class ApineedError(Exception):
"""Base exception for APINEED API errors."""
pass
class GoogleSearchClient:
"""Google Search API Client powered by APINEED."""
def __init__(self, api_key: Optional[str] = None, base_url: str = "https://apineed.com"):
self.api_key = api_key or os.getenv("APINEED_API_KEY")
if not self.api_key:
raise ValueError(
"APINEED API Key is required. Pass it via GoogleSearchClient(api_key='...') "
"or set the APINEED_API_KEY environment variable. "
"Get one at https://apineed.com/tools/google-search"
)
self.base_url = base_url.rstrip("/")
self._session = requests.Session()
self._session.headers.update({
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
"User-Agent": "GoogleSearchClient/1.0",
})
def query(
self,
query: str,
country: Optional[str] = None,
language: Optional[str] = "en",
time_range: Optional[str] = None,
max_results: Optional[int] = 10,
page: Optional[int] = 1,
autocorrect: Optional[bool] = True,
) -> Dict[str, Any]:
"""Search Google SERP and return normalized results."""
payload = {}
payload["query"] = query
if country is not None:
payload["country"] = country
if language is not None:
payload["language"] = language
if time_range is not None:
payload["time_range"] = time_range
if max_results is not None:
payload["max_results"] = max_results
if page is not None:
payload["page"] = page
if autocorrect is not None:
payload["autocorrect"] = autocorrect
res = self._session.post(
f"{self.base_url}/v1/tools/google_search/invoke",
json=payload,
)
if not res.ok:
raise ApineedError(
f"query failed [{res.status_code}]: {res.text}"
)
return res.json().get("output", {})