Skip to content

Commit f843f25

Browse files
authored
feat: Added support for list_import_events (#411)
* feat: Added support for list_import_events * Renamed max_results to limit
1 parent 9f6a925 commit f843f25

File tree

6 files changed

+430
-0
lines changed

6 files changed

+430
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
nylas-python Changelog
22
======================
33

4+
Unreleased
5+
----------------
6+
* Added support for `list_import_events`
7+
48
v6.7.0
59
----------------
610
* Added support for `select` query parameter in list calendars, list events, and list messages.
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Import Events Demo
2+
3+
This example demonstrates the usage of the `list_import_events` method in the Nylas SDK. This method returns a list of recurring events, recurring event exceptions, and single events from a specified calendar within a given time frame. It's particularly useful when you want to import, store, and synchronize events from a calendar to your application.
4+
5+
## Features Demonstrated
6+
7+
1. **Basic Usage**: Shows how to use `list_import_events` with required parameters.
8+
2. **Time Filtering**: Demonstrates filtering events by start and end time.
9+
3. **Pagination**: Shows how to handle paginated results with `limit` and `page_token`.
10+
4. **Field Selection**: Demonstrates how to use the `select` parameter to request only specific fields.
11+
5. **Multiple Scenarios**: Shows various parameter combinations for different use cases.
12+
13+
## Setup
14+
15+
1. Create a `.env` file in the root directory with your Nylas API credentials:
16+
```
17+
NYLAS_API_KEY=your_api_key_here
18+
NYLAS_GRANT_ID=your_grant_id_here
19+
```
20+
21+
2. Install the required dependencies:
22+
```bash
23+
pip install nylas python-dotenv
24+
```
25+
26+
## Running the Example
27+
28+
Run the example script:
29+
```bash
30+
python examples/import_events_demo/import_events_example.py
31+
```
32+
33+
The script will demonstrate different ways to use the `list_import_events` method with various parameters.
34+
35+
## Example Output
36+
37+
The script will show output similar to this:
38+
```
39+
=== Import Events Demo ===
40+
41+
Basic import (primary calendar):
42+
Event - Title: Team Meeting, ID: abc123...
43+
44+
Time-filtered import (Jan 1, 2023 - Dec 31, 2023):
45+
Event - Title: Annual Review, ID: def456...
46+
47+
Limited results with field selection (only id, title and when):
48+
Event - Title: Client Call, ID: ghi789...
49+
```
50+
51+
## Benefits of Using Import Events
52+
53+
1. **Efficient Syncing**: Easily synchronize calendar events to your application or database.
54+
2. **Better Performance**: Using time filters and limiting results can improve performance.
55+
3. **Selective Data**: Using the select parameter allows you to request only the fields you need.
56+
57+
## Available Parameters
58+
59+
The `list_import_events` method accepts the following parameters:
60+
61+
- `calendar_id` (required): Specify the calendar ID to import events from. You can use "primary" for the user's primary calendar.
62+
- `start`: Filter for events starting at or after this Unix timestamp.
63+
- `end`: Filter for events ending at or before this Unix timestamp.
64+
- `select`: Comma-separated list of fields to return in the response.
65+
- `limit`: Maximum number of objects to return (defaults to 50, max 200).
66+
- `page_token`: Token for retrieving the next page of results.
67+
68+
For more information, refer to the [Nylas API documentation](https://developer.nylas.com/).
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Nylas SDK Example: Using Import Events
4+
5+
This example demonstrates how to use the 'list_import_events' method to import and
6+
synchronize events from a calendar within a given time frame.
7+
8+
Required Environment Variables:
9+
NYLAS_API_KEY: Your Nylas API key
10+
NYLAS_GRANT_ID: Your Nylas grant ID
11+
12+
Usage:
13+
First, install the SDK in development mode:
14+
cd /path/to/nylas-python
15+
pip install -e .
16+
17+
Then set environment variables and run:
18+
export NYLAS_API_KEY="your_api_key"
19+
export NYLAS_GRANT_ID="your_grant_id"
20+
python examples/import_events_demo/import_events_example.py
21+
"""
22+
23+
import os
24+
import sys
25+
import json
26+
import time
27+
from datetime import datetime, timedelta
28+
from nylas import Client
29+
30+
31+
def get_env_or_exit(var_name: str) -> str:
32+
"""Get an environment variable or exit if not found."""
33+
value = os.getenv(var_name)
34+
if not value:
35+
print(f"Error: {var_name} environment variable is required")
36+
sys.exit(1)
37+
return value
38+
39+
40+
def print_data(data: list, title: str) -> None:
41+
"""Pretty print the data with a title."""
42+
print(f"\n{title}:")
43+
for item in data:
44+
# Convert to dict and pretty print
45+
item_dict = item.to_dict()
46+
print(json.dumps(item_dict, indent=2))
47+
48+
49+
def demonstrate_basic_import(client: Client, grant_id: str) -> None:
50+
"""Demonstrate basic usage of list_import_events with primary calendar."""
51+
print("\n=== Basic Import Events ===")
52+
53+
print("\nFetching events from primary calendar:")
54+
events = client.events.list_import_events(
55+
identifier=grant_id,
56+
query_params={"calendar_id": "primary", "limit": 2}
57+
)
58+
print_data(events.data, "Basic import events")
59+
60+
61+
def demonstrate_time_filtered_import(client: Client, grant_id: str) -> None:
62+
"""Demonstrate import events with time filtering."""
63+
print("\n=== Time Filtered Import Events ===")
64+
65+
# Get timestamps for a one-month period
66+
now = int(time.time())
67+
one_month_ago = now - (30 * 24 * 60 * 60) # 30 days ago
68+
one_month_future = now + (30 * 24 * 60 * 60) # 30 days in future
69+
70+
# Format dates for display
71+
from_date = datetime.fromtimestamp(one_month_ago).strftime("%Y-%m-%d")
72+
to_date = datetime.fromtimestamp(one_month_future).strftime("%Y-%m-%d")
73+
74+
print(f"\nFetching events from {from_date} to {to_date}:")
75+
events = client.events.list_import_events(
76+
identifier=grant_id,
77+
query_params={
78+
"calendar_id": "primary",
79+
"start": one_month_ago,
80+
"end": one_month_future
81+
}
82+
)
83+
print_data(events.data, f"Events from {from_date} to {to_date}")
84+
85+
86+
def demonstrate_limit(client: Client, grant_id: str) -> None:
87+
"""Demonstrate import events with limit parameter."""
88+
print("\n=== Import Events with Max Results ===")
89+
90+
print("\nFetching events with limit=5:")
91+
events = client.events.list_import_events(
92+
identifier=grant_id,
93+
query_params={
94+
"calendar_id": "primary",
95+
"limit": 5
96+
}
97+
)
98+
print_data(events.data, "Events with limit=5")
99+
100+
101+
def demonstrate_field_selection(client: Client, grant_id: str) -> None:
102+
"""Demonstrate import events with field selection."""
103+
print("\n=== Import Events with Field Selection ===")
104+
105+
print("\nFetching events with select parameter (only id, title, and when):")
106+
events = client.events.list_import_events(
107+
identifier=grant_id,
108+
query_params={
109+
"calendar_id": "primary",
110+
"limit": 2,
111+
"select": "id,title,when"
112+
}
113+
)
114+
print_data(events.data, "Events with selected fields only")
115+
116+
117+
def demonstrate_pagination(client: Client, grant_id: str) -> None:
118+
"""Demonstrate pagination for import events."""
119+
print("\n=== Import Events with Pagination ===")
120+
121+
# First page
122+
print("\nFetching first page of events (limit=3):")
123+
first_page = client.events.list_import_events(
124+
identifier=grant_id,
125+
query_params={
126+
"calendar_id": "primary",
127+
"limit": 3
128+
}
129+
)
130+
print_data(first_page.data, "First page of events")
131+
132+
# If there's a next page, fetch it
133+
if hasattr(first_page, 'next_cursor') and first_page.next_cursor:
134+
print("\nFetching second page of events:")
135+
second_page = client.events.list_import_events(
136+
identifier=grant_id,
137+
query_params={
138+
"calendar_id": "primary",
139+
"limit": 3,
140+
"page_token": first_page.next_cursor
141+
}
142+
)
143+
print_data(second_page.data, "Second page of events")
144+
else:
145+
print("\nNo second page available - not enough events to paginate")
146+
147+
148+
def demonstrate_full_example(client: Client, grant_id: str) -> None:
149+
"""Demonstrate a full example with all parameters."""
150+
print("\n=== Full Import Events Example ===")
151+
152+
# Get timestamps for the current year
153+
now = datetime.now()
154+
start_of_year = datetime(now.year, 1, 1).timestamp()
155+
end_of_year = datetime(now.year, 12, 31, 23, 59, 59).timestamp()
156+
157+
print(f"\nFetching events for {now.year} with all parameters:")
158+
events = client.events.list_import_events(
159+
identifier=grant_id,
160+
query_params={
161+
"calendar_id": "primary",
162+
"limit": 10,
163+
"start": int(start_of_year),
164+
"end": int(end_of_year),
165+
"select": "id,title,description,when,participants,location"
166+
}
167+
)
168+
print_data(events.data, f"Events for {now.year} with all parameters")
169+
170+
171+
def main():
172+
"""Main function demonstrating the import events method."""
173+
# Get required environment variables
174+
api_key = get_env_or_exit("NYLAS_API_KEY")
175+
grant_id = get_env_or_exit("NYLAS_GRANT_ID")
176+
177+
# Initialize Nylas client
178+
client = Client(
179+
api_key=api_key,
180+
)
181+
182+
print("\nDemonstrating Import Events Functionality")
183+
print("========================================")
184+
185+
# Demonstrate different ways to use list_import_events
186+
demonstrate_basic_import(client, grant_id)
187+
demonstrate_time_filtered_import(client, grant_id)
188+
demonstrate_limit(client, grant_id)
189+
demonstrate_field_selection(client, grant_id)
190+
demonstrate_pagination(client, grant_id)
191+
demonstrate_full_example(client, grant_id)
192+
193+
print("\nExample completed!")
194+
195+
196+
if __name__ == "__main__":
197+
main()

nylas/models/events.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -804,3 +804,25 @@ class SendRsvpRequest(TypedDict):
804804
"""
805805

806806
status: SendRsvpStatus
807+
808+
809+
class ListImportEventsQueryParams(ListQueryParams):
810+
"""
811+
Interface representing the query parameters for listing imported events.
812+
813+
Attributes:
814+
calendar_id: Specify calendar ID to import events to. "primary" is a supported value
815+
indicating the user's primary calendar.
816+
start: Filter for events that start at or after the specified time, in Unix timestamp format.
817+
end: Filter for events that end at or before the specified time, in Unix timestamp format.
818+
select: Comma-separated list of fields to return in the response.
819+
This allows you to receive only the portion of object data that you're interested in.
820+
page_token: An identifier that specifies which page of data to return.
821+
This value should be taken from a ListResponse object's next_cursor parameter.
822+
"""
823+
824+
calendar_id: str
825+
start: NotRequired[int]
826+
end: NotRequired[int]
827+
select: NotRequired[str]
828+
page_token: NotRequired[str]

nylas/resources/events.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
CreateEventRequest,
1313
FindEventQueryParams,
1414
ListEventQueryParams,
15+
ListImportEventsQueryParams,
1516
CreateEventQueryParams,
1617
UpdateEventQueryParams,
1718
DestroyEventQueryParams,
@@ -64,6 +65,34 @@ def list(
6465
overrides=overrides,
6566
)
6667

68+
def list_import_events(
69+
self,
70+
identifier: str,
71+
query_params: ListImportEventsQueryParams,
72+
overrides: RequestOverrides = None,
73+
) -> ListResponse[Event]:
74+
"""
75+
Returns a list of recurring events, recurring event exceptions, and
76+
single events from the specified calendar within a given time frame.
77+
This is useful when you want to import, store, and synchronize events
78+
from the time frame to your application
79+
80+
Args:
81+
identifier: The identifier of the Grant to act upon.
82+
query_params: The query parameters to include in the request.
83+
overrides: The request overrides to use for the request.
84+
85+
Returns:
86+
The list of imported Events.
87+
"""
88+
89+
return super().list(
90+
path=f"/v3/grants/{identifier}/events/import",
91+
response_type=Event,
92+
query_params=query_params,
93+
overrides=overrides,
94+
)
95+
6796
def find(
6897
self,
6998
identifier: str,

0 commit comments

Comments
 (0)