foxreach 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
foxreach/__init__.py ADDED
@@ -0,0 +1,79 @@
1
+ """FoxReach — Official Python SDK for the FoxReach cold email outreach API."""
2
+
3
+ from .client import AsyncFoxReach, FoxReach
4
+ from ._exceptions import (
5
+ AuthenticationError,
6
+ BadRequestError,
7
+ ConnectionError,
8
+ FoxReachError,
9
+ NotFoundError,
10
+ PermissionError,
11
+ RateLimitError,
12
+ ServerError,
13
+ ValidationError,
14
+ )
15
+ from .types import (
16
+ Campaign,
17
+ CampaignAnalytics,
18
+ CampaignCreate,
19
+ CampaignUpdate,
20
+ DailyStat,
21
+ EmailAccount,
22
+ Lead,
23
+ LeadCreate,
24
+ LeadListParams,
25
+ LeadUpdate,
26
+ OverviewStats,
27
+ PaginationMeta,
28
+ Sequence,
29
+ SequenceCreate,
30
+ SequenceUpdate,
31
+ Template,
32
+ TemplateCreate,
33
+ TemplateUpdate,
34
+ Thread,
35
+ ThreadListParams,
36
+ ThreadUpdate,
37
+ WebhookEvent,
38
+ )
39
+
40
+ __version__ = "0.1.0"
41
+
42
+ __all__ = [
43
+ # Clients
44
+ "FoxReach",
45
+ "AsyncFoxReach",
46
+ # Exceptions
47
+ "FoxReachError",
48
+ "AuthenticationError",
49
+ "BadRequestError",
50
+ "ConnectionError",
51
+ "NotFoundError",
52
+ "PermissionError",
53
+ "RateLimitError",
54
+ "ServerError",
55
+ "ValidationError",
56
+ # Types
57
+ "Campaign",
58
+ "CampaignAnalytics",
59
+ "CampaignCreate",
60
+ "CampaignUpdate",
61
+ "DailyStat",
62
+ "EmailAccount",
63
+ "Lead",
64
+ "LeadCreate",
65
+ "LeadListParams",
66
+ "LeadUpdate",
67
+ "OverviewStats",
68
+ "PaginationMeta",
69
+ "Sequence",
70
+ "SequenceCreate",
71
+ "SequenceUpdate",
72
+ "Template",
73
+ "TemplateCreate",
74
+ "TemplateUpdate",
75
+ "Thread",
76
+ "ThreadListParams",
77
+ "ThreadUpdate",
78
+ "WebhookEvent",
79
+ ]
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Optional
4
+
5
+
6
+ class FoxReachError(Exception):
7
+ """Base exception for all FoxReach SDK errors."""
8
+
9
+ def __init__(
10
+ self,
11
+ message: str,
12
+ status_code: Optional[int] = None,
13
+ response_body: Optional[dict[str, Any]] = None,
14
+ ) -> None:
15
+ super().__init__(message)
16
+ self.status_code = status_code
17
+ self.response_body = response_body
18
+
19
+
20
+ class AuthenticationError(FoxReachError):
21
+ """Raised on 401 Unauthorized responses."""
22
+
23
+
24
+ class PermissionError(FoxReachError):
25
+ """Raised on 403 Forbidden responses."""
26
+
27
+
28
+ class NotFoundError(FoxReachError):
29
+ """Raised on 404 Not Found responses."""
30
+
31
+
32
+ class BadRequestError(FoxReachError):
33
+ """Raised on 400 Bad Request responses."""
34
+
35
+
36
+ class ValidationError(FoxReachError):
37
+ """Raised on 422 Unprocessable Entity responses."""
38
+
39
+
40
+ class RateLimitError(FoxReachError):
41
+ """Raised on 429 Too Many Requests after retries are exhausted."""
42
+
43
+ def __init__(
44
+ self,
45
+ message: str,
46
+ retry_after: Optional[float] = None,
47
+ **kwargs: Any,
48
+ ) -> None:
49
+ super().__init__(message, **kwargs)
50
+ self.retry_after = retry_after
51
+
52
+
53
+ class ServerError(FoxReachError):
54
+ """Raised on 5xx server errors."""
55
+
56
+
57
+ class ConnectionError(FoxReachError):
58
+ """Raised on network / connection errors."""
foxreach/_http.py ADDED
@@ -0,0 +1,267 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import time
5
+ from typing import Any, Callable, Dict, Optional, Tuple
6
+
7
+ import httpx
8
+
9
+ from ._exceptions import (
10
+ AuthenticationError,
11
+ BadRequestError,
12
+ ConnectionError,
13
+ FoxReachError,
14
+ NotFoundError,
15
+ PermissionError,
16
+ RateLimitError,
17
+ ServerError,
18
+ ValidationError,
19
+ )
20
+
21
+ _VERSION = "0.1.0"
22
+
23
+ _CAMEL_TO_SNAKE_RE = re.compile(r"(?<=[a-z0-9])([A-Z])")
24
+ _SNAKE_TO_CAMEL_RE = re.compile(r"_([a-z])")
25
+
26
+
27
+ def _to_snake(name: str) -> str:
28
+ return _CAMEL_TO_SNAKE_RE.sub(r"_\1", name).lower()
29
+
30
+
31
+ def _to_camel(name: str) -> str:
32
+ return _SNAKE_TO_CAMEL_RE.sub(lambda m: m.group(1).upper(), name)
33
+
34
+
35
+ def _keys_to_snake(obj: Any) -> Any:
36
+ if isinstance(obj, dict):
37
+ return {_to_snake(k): _keys_to_snake(v) for k, v in obj.items()}
38
+ if isinstance(obj, list):
39
+ return [_keys_to_snake(i) for i in obj]
40
+ return obj
41
+
42
+
43
+ def _keys_to_camel(obj: Any) -> Any:
44
+ if isinstance(obj, dict):
45
+ return {_to_camel(k): _keys_to_camel(v) for k, v in obj.items()}
46
+ if isinstance(obj, list):
47
+ return [_keys_to_camel(i) for i in obj]
48
+ return obj
49
+
50
+
51
+ _ERROR_MAP: Dict[int, type] = {
52
+ 400: BadRequestError,
53
+ 401: AuthenticationError,
54
+ 403: PermissionError,
55
+ 404: NotFoundError,
56
+ 422: ValidationError,
57
+ }
58
+
59
+
60
+ def _raise_for_status(resp: httpx.Response) -> None:
61
+ if resp.is_success:
62
+ return
63
+
64
+ try:
65
+ body = resp.json()
66
+ except Exception:
67
+ body = {"detail": resp.text}
68
+
69
+ message = body.get("detail") or body.get("message") or resp.reason_phrase or "Unknown error"
70
+
71
+ if resp.status_code == 429:
72
+ retry_after = resp.headers.get("Retry-After")
73
+ raise RateLimitError(
74
+ f"Rate limited: {message}",
75
+ retry_after=float(retry_after) if retry_after else None,
76
+ status_code=429,
77
+ response_body=body,
78
+ )
79
+
80
+ if resp.status_code >= 500:
81
+ raise ServerError(str(message), status_code=resp.status_code, response_body=body)
82
+
83
+ exc_cls = _ERROR_MAP.get(resp.status_code, FoxReachError)
84
+ raise exc_cls(str(message), status_code=resp.status_code, response_body=body)
85
+
86
+
87
+ class HttpClient:
88
+ """Synchronous HTTP transport for the FoxReach API."""
89
+
90
+ def __init__(
91
+ self,
92
+ api_key: str,
93
+ base_url: str,
94
+ timeout: float,
95
+ max_retries: int,
96
+ ) -> None:
97
+ self._base_url = base_url.rstrip("/")
98
+ self._max_retries = max_retries
99
+ self._client = httpx.Client(
100
+ headers={
101
+ "X-API-Key": api_key,
102
+ "Content-Type": "application/json",
103
+ "User-Agent": f"foxreach-python/{_VERSION}",
104
+ },
105
+ timeout=timeout,
106
+ )
107
+
108
+ def close(self) -> None:
109
+ self._client.close()
110
+
111
+ # -- public helpers used by PaginatedResponse.next_page() ----------------
112
+
113
+ @property
114
+ def base_url(self) -> str:
115
+ return self._base_url
116
+
117
+ # -- core request --------------------------------------------------------
118
+
119
+ def request(
120
+ self,
121
+ method: str,
122
+ path: str,
123
+ *,
124
+ params: Optional[Dict[str, Any]] = None,
125
+ json_body: Optional[Any] = None,
126
+ ) -> Any:
127
+ url = f"{self._base_url}{path}"
128
+ clean_params = {k: v for k, v in (params or {}).items() if v is not None}
129
+ body = _keys_to_camel(json_body) if json_body is not None else None
130
+
131
+ last_exc: Optional[Exception] = None
132
+ for attempt in range(self._max_retries + 1):
133
+ try:
134
+ resp = self._client.request(
135
+ method,
136
+ url,
137
+ params=clean_params or None,
138
+ json=body,
139
+ )
140
+ except httpx.ConnectError as exc:
141
+ raise ConnectionError(f"Connection failed: {exc}") from exc
142
+ except httpx.TimeoutException as exc:
143
+ raise ConnectionError(f"Request timed out: {exc}") from exc
144
+
145
+ if resp.status_code == 429 and attempt < self._max_retries:
146
+ retry_after = float(resp.headers.get("Retry-After", 2 ** attempt))
147
+ time.sleep(retry_after)
148
+ last_exc = None
149
+ continue
150
+
151
+ _raise_for_status(resp)
152
+
153
+ if resp.status_code == 204 or not resp.content:
154
+ return None
155
+
156
+ return _keys_to_snake(resp.json())
157
+
158
+ # should not reach here, but just in case
159
+ if last_exc:
160
+ raise last_exc
161
+ return None
162
+
163
+ def request_paginated(
164
+ self,
165
+ path: str,
166
+ *,
167
+ params: Optional[Dict[str, Any]] = None,
168
+ ) -> Tuple[list, dict]:
169
+ """Returns (data_list, meta_dict) from a paginated endpoint."""
170
+ result = self.request("GET", path, params=params)
171
+ if isinstance(result, dict):
172
+ data = result.get("data", [])
173
+ meta = result.get("meta", {})
174
+ return data, meta
175
+ # Some endpoints return a bare list
176
+ if isinstance(result, list):
177
+ return result, {}
178
+ return [], {}
179
+
180
+
181
+ class AsyncHttpClient:
182
+ """Async HTTP transport for the FoxReach API."""
183
+
184
+ def __init__(
185
+ self,
186
+ api_key: str,
187
+ base_url: str,
188
+ timeout: float,
189
+ max_retries: int,
190
+ ) -> None:
191
+ self._base_url = base_url.rstrip("/")
192
+ self._max_retries = max_retries
193
+ self._client = httpx.AsyncClient(
194
+ headers={
195
+ "X-API-Key": api_key,
196
+ "Content-Type": "application/json",
197
+ "User-Agent": f"foxreach-python/{_VERSION}",
198
+ },
199
+ timeout=timeout,
200
+ )
201
+
202
+ async def close(self) -> None:
203
+ await self._client.aclose()
204
+
205
+ @property
206
+ def base_url(self) -> str:
207
+ return self._base_url
208
+
209
+ async def request(
210
+ self,
211
+ method: str,
212
+ path: str,
213
+ *,
214
+ params: Optional[Dict[str, Any]] = None,
215
+ json_body: Optional[Any] = None,
216
+ ) -> Any:
217
+ import asyncio
218
+
219
+ url = f"{self._base_url}{path}"
220
+ clean_params = {k: v for k, v in (params or {}).items() if v is not None}
221
+ body = _keys_to_camel(json_body) if json_body is not None else None
222
+
223
+ last_exc: Optional[Exception] = None
224
+ for attempt in range(self._max_retries + 1):
225
+ try:
226
+ resp = await self._client.request(
227
+ method,
228
+ url,
229
+ params=clean_params or None,
230
+ json=body,
231
+ )
232
+ except httpx.ConnectError as exc:
233
+ raise ConnectionError(f"Connection failed: {exc}") from exc
234
+ except httpx.TimeoutException as exc:
235
+ raise ConnectionError(f"Request timed out: {exc}") from exc
236
+
237
+ if resp.status_code == 429 and attempt < self._max_retries:
238
+ retry_after = float(resp.headers.get("Retry-After", 2 ** attempt))
239
+ await asyncio.sleep(retry_after)
240
+ last_exc = None
241
+ continue
242
+
243
+ _raise_for_status(resp)
244
+
245
+ if resp.status_code == 204 or not resp.content:
246
+ return None
247
+
248
+ return _keys_to_snake(resp.json())
249
+
250
+ if last_exc:
251
+ raise last_exc
252
+ return None
253
+
254
+ async def request_paginated(
255
+ self,
256
+ path: str,
257
+ *,
258
+ params: Optional[Dict[str, Any]] = None,
259
+ ) -> Tuple[list, dict]:
260
+ result = await self.request("GET", path, params=params)
261
+ if isinstance(result, dict):
262
+ data = result.get("data", [])
263
+ meta = result.get("meta", {})
264
+ return data, meta
265
+ if isinstance(result, list):
266
+ return result, {}
267
+ return [], {}
@@ -0,0 +1,173 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import (
4
+ Any,
5
+ AsyncIterator,
6
+ Callable,
7
+ Dict,
8
+ Generic,
9
+ Iterator,
10
+ List,
11
+ Optional,
12
+ TYPE_CHECKING,
13
+ TypeVar,
14
+ )
15
+
16
+ from .types import PaginationMeta
17
+
18
+ if TYPE_CHECKING:
19
+ from ._http import AsyncHttpClient, HttpClient
20
+
21
+ T = TypeVar("T")
22
+
23
+
24
+ class PaginatedResponse(Generic[T]):
25
+ """A single page of results from a paginated API endpoint."""
26
+
27
+ def __init__(
28
+ self,
29
+ data: List[T],
30
+ meta: PaginationMeta,
31
+ *,
32
+ _http: HttpClient,
33
+ _path: str,
34
+ _params: Dict[str, Any],
35
+ _item_factory: Callable[[dict], T],
36
+ ) -> None:
37
+ self.data = data
38
+ self.meta = meta
39
+ self._http = _http
40
+ self._path = _path
41
+ self._params = _params
42
+ self._item_factory = _item_factory
43
+
44
+ def __iter__(self) -> Iterator[T]:
45
+ return iter(self.data)
46
+
47
+ def __len__(self) -> int:
48
+ return len(self.data)
49
+
50
+ def has_next_page(self) -> bool:
51
+ return self.meta.page < self.meta.total_pages
52
+
53
+ def next_page(self) -> PaginatedResponse[T]:
54
+ if not self.has_next_page():
55
+ raise StopIteration("No more pages")
56
+ params = {**self._params, "page": self.meta.page + 1}
57
+ return _fetch_page(
58
+ self._http,
59
+ self._path,
60
+ params,
61
+ self._item_factory,
62
+ )
63
+
64
+ def auto_paging_iter(self) -> Iterator[T]:
65
+ """Iterate through all items across all pages."""
66
+ page: PaginatedResponse[T] = self
67
+ while True:
68
+ yield from page.data
69
+ if not page.has_next_page():
70
+ break
71
+ page = page.next_page()
72
+
73
+
74
+ class AsyncPaginatedResponse(Generic[T]):
75
+ """Async version of PaginatedResponse."""
76
+
77
+ def __init__(
78
+ self,
79
+ data: List[T],
80
+ meta: PaginationMeta,
81
+ *,
82
+ _http: AsyncHttpClient,
83
+ _path: str,
84
+ _params: Dict[str, Any],
85
+ _item_factory: Callable[[dict], T],
86
+ ) -> None:
87
+ self.data = data
88
+ self.meta = meta
89
+ self._http = _http
90
+ self._path = _path
91
+ self._params = _params
92
+ self._item_factory = _item_factory
93
+
94
+ def __iter__(self) -> Iterator[T]:
95
+ return iter(self.data)
96
+
97
+ def __len__(self) -> int:
98
+ return len(self.data)
99
+
100
+ def has_next_page(self) -> bool:
101
+ return self.meta.page < self.meta.total_pages
102
+
103
+ async def next_page(self) -> AsyncPaginatedResponse[T]:
104
+ if not self.has_next_page():
105
+ raise StopAsyncIteration("No more pages")
106
+ params = {**self._params, "page": self.meta.page + 1}
107
+ return await _async_fetch_page(
108
+ self._http,
109
+ self._path,
110
+ params,
111
+ self._item_factory,
112
+ )
113
+
114
+ async def auto_paging_iter(self) -> AsyncIterator[T]:
115
+ """Async iterate through all items across all pages."""
116
+ page: AsyncPaginatedResponse[T] = self
117
+ while True:
118
+ for item in page.data:
119
+ yield item
120
+ if not page.has_next_page():
121
+ break
122
+ page = await page.next_page()
123
+
124
+
125
+ # ---------------------------------------------------------------------------
126
+ # Helpers
127
+ # ---------------------------------------------------------------------------
128
+
129
+ def _build_meta(raw: dict) -> PaginationMeta:
130
+ return PaginationMeta(
131
+ page=raw.get("page", 1),
132
+ page_size=raw.get("page_size", 50),
133
+ total=raw.get("total", 0),
134
+ total_pages=raw.get("total_pages", 0),
135
+ )
136
+
137
+
138
+ def _fetch_page(
139
+ http: HttpClient,
140
+ path: str,
141
+ params: Dict[str, Any],
142
+ item_factory: Callable[[dict], T],
143
+ ) -> PaginatedResponse[T]:
144
+ data_list, meta_raw = http.request_paginated(path, params=params)
145
+ items = [item_factory(d) for d in data_list]
146
+ meta = _build_meta(meta_raw)
147
+ return PaginatedResponse(
148
+ data=items,
149
+ meta=meta,
150
+ _http=http,
151
+ _path=path,
152
+ _params=params,
153
+ _item_factory=item_factory,
154
+ )
155
+
156
+
157
+ async def _async_fetch_page(
158
+ http: AsyncHttpClient,
159
+ path: str,
160
+ params: Dict[str, Any],
161
+ item_factory: Callable[[dict], T],
162
+ ) -> AsyncPaginatedResponse[T]:
163
+ data_list, meta_raw = await http.request_paginated(path, params=params)
164
+ items = [item_factory(d) for d in data_list]
165
+ meta = _build_meta(meta_raw)
166
+ return AsyncPaginatedResponse(
167
+ data=items,
168
+ meta=meta,
169
+ _http=http,
170
+ _path=path,
171
+ _params=params,
172
+ _item_factory=item_factory,
173
+ )
foxreach/client.py ADDED
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ from ._http import AsyncHttpClient, HttpClient
4
+ from .resources.leads import AsyncLeadsResource, LeadsResource
5
+ from .resources.campaigns import AsyncCampaignsResource, CampaignsResource
6
+ from .resources.templates import AsyncTemplatesResource, TemplatesResource
7
+ from .resources.email_accounts import AsyncEmailAccountsResource, EmailAccountsResource
8
+ from .resources.inbox import AsyncInboxResource, InboxResource
9
+ from .resources.analytics import AsyncAnalyticsResource, AnalyticsResource
10
+
11
+ _DEFAULT_BASE_URL = "https://api.foxreach.io/api/v1"
12
+
13
+
14
+ class FoxReach:
15
+ """Synchronous FoxReach API client.
16
+
17
+ Usage::
18
+
19
+ from foxreach import FoxReach
20
+
21
+ client = FoxReach(api_key="otr_...")
22
+ leads = client.leads.list(search="jane")
23
+ for lead in leads:
24
+ print(lead.email)
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ api_key: str,
30
+ *,
31
+ base_url: str = _DEFAULT_BASE_URL,
32
+ timeout: float = 30.0,
33
+ max_retries: int = 3,
34
+ ) -> None:
35
+ if not api_key or not api_key.startswith("otr_"):
36
+ raise ValueError('API key must start with "otr_"')
37
+
38
+ self._http = HttpClient(
39
+ api_key=api_key,
40
+ base_url=base_url,
41
+ timeout=timeout,
42
+ max_retries=max_retries,
43
+ )
44
+
45
+ self.leads = LeadsResource(self._http)
46
+ self.campaigns = CampaignsResource(self._http)
47
+ self.templates = TemplatesResource(self._http)
48
+ self.email_accounts = EmailAccountsResource(self._http)
49
+ self.inbox = InboxResource(self._http)
50
+ self.analytics = AnalyticsResource(self._http)
51
+
52
+ def close(self) -> None:
53
+ self._http.close()
54
+
55
+ def __enter__(self) -> FoxReach:
56
+ return self
57
+
58
+ def __exit__(self, *args: object) -> None:
59
+ self.close()
60
+
61
+
62
+ class AsyncFoxReach:
63
+ """Async FoxReach API client.
64
+
65
+ Usage::
66
+
67
+ from foxreach import AsyncFoxReach
68
+
69
+ async with AsyncFoxReach(api_key="otr_...") as client:
70
+ leads = await client.leads.list(search="jane")
71
+ async for lead in leads.auto_paging_iter():
72
+ print(lead.email)
73
+ """
74
+
75
+ def __init__(
76
+ self,
77
+ api_key: str,
78
+ *,
79
+ base_url: str = _DEFAULT_BASE_URL,
80
+ timeout: float = 30.0,
81
+ max_retries: int = 3,
82
+ ) -> None:
83
+ if not api_key or not api_key.startswith("otr_"):
84
+ raise ValueError('API key must start with "otr_"')
85
+
86
+ self._http = AsyncHttpClient(
87
+ api_key=api_key,
88
+ base_url=base_url,
89
+ timeout=timeout,
90
+ max_retries=max_retries,
91
+ )
92
+
93
+ self.leads = AsyncLeadsResource(self._http)
94
+ self.campaigns = AsyncCampaignsResource(self._http)
95
+ self.templates = AsyncTemplatesResource(self._http)
96
+ self.email_accounts = AsyncEmailAccountsResource(self._http)
97
+ self.inbox = AsyncInboxResource(self._http)
98
+ self.analytics = AsyncAnalyticsResource(self._http)
99
+
100
+ async def close(self) -> None:
101
+ await self._http.close()
102
+
103
+ async def __aenter__(self) -> AsyncFoxReach:
104
+ return self
105
+
106
+ async def __aexit__(self, *args: object) -> None:
107
+ await self.close()
@@ -0,0 +1,21 @@
1
+ from .leads import LeadsResource, AsyncLeadsResource
2
+ from .campaigns import CampaignsResource, AsyncCampaignsResource
3
+ from .templates import TemplatesResource, AsyncTemplatesResource
4
+ from .email_accounts import EmailAccountsResource, AsyncEmailAccountsResource
5
+ from .inbox import InboxResource, AsyncInboxResource
6
+ from .analytics import AnalyticsResource, AsyncAnalyticsResource
7
+
8
+ __all__ = [
9
+ "LeadsResource",
10
+ "AsyncLeadsResource",
11
+ "CampaignsResource",
12
+ "AsyncCampaignsResource",
13
+ "TemplatesResource",
14
+ "AsyncTemplatesResource",
15
+ "EmailAccountsResource",
16
+ "AsyncEmailAccountsResource",
17
+ "InboxResource",
18
+ "AsyncInboxResource",
19
+ "AnalyticsResource",
20
+ "AsyncAnalyticsResource",
21
+ ]