diff --git a/examples/async/events_async.py b/examples/async/events_async.py index f43357b..4133a2b 100644 --- a/examples/async/events_async.py +++ b/examples/async/events_async.py @@ -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']}") diff --git a/examples/events.py b/examples/events.py index cdb035e..f2fc745 100644 --- a/examples/events.py +++ b/examples/events.py @@ -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"} 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']}") diff --git a/resend/events/_events.py b/resend/events/_events.py index dd1890d..7164925 100644 --- a/resend/events/_events.py +++ b/resend/events/_events.py @@ -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. @@ -286,7 +303,11 @@ 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 @@ -294,13 +315,17 @@ def send(cls, params: "Events.SendParams") -> "Events.SendResponse": 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 @@ -407,7 +432,11 @@ 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 @@ -415,13 +444,17 @@ async def send_async(cls, params: "Events.SendParams") -> "Events.SendResponse": 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 diff --git a/tests/events_async_test.py b/tests/events_async_test.py index 064cf53..7c57e74 100644 --- a/tests/events_async_test.py +++ b/tests/events_async_test.py @@ -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 @@ -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" diff --git a/tests/events_test.py b/tests/events_test.py index c543917..c9c3f83 100644 --- a/tests/events_test.py +++ b/tests/events_test.py @@ -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 @@ -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" + 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"]