Repository navigation
Expand file tree
/
Copy pathclient.py
More file actions
98 lines (84 loc) · 2.97 KB
/
Copy pathclient.py
File metadata and controls
98 lines (84 loc) · 2.97 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""
Single-file lightweight Python client for APINEED Google Places 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 GooglePlacesClient:
"""Google Places 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 GooglePlacesClient(api_key='...') "
"or set the APINEED_API_KEY environment variable. "
"Get one at https://apineed.com/tools/google-places"
)
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": "GooglePlacesClient/1.0",
})
def search(
self,
query: str,
location: Optional[str] = None,
country: Optional[str] = None,
language: Optional[str] = "en",
page: Optional[int] = 1,
) -> Dict[str, Any]:
"""Search Google Places with optional country, location, and language."""
payload = {}
payload["query"] = query
if location is not None:
payload["location"] = location
if country is not None:
payload["country"] = country
if language is not None:
payload["language"] = language
if page is not None:
payload["page"] = page
res = self._session.post(
f"{self.base_url}/v1/tools/google_places/invoke",
json=payload,
)
if not res.ok:
raise ApineedError(
f"search failed [{res.status_code}]: {res.text}"
)
return res.json().get("output", {})
def search_maps(
self,
query: str,
ll: Optional[str] = None,
place_id: Optional[str] = None,
language: Optional[str] = "en",
page: Optional[int] = 1,
) -> Dict[str, Any]:
"""Search Google Maps centered at @lat,long,zoom."""
payload = {}
payload["query"] = query
if ll is not None:
payload["ll"] = ll
if place_id is not None:
payload["place_id"] = place_id
if language is not None:
payload["language"] = language
if page is not None:
payload["page"] = page
res = self._session.post(
f"{self.base_url}/v1/tools/google_maps/invoke",
json=payload,
)
if not res.ok:
raise ApineedError(
f"search_maps failed [{res.status_code}]: {res.text}"
)
return res.json().get("output", {})