Skip to content
Merged
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
3 changes: 2 additions & 1 deletion .github/workflows/sdk-reference.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,33 @@

jobs:
docs:
runs-on: ubuntu-latest
# Python 3.8 has no actions/python-versions build for ubuntu-26.04, which ubuntu-latest now resolves to.
runs-on: ubuntu-24.04
environment:
name: sdk-reference
url: ${{ steps.deploy.outputs.deployment-url }}
steps:
- uses: actions/checkout@v2
- name: Setup Nodejs
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Install dependencies and build
run: pip install .[docs]
- name: Build docs
run: python setup.py build-docs
- name: Set env BRANCH
run: echo "BRANCH=$(echo $GITHUB_REF | cut -d'/' -f 3)" >> $GITHUB_ENV
- name: Set env CLOUDFLARE_BRANCH
run: |
if [[ $BRANCH == 'main' && $GITHUB_EVENT_NAME == 'push' ]]; then
echo "CLOUDFLARE_BRANCH=main" >> "$GITHUB_ENV"
else
echo "CLOUDFLARE_BRANCH=$BRANCH" >> "$GITHUB_ENV"
fi
- name: Publish to Cloudflare Pages
uses: cloudflare/wrangler-action@953926a2e2182532811c01a25e53647d93bf07c0 # v4.1.3
id: deploy
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
Expand Down
6 changes: 4 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,46 +11,48 @@

jobs:
pytest:
runs-on: ubuntu-latest
# Python 3.8 has no actions/python-versions build for ubuntu-26.04, which ubuntu-latest now resolves to.
runs-on: ubuntu-24.04
strategy:
matrix:
python-version: ["3.8", "3.x"]
name: Python ${{ matrix.python-version }}
steps:
- uses: actions/checkout@v2
- name: Setup python
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}

- name: Install dependencies
run: pip install .[test]

- name: Run tests
run: python setup.py test

- name: Upload coverage to Codecov
if: ${{ always() }}
uses: codecov/codecov-action@v3

black:

Check warning

Code scanning / CodeQL

Workflow does not contain permissions Medium test

Actions job or workflow does not limit the permissions of the GITHUB_TOKEN. Consider setting an explicit permissions block, using the following as a minimal starting point: {contents: read}
runs-on: ubuntu-latest
# Python 3.8 has no actions/python-versions build for ubuntu-26.04, which ubuntu-latest now resolves to.
runs-on: ubuntu-24.04
name: Pylint and Black
steps:
- uses: actions/checkout@v2
- name: Setup python
uses: actions/setup-python@v2
with:
python-version: "3.8"

- name: Install dependencies
run: pip install .

- name: Install pylint and black
run: pip install pylint black

- name: Run pylint
run: pylint nylas

- name: Run black
run: black .

Check warning

Code scanning / CodeQL

Workflow does not contain permissions Medium test

Actions job or workflow does not limit the permissions of the GITHUB_TOKEN. Consider setting an explicit permissions block, using the following as a minimal starting point: {contents: read}
1 change: 1 addition & 0 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,4 @@ generated-members=
FreeBusyError.from_dict,
FreeBusy.from_dict,
ScheduledMessage.from_dict,
BatchEventResult.from_dict,
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
nylas-python Changelog
======================
Unreleased
----------
* Added Events batch endpoint (Google and Microsoft): `events.batch()` runs create, update, and delete operations in one `POST /v3/grants/{grant_id}/events/batch` request, with the `BatchEventsRequest`, `BatchEventsQueryParams`, and `BatchEventResult` models. A partial failure (HTTP 207) returns the per-operation results instead of raising an error

v6.18.0
----------
* Added optional `tracking_options.domain_name` support for custom link and open tracking hostnames in message sends, scheduled sends, drafts, and Transactional Send
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ logging.getLogger("urllib3").setLevel(logging.DEBUG)

## 💡 Examples

Runnable examples live in [`examples/`](examples/) — including [send email](examples/send_email_demo/), [inline attachments](examples/inline_attachment_demo/), [folders](examples/folders_demo/), [import events](examples/import_events_demo/), [Notetaker API](examples/notetaker_api_demo/), [Notetaker calendar](examples/notetaker_calendar_demo/), [message fields](examples/message_fields_demo/), [metadata fields](examples/metadata_field_demo/), [provider errors](examples/provider_error_demo/), [response headers](examples/response_headers_demo/), [`select` parameter](examples/select_param_demo/), [special characters](examples/special_characters_demo/), [hidden folders](examples/include_hidden_folders_demo/), and [plain text](examples/is_plaintext_demo/).
Runnable examples live in [`examples/`](examples/) — including [send email](examples/send_email_demo/), [inline attachments](examples/inline_attachment_demo/), [folders](examples/folders_demo/), [import events](examples/import_events_demo/), [events batch](examples/events_batch_demo/), [Notetaker API](examples/notetaker_api_demo/), [Notetaker calendar](examples/notetaker_calendar_demo/), [message fields](examples/message_fields_demo/), [metadata fields](examples/metadata_field_demo/), [provider errors](examples/provider_error_demo/), [response headers](examples/response_headers_demo/), [`select` parameter](examples/select_param_demo/), [special characters](examples/special_characters_demo/), [hidden folders](examples/include_hidden_folders_demo/), and [plain text](examples/is_plaintext_demo/).

For full sample apps and product quickstarts, browse [**nylas-samples** on GitHub](https://github.com/orgs/nylas-samples/repositories?q=python) — every official SDK has Email, Calendar, Contacts, Scheduler, and Webhooks quickstarts.

Expand Down
135 changes: 135 additions & 0 deletions examples/events_batch_demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# Events Batch Demo

This example demonstrates how to create, update, and delete events in a single request with `events.batch()`, and how to retry the operations that failed.

Batch operations are available for Google and Microsoft grants. For other providers, the API returns a 400 error.

## Usage

```python
from nylas import Client

nylas = Client(api_key="NYLAS_API_KEY")

operations = [
{
"method": "create",
"body": {
"title": "Standup",
"when": {"start_time": 1798794000, "end_time": 1798795800},
},
},
{"method": "update", "event_id": "EVENT_ID_1", "body": {"title": "Renamed"}},
{"method": "delete", "event_id": "EVENT_ID_2"},
]

response = nylas.events.batch(
identifier="NYLAS_GRANT_ID",
query_params={"calendar_id": "primary"},
request_body={"operations": operations},
)

# response.data[i] is the result of operations[i].
for operation, result in zip(operations, response.data):
if result.error is None:
print(operation["method"], "succeeded with status", result.status)
else:
print(operation["method"], "failed:", result.status, result.error.type, result.error.message)
```

Each operation has a `method` of `create`, `update`, or `delete`:

- `create` needs a `body`. The body has the same fields as the request body of `events.create()`.
- `update` needs an `event_id` and a `body`. The body has the same fields as the request body of `events.update()`.
- `delete` needs an `event_id`.

The query parameters (`calendar_id`, `notify_participants`, `grant_email`, `tentative_as_busy`, and `select`) apply to every operation in the batch. `calendar_id` is required. An event can appear in only one operation per batch.

## Results

`response.data` has one result for each operation, in the same order as the operations. Each result has these fields:

| Field | Description |
| --- | --- |
| `status` | The HTTP status code of the operation. |
| `data` | The created or updated `Event`. `None` for delete operations and for failed operations. |
| `error` | The `type`, `message`, and `provider_error` of the error. `None` if the operation succeeded. |
| `retry_after` | The number of seconds to wait before a retry. Only set if the provider throttled the request. Can be `0`. |
| `provider_event_created` | `True` if the provider created the event before a later step failed. |

If some or all of the operations fail, the API returns HTTP 207. `events.batch()` doesn't raise an error for a 207 response. It returns the results, so check the `status` or `error` of each result.

If the request itself is invalid, the API returns HTTP 400 and runs none of the operations. For example, the request is invalid if `calendar_id` is missing, if the batch has too many operations, or if two operations use the same `event_id`. `events.batch()` then raises a `NylasApiError`, as for any other API error.

## Retrying Failed Operations

The SDK doesn't retry failed operations. Use these rules to retry them yourself:

- Retry an operation if its `status` is `429` or `503`. If `retry_after` is set, wait that number of seconds first. A `retry_after` of `0` means that you can retry now, so compare it with `None` instead of checking whether it is truthy.
- **Never** retry an operation if `provider_event_created` is `True`. The provider already created the event, so a retry creates a duplicate event.
- Send only the failed operations again. Don't send the operations that succeeded.

```python
import time

RETRYABLE_STATUSES = {429, 503}


def run_batch(nylas, grant_id, calendar_id, operations, max_attempts=3):
"""Run a batch, and retry the failed operations that are safe to retry."""
results = [None] * len(operations)
pending = list(range(len(operations)))

for attempt in range(1, max_attempts + 1):
response = nylas.events.batch(
identifier=grant_id,
query_params={"calendar_id": calendar_id},
request_body={"operations": [operations[index] for index in pending]},
)

retry = []
wait_seconds = 0
for index, result in zip(pending, response.data):
results[index] = result
if result.error is None or result.provider_event_created:
continue
if result.status in RETRYABLE_STATUSES:
retry.append(index)
delay = 1 if result.retry_after is None else result.retry_after
wait_seconds = max(wait_seconds, delay)

if not retry or attempt == max_attempts:
break
time.sleep(wait_seconds)
pending = retry

return results
```

## Setup

1. Install the SDK in development mode from the repository root:
```bash
cd /path/to/nylas-python
pip install -e .
```

2. Set your environment variables:
```bash
export NYLAS_API_KEY="your_api_key"
export NYLAS_GRANT_ID="your_grant_id" # A Google or Microsoft grant
export NYLAS_CALENDAR_ID="primary" # Optional, defaults to primary
export NYLAS_API_URI="https://api.us.nylas.com" # Optional, defaults to US
```

## Running the Example

```bash
python examples/events_batch_demo/events_batch_example.py
```

The example changes the calendar of the grant:

1. It creates two events one day from now, in one batch.
2. It renames one of the events. In the same batch, it deletes an event ID that doesn't exist, so the API returns HTTP 207 with one failed result.
3. It deletes both events in one batch.
185 changes: 185 additions & 0 deletions examples/events_batch_demo/events_batch_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
"""
Nylas SDK Example: Creating, Updating, and Deleting Events in a Batch

This example demonstrates how to use events.batch() to run several event operations
in a single request, and how to retry only the failed operations that are safe to retry.

The example changes the calendar. It creates two events one day from now, renames one
of them, and then deletes both. The second batch also deletes an event ID that doesn't
exist, to show how the results of a partial failure (HTTP 207) are returned.

Batch operations are only available for Google and Microsoft grants.

Required Environment Variables:
NYLAS_API_KEY: Your Nylas API key
NYLAS_GRANT_ID: Your Nylas grant ID for a Google or Microsoft account

Optional Environment Variables:
NYLAS_API_URI: The Nylas API URI (defaults to https://api.us.nylas.com)
NYLAS_CALENDAR_ID: The calendar to use (defaults to "primary")

Usage:
First, install the SDK in development mode:
cd /path/to/nylas-python
pip install -e .

Then set environment variables and run:
export NYLAS_API_KEY="your_api_key"
export NYLAS_GRANT_ID="your_grant_id"
python examples/events_batch_demo/events_batch_example.py
"""

import os
import sys
import time

from nylas import Client
from nylas.models.errors import NylasApiError

RETRYABLE_STATUSES = {429, 503}
DEFAULT_RETRY_SECONDS = 1
MAX_ATTEMPTS = 3


def get_env_or_exit(var_name: str) -> str:
"""Get an environment variable or exit if not found."""
value = os.getenv(var_name)
if not value:
print(f"Error: {var_name} environment variable is required")
sys.exit(1)
return value


def run_batch(client, grant_id, calendar_id, operations):
"""
Run a batch of event operations, and retry the failed operations that are safe to retry.

Returns one result for each operation, in the same order as the operations.
"""
results = [None] * len(operations)
pending = list(range(len(operations)))

for attempt in range(1, MAX_ATTEMPTS + 1):
response = client.events.batch(
identifier=grant_id,
query_params={"calendar_id": calendar_id},
request_body={"operations": [operations[index] for index in pending]},
)

retry = []
wait_seconds = 0
# response.data[i] is the result of the i-th operation in this request.
for index, result in zip(pending, response.data):
results[index] = result
if result.error is None:
continue
if result.provider_event_created:
# The provider created the event before a later step failed.
# Retrying this operation would create a duplicate event.
continue
if result.status in RETRYABLE_STATUSES:
retry.append(index)
# retry_after can be 0, which means the operation can be retried now.
if result.retry_after is None:
delay = DEFAULT_RETRY_SECONDS
else:
delay = result.retry_after
wait_seconds = max(wait_seconds, delay)

if not retry or attempt == MAX_ATTEMPTS:
break
print(f" Retrying {len(retry)} operation(s) in {wait_seconds} second(s)...")
time.sleep(wait_seconds)
pending = retry

return results


def print_results(operations, results):
"""Print the outcome of each operation."""
for operation, result in zip(operations, results):
target = operation.get("event_id") or operation["body"]["title"]
if result.error is None:
print(f" ✓ {operation['method']} {target}: HTTP {result.status}")
continue
print(
f" ✗ {operation['method']} {target}: HTTP {result.status} "
f"{result.error.type}: {result.error.message}"
)
if result.provider_event_created:
print(" The provider created this event anyway. Don't retry it.")


def run_demo(client, grant_id, calendar_id):
"""Create two events, rename one of them, and then delete both."""
start = int(time.time()) + 24 * 60 * 60
create_operations = [
{
"method": "create",
"body": {
"title": "Batch demo: standup",
"when": {"start_time": start, "end_time": start + 30 * 60},
},
},
{
"method": "create",
"body": {
"title": "Batch demo: retro",
"when": {"start_time": start + 60 * 60, "end_time": start + 90 * 60},
},
},
]

print("Creating two events in one batch...")
results = run_batch(client, grant_id, calendar_id, create_operations)
print_results(create_operations, results)
event_ids = [result.data.id for result in results if result.data is not None]
if not event_ids:
return

try:
change_operations = [
{
"method": "update",
"event_id": event_ids[0],
"body": {"title": "Batch demo: renamed standup"},
},
{"method": "delete", "event_id": "batch-demo-missing-event"},
]
print("\nRenaming an event and deleting an event that doesn't exist...")
results = run_batch(client, grant_id, calendar_id, change_operations)
print_results(change_operations, results)
finally:
delete_operations = [
{"method": "delete", "event_id": event_id} for event_id in event_ids
]
print("\nDeleting the created events in one batch...")
results = run_batch(client, grant_id, calendar_id, delete_operations)
print_results(delete_operations, results)


def main() -> None:
"""Run the batch example."""
api_key = get_env_or_exit("NYLAS_API_KEY")
grant_id = get_env_or_exit("NYLAS_GRANT_ID")
calendar_id = os.getenv("NYLAS_CALENDAR_ID", "primary")

client = Client(
api_key=api_key,
api_uri=os.getenv("NYLAS_API_URI", "https://api.us.nylas.com"),
)

try:
run_demo(client, grant_id, calendar_id)
except NylasApiError as error:
# events.batch() raises only when the API rejects the whole request,
# for example with HTTP 400 for an invalid batch or an unsupported provider.
print(
f"Error: {error} (HTTP {error.status_code}, request ID {error.request_id})"
)
sys.exit(1)


if __name__ == "__main__":
main()
Loading
Loading