Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions examples/async/events_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,15 @@ async def main() -> None:
)
print(f"Sent event: {sent['event']}")

# --- Send event with email ---
print("\n--- Send event with email ---")
# --- Send event with email and an idempotency key ---
print("\n--- Send event with email and an idempotency key ---")
send_options: resend.Events.SendOptions = {"idempotency_key": "user-signed-up/123"}
sent_email: resend.Events.SendResponse = await resend.Events.send_async(
{
"event": "user.signed_up",
"email": "test-events-async@example.com",
}
},
send_options,
)
print(f"Sent event: {sent_email['event']}")

Expand Down
8 changes: 5 additions & 3 deletions examples/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,15 @@
)
print(f"Sent event: {sent['event']}")

# --- Send event with email ---
print("\n--- Send event with email ---")
# --- Send event with email and an idempotency key ---
print("\n--- Send event with email and an idempotency key ---")
send_options: resend.Events.SendOptions = {"idempotency_key": "user-signed-up/123"}
Comment thread
NicolasLopes7 marked this conversation as resolved.
Resolved
sent_email: resend.Events.SendResponse = resend.Events.send(
{
"event": "user.signed_up",
"email": "test-events@example.com",
}
},
send_options,
)
print(f"Sent event: {sent_email['event']}")

Expand Down
41 changes: 37 additions & 4 deletions resend/events/_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,23 @@ class SendParams(TypedDict):
Key/value pairs to include with the event.
"""

class SendOptions(TypedDict):
"""
SendOptions is the class that wraps the options for the send method.

Attributes:
idempotency_key (NotRequired[str]): Unique key that ensures the same event is not processed multiple times.
Allows for safe retries without starting duplicate Automation runs.
If provided, will be sent as the `Idempotency-Key` header.
"""

idempotency_key: NotRequired[str]
"""
Unique key that ensures the same event is not processed multiple times.
Allows for safe retries without starting duplicate Automation runs.
If provided, will be sent as the `Idempotency-Key` header.
"""

class ListParams(TypedDict):
"""
ListParams is the class that wraps the parameters for the list method.
Expand Down Expand Up @@ -286,21 +303,29 @@ def remove(cls, identifier: str) -> "Events.DeleteResponse":
return resp

@classmethod
def send(cls, params: "Events.SendParams") -> "Events.SendResponse":
def send(
cls,
params: "Events.SendParams",
options: Optional["Events.SendOptions"] = None,
) -> "Events.SendResponse":
"""
Send an event for a contact.
see more: https://resend.com/docs/api-reference/events/send-event

Args:
params (SendParams): The event send parameters.
Exactly one of contact_id or email must be provided.
options (Optional[SendOptions]): The send options, ie: idempotency_key

Returns:
SendResponse: The send event response
"""
path = "/events/send"
resp = request.Request[Events.SendResponse](
path=path, params=cast(Dict[Any, Any], params), verb="post"
path=path,
params=cast(Dict[Any, Any], params),
verb="post",
options=cast(Dict[Any, Any], options),
).perform_with_content()
return resp

Expand Down Expand Up @@ -407,21 +432,29 @@ async def remove_async(cls, identifier: str) -> "Events.DeleteResponse":
return resp

@classmethod
async def send_async(cls, params: "Events.SendParams") -> "Events.SendResponse":
async def send_async(
cls,
params: "Events.SendParams",
options: Optional["Events.SendOptions"] = None,
) -> "Events.SendResponse":
"""
Send an event for a contact (async).
see more: https://resend.com/docs/api-reference/events/send-event

Args:
params (SendParams): The event send parameters.
Exactly one of contact_id or email must be provided.
options (Optional[SendOptions]): The send options, ie: idempotency_key

Returns:
SendResponse: The send event response
"""
path = "/events/send"
resp = await AsyncRequest[Events.SendResponse](
path=path, params=cast(Dict[Any, Any], params), verb="post"
path=path,
params=cast(Dict[Any, Any], params),
verb="post",
options=cast(Dict[Any, Any], options),
).perform_with_content()
return resp

Expand Down
24 changes: 24 additions & 0 deletions tests/events_async_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from unittest.mock import create_autospec

import pytest

import resend
from resend.exceptions import NoContentError
from resend.http_client_async import AsyncHTTPClient
from tests.conftest import AsyncResendBaseTest

# flake8: noqa
Expand Down Expand Up @@ -146,3 +149,24 @@ async def test_events_list_async_raises_when_no_content(self) -> None:
self.set_mock_json(None)
with pytest.raises(NoContentError):
_ = await resend.Events.list_async()


async def test_events_send_async_sends_the_idempotency_key(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client = create_autospec(AsyncHTTPClient, instance=True)
client.request.return_value = (
b'{"object": "event", "event": "order.created"}',
202,
{"Content-Type": "application/json"},
)
monkeypatch.setattr(resend, "api_key", "re_123")
monkeypatch.setattr(resend, "default_async_http_client", client)

resp = await resend.Events.send_async(
{"event": "order.created", "email": "ana@example.com"},
{"idempotency_key": "order/123"},
)
assert resp["event"] == "order.created"
_, kwargs = client.request.call_args
assert kwargs["headers"]["Idempotency-Key"] == "order/123"
36 changes: 36 additions & 0 deletions tests/events_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
from unittest import TestCase
from unittest.mock import create_autospec

import resend
from resend import HTTPClient
from tests.conftest import ResendBaseTest

# flake8: noqa
Expand Down Expand Up @@ -243,3 +247,35 @@ def test_events_list_with_pagination_params(self) -> None:
events = resend.Events.list(params=params)
assert events["has_more"] is True
assert len(events["data"]) == 1


class TestResendEventsSendRequest(TestCase):
def setUp(self) -> None:
resend.api_key = "re_123"
Comment thread
NicolasLopes7 marked this conversation as resolved.
Resolved
self.mock_client = create_autospec(HTTPClient, instance=True)
self.mock_client.name = "mock"
self.mock_client.request.return_value = (
b'{"object": "event", "event": "order.created"}',
202,
{"Content-Type": "application/json"},
)
self.previous_http_client = resend.default_http_client
resend.default_http_client = self.mock_client

def tearDown(self) -> None:
resend.default_http_client = self.previous_http_client

def test_events_send_sends_the_idempotency_key(self) -> None:
params: resend.Events.SendParams = {
"event": "order.created",
"email": "ana@example.com",
}
options: resend.Events.SendOptions = {"idempotency_key": "order/123"}
resend.Events.send(params, options)
_, kwargs = self.mock_client.request.call_args
assert kwargs["headers"]["Idempotency-Key"] == "order/123"
assert kwargs["json"] == params

resend.Events.send(params)
_, kwargs = self.mock_client.request.call_args
assert "Idempotency-Key" not in kwargs["headers"]