receiverdotemail 2.0.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.
- receiverdotemail/__init__.py +40 -0
- receiverdotemail/_context.py +50 -0
- receiverdotemail/_sse.py +39 -0
- receiverdotemail/_utils.py +26 -0
- receiverdotemail/_version.py +3 -0
- receiverdotemail/client.py +91 -0
- receiverdotemail/errors.py +58 -0
- receiverdotemail/http.py +169 -0
- receiverdotemail/resources/__init__.py +12 -0
- receiverdotemail/resources/api_keys.py +85 -0
- receiverdotemail/resources/emails.py +492 -0
- receiverdotemail/resources/inboxes.py +37 -0
- receiverdotemail/resources/organizations.py +90 -0
- receiverdotemail/resources/projects.py +88 -0
- receiverdotemail/resources/webhooks.py +58 -0
- receiverdotemail/types/__init__.py +69 -0
- receiverdotemail/types/api_key.py +42 -0
- receiverdotemail/types/base.py +17 -0
- receiverdotemail/types/email.py +126 -0
- receiverdotemail/types/inbox.py +15 -0
- receiverdotemail/types/organization.py +64 -0
- receiverdotemail/types/project.py +27 -0
- receiverdotemail/types/webhook.py +48 -0
- receiverdotemail/types/whoami.py +44 -0
- receiverdotemail/webhooks.py +47 -0
- receiverdotemail-2.0.0.dist-info/METADATA +301 -0
- receiverdotemail-2.0.0.dist-info/RECORD +29 -0
- receiverdotemail-2.0.0.dist-info/WHEEL +5 -0
- receiverdotemail-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Receiver.email Python SDK
|
|
3
|
+
Official SDK for the Receiver.email email testing platform
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from receiverdotemail._version import __version__
|
|
7
|
+
from receiverdotemail.client import ReceiverClient
|
|
8
|
+
from receiverdotemail.webhooks import verify_webhook_signature
|
|
9
|
+
from receiverdotemail.errors import (
|
|
10
|
+
ReceiverError,
|
|
11
|
+
ReceiverTimeoutError,
|
|
12
|
+
RateLimitError,
|
|
13
|
+
AuthenticationError,
|
|
14
|
+
NotFoundError,
|
|
15
|
+
)
|
|
16
|
+
from receiverdotemail.types import (
|
|
17
|
+
Email,
|
|
18
|
+
Inbox,
|
|
19
|
+
OtpResult,
|
|
20
|
+
OtpCandidate,
|
|
21
|
+
StreamEvent,
|
|
22
|
+
WhoAmI,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"__version__",
|
|
27
|
+
"ReceiverClient",
|
|
28
|
+
"verify_webhook_signature",
|
|
29
|
+
"ReceiverError",
|
|
30
|
+
"ReceiverTimeoutError",
|
|
31
|
+
"RateLimitError",
|
|
32
|
+
"AuthenticationError",
|
|
33
|
+
"NotFoundError",
|
|
34
|
+
"Email",
|
|
35
|
+
"Inbox",
|
|
36
|
+
"OtpResult",
|
|
37
|
+
"OtpCandidate",
|
|
38
|
+
"StreamEvent",
|
|
39
|
+
"WhoAmI",
|
|
40
|
+
]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Resolves the project for methods called without ``project_id``
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from receiverdotemail.errors import ReceiverError
|
|
9
|
+
from receiverdotemail.http import HttpClient
|
|
10
|
+
from receiverdotemail.types.whoami import WhoAmI
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ProjectContext:
|
|
14
|
+
"""Calls ``GET /whoami`` at most once (unless asked) and caches the API key's project."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, http: HttpClient, default_project_id: Optional[str] = None):
|
|
17
|
+
self._http = http
|
|
18
|
+
self._default_project_id = default_project_id
|
|
19
|
+
self._whoami: Optional[WhoAmI] = None
|
|
20
|
+
self._lock: Optional[asyncio.Lock] = None
|
|
21
|
+
|
|
22
|
+
async def whoami(self) -> WhoAmI:
|
|
23
|
+
"""Fetch ``GET /whoami`` and refresh the cache."""
|
|
24
|
+
data = await self._http.get("/whoami")
|
|
25
|
+
result = WhoAmI(**data)
|
|
26
|
+
self._whoami = result
|
|
27
|
+
return result
|
|
28
|
+
|
|
29
|
+
async def project_id(self, explicit: Optional[str] = None) -> str:
|
|
30
|
+
"""Return ``explicit`` if given, else the API key's project (cached after one whoami)."""
|
|
31
|
+
if explicit:
|
|
32
|
+
return explicit
|
|
33
|
+
if self._default_project_id:
|
|
34
|
+
return self._default_project_id
|
|
35
|
+
if self._whoami is None:
|
|
36
|
+
# Created lazily so it binds to the running loop (Python 3.9).
|
|
37
|
+
if self._lock is None:
|
|
38
|
+
self._lock = asyncio.Lock()
|
|
39
|
+
async with self._lock:
|
|
40
|
+
if self._whoami is None:
|
|
41
|
+
await self.whoami()
|
|
42
|
+
assert self._whoami is not None
|
|
43
|
+
if self._whoami.project is None:
|
|
44
|
+
raise ReceiverError(
|
|
45
|
+
"project_id is required: this client is not authenticated with a project "
|
|
46
|
+
"API key (recv_live_...), so it has no default project",
|
|
47
|
+
status_code=400,
|
|
48
|
+
code="PROJECT_ID_REQUIRED",
|
|
49
|
+
)
|
|
50
|
+
return self._whoami.project.id
|
receiverdotemail/_sse.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Minimal Server-Sent Events parser
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import AsyncIterator, NamedTuple, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SseMessage(NamedTuple):
|
|
9
|
+
"""A dispatched event, or a comment (``event is None``, e.g. ``: ping``)."""
|
|
10
|
+
|
|
11
|
+
event: Optional[str]
|
|
12
|
+
data: str
|
|
13
|
+
id: Optional[str] = None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def iter_sse(lines: AsyncIterator[str]) -> AsyncIterator[SseMessage]:
|
|
17
|
+
"""Parse SSE lines into messages. An unterminated event at EOF is dropped, per the spec."""
|
|
18
|
+
event = ""
|
|
19
|
+
data: list = []
|
|
20
|
+
event_id: Optional[str] = None
|
|
21
|
+
async for raw in lines:
|
|
22
|
+
line = raw.rstrip("\r\n")
|
|
23
|
+
if line == "":
|
|
24
|
+
if data:
|
|
25
|
+
yield SseMessage(event or "message", "\n".join(data), event_id)
|
|
26
|
+
event, data, event_id = "", [], None
|
|
27
|
+
continue
|
|
28
|
+
if line.startswith(":"):
|
|
29
|
+
yield SseMessage(None, line[1:].strip())
|
|
30
|
+
continue
|
|
31
|
+
field, _, value = line.partition(":")
|
|
32
|
+
if value.startswith(" "):
|
|
33
|
+
value = value[1:]
|
|
34
|
+
if field == "event":
|
|
35
|
+
event = value
|
|
36
|
+
elif field == "data":
|
|
37
|
+
data.append(value)
|
|
38
|
+
elif field == "id":
|
|
39
|
+
event_id = value
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Small helpers shared by the resources
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from typing import Union
|
|
7
|
+
|
|
8
|
+
SinceLike = Union[datetime, str]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def to_iso(value: SinceLike) -> str:
|
|
12
|
+
"""
|
|
13
|
+
Format a timestamp the way the API expects it (``2026-03-01T10:00:00.000Z``).
|
|
14
|
+
|
|
15
|
+
Strings are passed through unchanged, so an API value such as
|
|
16
|
+
``inbox.created_at`` or an ``end`` event's ``since`` round-trips exactly.
|
|
17
|
+
Naive datetimes are treated as local time, like ``datetime.now()``.
|
|
18
|
+
Precision is milliseconds, the API's precision.
|
|
19
|
+
"""
|
|
20
|
+
if isinstance(value, str):
|
|
21
|
+
return value
|
|
22
|
+
if value.tzinfo is None:
|
|
23
|
+
value = value.astimezone()
|
|
24
|
+
return (
|
|
25
|
+
value.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
26
|
+
)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Main Receiver client
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from receiverdotemail._context import ProjectContext
|
|
9
|
+
from receiverdotemail.errors import ReceiverError
|
|
10
|
+
from receiverdotemail.http import DEFAULT_USER_AGENT, HttpClient
|
|
11
|
+
from receiverdotemail.resources.api_keys import ApiKeys
|
|
12
|
+
from receiverdotemail.resources.emails import Emails
|
|
13
|
+
from receiverdotemail.resources.inboxes import Inboxes
|
|
14
|
+
from receiverdotemail.resources.organizations import Organizations
|
|
15
|
+
from receiverdotemail.resources.projects import Projects
|
|
16
|
+
from receiverdotemail.resources.webhooks import Webhooks
|
|
17
|
+
from receiverdotemail.types.whoami import WhoAmI
|
|
18
|
+
|
|
19
|
+
DEFAULT_BASE_URL = "https://api.receiver.email/api/v1"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ReceiverClient:
|
|
23
|
+
"""Main client for interacting with Receiver API."""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
api_key: Optional[str] = None,
|
|
28
|
+
base_url: Optional[str] = None,
|
|
29
|
+
timeout: float = 30,
|
|
30
|
+
user_agent: Optional[str] = None,
|
|
31
|
+
project_id: Optional[str] = None,
|
|
32
|
+
):
|
|
33
|
+
"""
|
|
34
|
+
Initialize Receiver client.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
api_key: Your Receiver API key (recv_live_...). Default: ``RECEIVER_API_KEY``.
|
|
38
|
+
base_url: API base URL. Default: ``RECEIVER_API_URL``, else production.
|
|
39
|
+
timeout: Request timeout in seconds for ordinary requests (default: 30).
|
|
40
|
+
Waits set their own HTTP timeout from their ``timeout`` argument.
|
|
41
|
+
user_agent: User-Agent header (default: ``receiver-sdk-py/<version>``).
|
|
42
|
+
Tools built on the SDK pass their own, e.g. ``my-tool/1.2``.
|
|
43
|
+
project_id: Default project for email and inbox methods. Default:
|
|
44
|
+
``RECEIVER_PROJECT_ID``. With an API key and no default, the client
|
|
45
|
+
looks it up once with ``whoami()``; setting it saves that request.
|
|
46
|
+
"""
|
|
47
|
+
api_key = api_key or os.environ.get("RECEIVER_API_KEY")
|
|
48
|
+
if not api_key:
|
|
49
|
+
raise ReceiverError(
|
|
50
|
+
"No API key: pass api_key=... or set RECEIVER_API_KEY",
|
|
51
|
+
status_code=0,
|
|
52
|
+
code="MISSING_API_KEY",
|
|
53
|
+
)
|
|
54
|
+
base_url = (base_url or os.environ.get("RECEIVER_API_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
55
|
+
|
|
56
|
+
self._http = HttpClient(
|
|
57
|
+
api_key=api_key,
|
|
58
|
+
base_url=base_url,
|
|
59
|
+
timeout=timeout,
|
|
60
|
+
user_agent=user_agent or DEFAULT_USER_AGENT,
|
|
61
|
+
)
|
|
62
|
+
self._context = ProjectContext(
|
|
63
|
+
self._http, default_project_id=project_id or os.environ.get("RECEIVER_PROJECT_ID")
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
self.emails = Emails(self._http, self._context)
|
|
67
|
+
self.inboxes = Inboxes(self._http, self._context)
|
|
68
|
+
self.webhooks = Webhooks(self._http)
|
|
69
|
+
self.projects = Projects(self._http)
|
|
70
|
+
self.organizations = Organizations(self._http)
|
|
71
|
+
self.api_keys = ApiKeys(self._http)
|
|
72
|
+
|
|
73
|
+
async def whoami(self) -> WhoAmI:
|
|
74
|
+
"""
|
|
75
|
+
``GET /whoami``: the API key's project (id, name, identifier, email_suffix),
|
|
76
|
+
or the user for a dashboard session. Also refreshes the cached project
|
|
77
|
+
used when ``project_id`` is omitted.
|
|
78
|
+
"""
|
|
79
|
+
return await self._context.whoami()
|
|
80
|
+
|
|
81
|
+
async def close(self) -> None:
|
|
82
|
+
"""Close the HTTP client."""
|
|
83
|
+
await self._http.close()
|
|
84
|
+
|
|
85
|
+
async def __aenter__(self) -> "ReceiverClient":
|
|
86
|
+
"""Async context manager entry."""
|
|
87
|
+
return self
|
|
88
|
+
|
|
89
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: # type: ignore[no-untyped-def]
|
|
90
|
+
"""Async context manager exit."""
|
|
91
|
+
await self.close()
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Error classes for Receiver SDK
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ReceiverError(Exception):
|
|
9
|
+
"""Base exception for Receiver SDK."""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
message: str,
|
|
14
|
+
status_code: Optional[int] = None,
|
|
15
|
+
code: Optional[str] = None,
|
|
16
|
+
):
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.message = message
|
|
19
|
+
self.status_code = status_code
|
|
20
|
+
self.code = code
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class RateLimitError(ReceiverError):
|
|
24
|
+
"""Rate limit exceeded."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, message: str, reset_at: Optional[str] = None):
|
|
27
|
+
super().__init__(message, status_code=429, code="RATE_LIMIT_EXCEEDED")
|
|
28
|
+
self.reset_at = reset_at
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class AuthenticationError(ReceiverError):
|
|
32
|
+
"""Authentication failed."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, message: str = "Invalid API key"):
|
|
35
|
+
super().__init__(message, status_code=401, code="UNAUTHORIZED")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class NotFoundError(ReceiverError):
|
|
39
|
+
"""Resource not found."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, message: str = "Resource not found"):
|
|
42
|
+
super().__init__(message, status_code=404, code="NOT_FOUND")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ReceiverTimeoutError(ReceiverError):
|
|
46
|
+
"""
|
|
47
|
+
No matching email arrived within the requested timeout.
|
|
48
|
+
|
|
49
|
+
Attributes:
|
|
50
|
+
since: The ISO timestamp the wait matched against. Pass it as ``since``
|
|
51
|
+
to a new wait to keep waiting without missing or re-matching mail.
|
|
52
|
+
waited_seconds: How long the SDK waited in total.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(self, message: str, since: Optional[str], waited_seconds: float):
|
|
56
|
+
super().__init__(message, status_code=408, code="WAIT_TIMEOUT")
|
|
57
|
+
self.since = since
|
|
58
|
+
self.waited_seconds = waited_seconds
|
receiverdotemail/http.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""
|
|
2
|
+
HTTP client for making requests to Receiver API
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import Any, AsyncIterator, Dict, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from receiverdotemail._utils import to_iso
|
|
12
|
+
from receiverdotemail._version import __version__
|
|
13
|
+
from receiverdotemail.errors import (
|
|
14
|
+
AuthenticationError,
|
|
15
|
+
NotFoundError,
|
|
16
|
+
RateLimitError,
|
|
17
|
+
ReceiverError,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
DEFAULT_USER_AGENT = f"receiver-sdk-py/{__version__}"
|
|
21
|
+
|
|
22
|
+
# The stream sends a ping every 15 s, so a read that stalls longer than this is a dead connection.
|
|
23
|
+
STREAM_READ_TIMEOUT = 45.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _clean_params(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
|
27
|
+
"""Drop None values and format datetimes as ISO strings."""
|
|
28
|
+
if not params:
|
|
29
|
+
return params
|
|
30
|
+
cleaned: Dict[str, Any] = {}
|
|
31
|
+
for key, value in params.items():
|
|
32
|
+
if value is None:
|
|
33
|
+
continue
|
|
34
|
+
cleaned[key] = to_iso(value) if isinstance(value, datetime) else value
|
|
35
|
+
return cleaned
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _error_info(response: httpx.Response, default: str) -> Tuple[str, Optional[str]]:
|
|
39
|
+
"""Read ``{"error": {"code", "message"}}`` (or ``{"error": "..."}``) from a response."""
|
|
40
|
+
try:
|
|
41
|
+
error = response.json().get("error")
|
|
42
|
+
except Exception:
|
|
43
|
+
return default, None
|
|
44
|
+
if isinstance(error, dict):
|
|
45
|
+
return error.get("message") or default, error.get("code")
|
|
46
|
+
return default, None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def raise_for_status(response: httpx.Response) -> None:
|
|
50
|
+
"""Map an error response to the SDK's typed errors. The body must already be read."""
|
|
51
|
+
status = response.status_code
|
|
52
|
+
if status < 400:
|
|
53
|
+
return
|
|
54
|
+
if status == 429:
|
|
55
|
+
raise RateLimitError("Rate limit exceeded", reset_at=response.headers.get("X-RateLimit-Reset"))
|
|
56
|
+
if status == 401:
|
|
57
|
+
raise AuthenticationError(_error_info(response, "Invalid API key")[0])
|
|
58
|
+
if status == 404:
|
|
59
|
+
raise NotFoundError(_error_info(response, "Resource not found")[0])
|
|
60
|
+
message, code = _error_info(response, "Request failed")
|
|
61
|
+
raise ReceiverError(message, status_code=status, code=code)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class HttpClient:
|
|
65
|
+
"""HTTP client wrapper for Receiver API."""
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
api_key: str,
|
|
70
|
+
base_url: str,
|
|
71
|
+
timeout: float,
|
|
72
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
73
|
+
):
|
|
74
|
+
self.api_key = api_key
|
|
75
|
+
self.base_url = base_url
|
|
76
|
+
self.timeout = timeout
|
|
77
|
+
self.user_agent = user_agent
|
|
78
|
+
|
|
79
|
+
self._client = httpx.AsyncClient(
|
|
80
|
+
base_url=base_url,
|
|
81
|
+
timeout=timeout,
|
|
82
|
+
headers={
|
|
83
|
+
"Authorization": f"Bearer {api_key}",
|
|
84
|
+
"Content-Type": "application/json",
|
|
85
|
+
"User-Agent": user_agent,
|
|
86
|
+
},
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
async def request(
|
|
90
|
+
self,
|
|
91
|
+
method: str,
|
|
92
|
+
path: str,
|
|
93
|
+
json: Optional[Dict[str, Any]] = None,
|
|
94
|
+
params: Optional[Dict[str, Any]] = None,
|
|
95
|
+
timeout: Optional[float] = None,
|
|
96
|
+
) -> Any:
|
|
97
|
+
"""Make an HTTP request. ``timeout`` overrides the client timeout (long polls)."""
|
|
98
|
+
extra: Dict[str, Any] = {}
|
|
99
|
+
if timeout is not None:
|
|
100
|
+
extra["timeout"] = timeout
|
|
101
|
+
try:
|
|
102
|
+
response = await self._client.request(
|
|
103
|
+
method=method,
|
|
104
|
+
url=path,
|
|
105
|
+
json=json,
|
|
106
|
+
params=_clean_params(params),
|
|
107
|
+
**extra,
|
|
108
|
+
)
|
|
109
|
+
raise_for_status(response)
|
|
110
|
+
if response.status_code == 204 or not response.content:
|
|
111
|
+
return None
|
|
112
|
+
return response.json()
|
|
113
|
+
except httpx.TimeoutException:
|
|
114
|
+
raise ReceiverError("Request timeout", status_code=408)
|
|
115
|
+
except ReceiverError:
|
|
116
|
+
raise
|
|
117
|
+
except Exception as e:
|
|
118
|
+
raise ReceiverError(f"Network error: {str(e)}", status_code=0)
|
|
119
|
+
|
|
120
|
+
@asynccontextmanager
|
|
121
|
+
async def stream(
|
|
122
|
+
self, path: str, params: Optional[Dict[str, Any]] = None
|
|
123
|
+
) -> AsyncIterator[httpx.Response]:
|
|
124
|
+
"""
|
|
125
|
+
Open a Server-Sent Events response. Error statuses raise the usual typed
|
|
126
|
+
errors; transport failures (also while reading) raise ReceiverError with
|
|
127
|
+
status 0 or 408.
|
|
128
|
+
"""
|
|
129
|
+
try:
|
|
130
|
+
async with self._client.stream(
|
|
131
|
+
"GET",
|
|
132
|
+
path,
|
|
133
|
+
params=_clean_params(params),
|
|
134
|
+
headers={"Accept": "text/event-stream"},
|
|
135
|
+
timeout=httpx.Timeout(self.timeout, read=STREAM_READ_TIMEOUT),
|
|
136
|
+
) as response:
|
|
137
|
+
if response.status_code >= 400:
|
|
138
|
+
await response.aread()
|
|
139
|
+
raise_for_status(response)
|
|
140
|
+
yield response
|
|
141
|
+
except httpx.TimeoutException:
|
|
142
|
+
raise ReceiverError("Stream timeout", status_code=408)
|
|
143
|
+
except httpx.TransportError as e:
|
|
144
|
+
raise ReceiverError(f"Network error: {str(e)}", status_code=0)
|
|
145
|
+
|
|
146
|
+
async def get(
|
|
147
|
+
self,
|
|
148
|
+
path: str,
|
|
149
|
+
params: Optional[Dict[str, Any]] = None,
|
|
150
|
+
timeout: Optional[float] = None,
|
|
151
|
+
) -> Any:
|
|
152
|
+
"""Make GET request."""
|
|
153
|
+
return await self.request("GET", path, params=params, timeout=timeout)
|
|
154
|
+
|
|
155
|
+
async def post(self, path: str, json: Optional[Dict[str, Any]] = None) -> Any:
|
|
156
|
+
"""Make POST request."""
|
|
157
|
+
return await self.request("POST", path, json=json)
|
|
158
|
+
|
|
159
|
+
async def patch(self, path: str, json: Optional[Dict[str, Any]] = None) -> Any:
|
|
160
|
+
"""Make PATCH request."""
|
|
161
|
+
return await self.request("PATCH", path, json=json)
|
|
162
|
+
|
|
163
|
+
async def delete(self, path: str) -> Any:
|
|
164
|
+
"""Make DELETE request."""
|
|
165
|
+
return await self.request("DELETE", path)
|
|
166
|
+
|
|
167
|
+
async def close(self) -> None:
|
|
168
|
+
"""Close HTTP client."""
|
|
169
|
+
await self._client.aclose()
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Resource modules for Receiver SDK
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from receiverdotemail.resources.emails import Emails
|
|
6
|
+
from receiverdotemail.resources.inboxes import Inboxes
|
|
7
|
+
from receiverdotemail.resources.webhooks import Webhooks
|
|
8
|
+
from receiverdotemail.resources.projects import Projects
|
|
9
|
+
from receiverdotemail.resources.organizations import Organizations
|
|
10
|
+
from receiverdotemail.resources.api_keys import ApiKeys
|
|
11
|
+
|
|
12
|
+
__all__ = ["Emails", "Inboxes", "Webhooks", "Projects", "Organizations", "ApiKeys"]
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""
|
|
2
|
+
API Key resource operations
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from receiverdotemail.http import HttpClient
|
|
8
|
+
from receiverdotemail.types.api_key import ApiKey, ApiKeyListResponse, CreateApiKeyResponse
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ApiKeys:
|
|
12
|
+
"""API Key operations."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, http: HttpClient):
|
|
15
|
+
self._http = http
|
|
16
|
+
|
|
17
|
+
async def list(
|
|
18
|
+
self,
|
|
19
|
+
project_id: str,
|
|
20
|
+
limit: int = 50,
|
|
21
|
+
cursor: Optional[str] = None,
|
|
22
|
+
) -> ApiKeyListResponse:
|
|
23
|
+
"""
|
|
24
|
+
List API keys for a project.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
project_id: Project ID
|
|
28
|
+
limit: Number of API keys to return
|
|
29
|
+
cursor: Pagination cursor
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
ApiKeyListResponse with API keys and pagination info
|
|
33
|
+
"""
|
|
34
|
+
params = {"limit": limit, "cursor": cursor}
|
|
35
|
+
data = await self._http.get(f"/projects/{project_id}/api-keys", params=params)
|
|
36
|
+
return ApiKeyListResponse(**data)
|
|
37
|
+
|
|
38
|
+
async def get(self, project_id: str, api_key_id: str) -> ApiKey:
|
|
39
|
+
"""
|
|
40
|
+
Get a single API key by ID.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
project_id: Project ID
|
|
44
|
+
api_key_id: API Key ID
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
ApiKey object
|
|
48
|
+
"""
|
|
49
|
+
data = await self._http.get(f"/projects/{project_id}/api-keys/{api_key_id}")
|
|
50
|
+
return ApiKey(**data)
|
|
51
|
+
|
|
52
|
+
async def create(
|
|
53
|
+
self,
|
|
54
|
+
project_id: str,
|
|
55
|
+
name: str,
|
|
56
|
+
expires_at: Optional[datetime] = None,
|
|
57
|
+
) -> CreateApiKeyResponse:
|
|
58
|
+
"""
|
|
59
|
+
Create a new API key.
|
|
60
|
+
Returns the full key - it will only be shown once!
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
project_id: Project ID
|
|
64
|
+
name: API key name/label
|
|
65
|
+
expires_at: Optional expiration date
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
CreateApiKeyResponse with the full key
|
|
69
|
+
"""
|
|
70
|
+
json_data = {"name": name}
|
|
71
|
+
if expires_at:
|
|
72
|
+
json_data["expiresAt"] = expires_at.isoformat()
|
|
73
|
+
|
|
74
|
+
data = await self._http.post(f"/projects/{project_id}/api-keys", json=json_data)
|
|
75
|
+
return CreateApiKeyResponse(**data)
|
|
76
|
+
|
|
77
|
+
async def revoke(self, project_id: str, api_key_id: str) -> None:
|
|
78
|
+
"""
|
|
79
|
+
Revoke an API key.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
project_id: Project ID
|
|
83
|
+
api_key_id: API Key ID
|
|
84
|
+
"""
|
|
85
|
+
await self._http.delete(f"/projects/{project_id}/api-keys/{api_key_id}")
|