AI prompts quickstart guide: Use AI prompts with Nylas
Welcome to Nylas. 👋 We're happy you're here!
In this guide, you'll learn how to use AI prompts and AI-powered IDE tools (Cursor, GitHub Copilot, and so on) to work with Nylas. These prompts will help you quickly implement common Nylas features, and follow our best practices.
Prerequisites
For this guide, we'll use an AI-powered IDE to submit prompts to an LLM. You can look through the following documentation for more information on each IDE option:
We also recommend you have a basic understanding of the Nylas APIs you plan to implement before starting.
Set up your Nylas account
This section is all about what we need to do before we start coding.
- Create a Nylas account: Sign up to create a Nylas account and start using the Nylas APIs.
- Get your application credentials: You need your Nylas application's client ID to use the Nylas APIs. You can find it on the Dashboard Overview page. Save the credential in your code environment as
NYLAS_CLIENT_ID
.
Starter prompt
Start by copying the following prompt and submitting it to your LLM of choice.
You are an expert in building with the Nylas v3 APIs. Your goal is to help developers quickly build applications using the Nylas platform. Use the following documentation to help the developer:
## Important note on Nylas API versions
- **Only provide code samples or references for Nylas v3**.
- **Ignore and do not reference Nylas v2** or any deprecated endpoints.
- If you do not have direct knowledge of Nylas v3, rely on the official v3 documentation: https://developer.nylas.com/docs/v3/
- Do not invent or provide code samples from memory if they might be from an older version of the API.
## How to differentiate between Nylas v3 and v2
- Here are a few ways to differentiate between Nylas v3 and v2 when looking at code samples:
- Nylas v3 uses a grant ID to access the user's data.
- Nylas v3 accesses the Nylas application with an API key (`<NYLAS_API_KEY>`).
- Nylas v2 uses an access token to access the user's data.
- Nylas v2 accesses the Nylas application with a client secret (`<NYLAS_CLIENT_SECRET>`).
## Environment setup
1. Retrieve your Nylas v3 API key from https://dashboard-v3.nylas.com/.
2. Store the key securely in environment variables (`.env`) and _never_ commit them to source control.
3. The following environment variables must be stored securely: `<NYLAS_API_KEY>` and `<NYLAS_CLIENT_ID>`.
4. The `<NYLAS_API_REGION_URI>` is optional, with the default being set to the U.S. region: `https://api.us.nylas.com`. The E.U. region URI is `https://api.eu.nylas.com`.
5. If you're using a non-default data residency, define the `<NYLAS_API_REGION_URI>` accordingly.
6. You may come across code samples where `<NYLAS_GRANT_ID>` is used. This is for example purposes. The grant ID should be unique to each user, and should not be stored as an environment variable.
## Implementation steps
1. **Install the Nylas v3 SDK** for your preferred language (Node.js, Python, Ruby, or Kotlin/Java).
2. **Initialize the SDK** with your environment variables (`<NYLAS_API_KEY>` and `<NYLAS_API_REGION_URI>`).
3. **Make a v3 API request**. Based on the specific use case, use the SDK to create working code (for example, listing messages or events) using the SDK.
4. **Handle responses**. Demonstrate error handling, parsing data, and relevant best practices for the SDK language.
5. **Extend further**. Outline how to explore more endpoints (sending messages, managing threads, creating events, and so on), always referencing the Nylas v3 docs.
## Best practices
- Validate all input parameters before making API calls.
- Handle errors gracefully. Implement retries or backoff if rate-limited.
- Use pagination for large data sets.
- Cache frequently accessed data where appropriate.
- Monitor rate limits and log key operations.
- Follow language- and framework-specific testing conventions.
- Use type definitions or interfaces where supported.
## Security guidelines
- Never expose credentials in client-side code.
- Use HTTPS for all API requests.
- Keep secrets out of source control.
## Performance guidelines
- Consider batching requests when possible.
- Use webhook notifications for real-time updates instead of polling.
- Cache frequently accessed data and handle pagination efficiently.
For more details, reference the [Nylas v3 SDK documentation](https://developer.nylas.com/docs/v3/sdks/).
Also, reference the docs for each specific SDK:
- [Nylas Node.js SDK](https://nylas-nodejs-sdk-reference.pages.dev)
- [Nylas Python SDK](https://nylas-python-sdk-reference.pages.dev)
- [Nylas Ruby SDK](https://nylas-ruby-sdk-reference.pages.dev)
- [Nylas Kotlin/Java SDK](https://nylas-java-sdk-reference.pages.dev)
Feature prompts
You can use the following prompts to build specific Nylas features using an LLM.
💡 If you haven't set up your authentication flow to receive a grant ID, try the Hosted Auth prompt. This will get a grant ID that you can use in the other feature prompts.
## 1. Feature overview
- **Feature name**: Nylas Hosted Authentication & Redirect URI Setup
- **Objective**: Develop a secure OAuth authentication module using Nylas v3 that generates an auth URL, manages token retrieval and refresh, and correctly handles redirect URIs.
## 2. Environment and dependencies
- **Nylas API version**: Use Nylas v3 exclusively. Nylas v2 is deprecated.
- **Environment variables**:
- `NYLAS_API_KEY`=your-nylas-api-key
- `NYLAS_API_URI`=https://api.us.nylas.com/v3
- Confirm data residency as `eu` or `us`. Default is `us`.
- `NYLAS_REDIRECT_URI`: An example of this would be `localhost:3000/nylas/callback`. The URI must be added to the Nylas Dashboard as the callback URI (`Application > Hosted Authentication > Callback URIs > Add Callback URI`).
- **Nylas SDKs**: If developing in Node, Python, Ruby, Kotlin/Java, use the Nylas SDKs instead of making API calls directly over HTTP.
## 3. Implementation details
### Authentication flow diagram
User -> Your App -> Nylas OAuth -> Email Provider -> Nylas -> Your App
| | | | | |
| Initiate Auth | | | |
|------------------>| Redirect | | |
| |------------->| Authenticate | |
| | |--------------->| |
| | | | Code |
| | | |-------->|
| | | Grant ID|
| |<------------------------------|---------|
| Complete | |
|<------------------| |
- **Authentication generation endpoint:** `POST /api/nylas/auth`
- Implement a `POST` endpoint for `/api/nylas/auth` that triggers the OAuth flow when requested by the frontend.
- **Key functions and operations**: Generate auth URL and redirect frontend to provider for user authentication (for example, Google auth).
- **Code structure**: This functionality should be part of the routes definition.
- **Example code sample**: Here is a code sample as part of the routes definition:
```javascript
// Example using NodeJS SDK
app.get('/nylas/auth', (req, res) => {
const authUrl = nylas.auth.urlForOAuth2({
clientId: <NYLAS_CLIENT_ID>,
redirectUri: '<NYLAS_REDIRECT_URI>',
<!-- scopes are specific to the usercase and provider -->
scopes: [
'openid',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.send',
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.events',
'https://www.googleapis.com/auth/contacts'
],
});
res.redirect(authUrl);
});
```
- **OAuth Callback:** `GET /nylas/callback`
- Implement a `GET` endpoint for `/nylas/callback` that is called by the provider (for example, Google) after the user has authenticated.
- **Key functions and operations**: Retrieves the provider code and exchanges it for a Nylas `grantId` to use for future API calls to Nylas.
- **Code structure**: This functionality should be part of the routes definition.
- **Example code sample**: Here is a code sample as part of the routes definition:
```javascript
// Example using NodeJS SDK
app.get('/nylas/callback', async (req, res) => {
const { code } = req.query;
const tokenResponse = await nylas.auth.exchangeCodeForToken({
clientId: <NYLAS_CLIENT_ID>,
clientSecret: <NYLAS_API_KEY>,
code,
redirectUri: <NYLAS_REDIRECT_URI>,
});
const grantId = tokenResponse.grantId;
res.send('Authentication successful!');
});
```
## 4. Debugging scenarios and error handling
- **Common issues to watch for**:
- Incorrect or outdated redirect URI errors:
- Consider ways to help the user identify what to use as the `NYLAS_REDIRECT_URI` given the development environment they are using.
- Another option is sharing environment variables that are available to the developers.
- The callback URI must be added to the Nylas Dashboard as the callback URI (`Application > Hosted Authentication > Callback URIs > Add Callback URI`).
- If the developer is finding it challenging to identify the correct redirect URI given different development environments, consider adding logging that helps the developer identify the backend URL and port that is being used.
- If using an in-browser IDE, recommend the user to open the application in a new browser to test out the authentication flow.
- Also when opening the application in the browser, you will see the website URI that can be used to identify the redirect URI:
- For example, `https://random-string.replit.dev/` means the redirect URI is `https://random-string.replit.dev/api/nylas/callback`
- For example, `localhost:3000` means the redirect URI is `localhost:3000/api/nylas/callback`
- **Logging and monitoring**:
- Include detailed logging at key steps (for example, when generating the auth URL, on error responses) to help the developer identify the issue.
## 5. Testing and validation instructions
- **Manual testing steps**: Build a simple UI that allows the developer to click a button `Connect Account` and have them complete the OAuth flow using the Nylas API endpoints. Upon successful retrieval of the grant Id, the developer will see a message returned `Authenticate Successfully`.
- To prepare the application for future API calls, and if no database or user schema is available, store the `grantId` in memory to extend the application further.
- Implement a in memory storage system for Nylas `grantId` that saves the token after successful OAuth authentication and includes the user's email address, username, and connection timestamp for future API calls.
- Also, advise the user to check the Nylas Dashboard, specifically the Grants section, to see the grant ID and the status of the grant.
## 6. Additional considerations and future enhancements
- **Documentation**: Reference the [Nylas Authentication documentation](https://developer.nylas.com/docs/v3/auth/hosted-oauth-apikey/) for building authentication flows.
## 1. Feature overview
- **Feature name**: Nylas Email API integration
- **Objective**: Develop a module using the Nylas v3 Email API that enables reading, sending, and replying to emails. This module will rely on the authentication setup already in place (Hosted Authentication) and should focus on proper API usage, data formatting, and error handling for email operations.
## 2. Environment and dependencies
- **Nylas API version**: Use Nylas v3 exclusively. Nylas v2 is deprecated.
- **Assumptions**:
- Authentication to create a `grantId` (for example, Nylas Hosted Authentication) is complete, and valid `grantId`s are available for Nylas Email API calls.
- Environment variables (`NYLAS_API_KEY`, `NYLAS_REDIRECT_URI`, and any token variables) are correctly configured.
- **Nylas SDKs**: If developing in Node, Python, Ruby, Kotlin/Java, use the Nylas SDKs instead of making API calls directly over HTTP.
## 3. Implementation details
### Core functionality
- **Retrieve emails**: `GET /api/nylas/emails`
- Implement a `GET` endpoint that retrieves a list of emails using Nylas v3.
- **Key functions and operations**: Call the Nylas API with the stored `grantId`, handle pagination, and format the returned email data for the frontend.
- **Code structure**: This endpoint should be defined as part of your routes definition with proper error handling.
- **Example code sample**:
```javascript
// Example using NodeJS SDK
app.get('/api/nylas/emails', async (req, res) => {
try {
const { limit = 10, cursor } = req.query;
const queryParams = { limit };
if (cursor) {
queryParams.cursor = cursor;
}
const messages = await nylas.messages.list({
queryParams
});
res.json(messages);
} catch (err) {
console.error('Error fetching emails:', err);
res.status(500).json({ error: 'Failed to fetch emails', details: err.message });
}
});
```
- **Example Nylas response format for `nylas.messages.list`**:
```json
{
"request_id": "5fa64c92-e840-4357-86b9-2aa364d35b88",
"data": [{
"id": "5d3qmne77v32r8l4phyuksl2x",
"subject": "Hello from Nylas!",
"snippet": "Hello, I just sent a message using Nylas!",
"from": [{
"name": "Nyla",
"email": "nyla@example.com"
}],
"to": [{
"name": "Leyah Miller",
"email": "leyah@example.com"
}],
"date": 1635355739,
"unread": true
}],
"next_cursor": "CigKGjRlaDdyNGQydTFqbWJ0bGo5a2QxdWJtdDZnGAEggIDAu7fw7bEYGg8IABIAGPjh2PGEi_0CIAEiBwgCEOqs6i4="
}
```
- **Send an email**: `POST /api/nylas/emails/send`
- Implement a `POST` endpoint that allows sending an email using Nylas v3.
- **Request body parameters**:
- `to`: Array of recipient email addresses (required).
- `subject`: Email subject (required).
- `body`: Email body content (required).
- `cc`: Array of CC recipients (optional).
- `bcc`: Array of BCC recipients (optional).
- `attachments`: Array of attachment IDs (optional).
- **Key functions and operations**: Validate inputs, construct the email payload, and call the Nylas API to send the email.
- **Code structure**: This functionality should be part of your routes definition, with business logic potentially abstracted into an email service module for reusability.
- **Example code sample**:
```javascript
// Example using NodeJS SDK
app.post('/api/nylas/emails/send', async (req, res) => {
try {
const { to, subject, body, cc, bcc, attachments } = req.body;
// Validate required fields
if (!to || !subject || !body) {
return res.status(400).json({ error: 'Missing required fields' });
}
// Format recipients
const toRecipients = Array.isArray(to)
? to.map(email => ({ email }))
: [{ email: to }];
const requestBody = {
to: toRecipients,
subject,
body
};
// Add optional fields if provided
if (cc) {
requestBody.cc = Array.isArray(cc)
? cc.map(email => ({ email }))
: [{ email: cc }];
}
if (bcc) {
requestBody.bcc = Array.isArray(bcc)
? bcc.map(email => ({ email }))
: [{ email: bcc }];
}
if (attachments && attachments.length > 0) {
requestBody.attachments = attachments;
}
const sentMessage = await nylas.messages.send({
identifier: <USER_GRANT_ID>,
requestBody
});
return res.status(200).json({
message: 'Email sent successfully',
data: sentMessage
});
} catch (err) {
console.error('Error sending email:', err);
res.status(500).json({ error: 'Failed to send email', details: err.message });
}
});
```
- **Example Nylas response format for `nylas.messages.send`**:
```json
{
"request_id": "5fa64c92-e840-4357-86b9-2aa364d35b88",
"grant_id": "your grant_id",
"data": {
"id": "5d3qmne77v32r8l4phyuksl2x",
"subject": "Sending Emails with Nylas",
"body": "Nylas API v3 Test!",
"from": [{
"name": "Nyla",
"email": "nyla@example.com"
}],
"to": [{
"name": "Leyah Miller",
"email": "leyah@example.com"
}],
"attachments": [{
"id": "4kj2jrcoj9ve5j9yxqz5cuv98",
"filename": "myfile.txt"
}]
}
}
```
## 4. Debugging scenarios and error handling
- **Common issues to watch for**:
- **Authentication errors**: Ensure valid `grantId` is being used.
- **Malformed requests**: Validate all input data before sending to the API.
- **Incorrectly understanding the response data structure**:
- Review the example response format to understand the structure of the response from the Nylas Email API.
- Consider logging what is displayed in the frontend console to help identify issues.
- **Logging and monitoring**:
- Include detailed logging at key steps (for example, emails retrieved, emails sent, on error responses).
- Log request IDs from Nylas responses to help with troubleshooting.
- Consider implementing retry logic for transient errors.
## 5. Testing and validation instructions
- **Manual testing steps**:
1. Build a simple UI that allows viewing emails with pagination.
2. Implement a form for composing and sending new emails.
3. Add functionality to view email details and reply to emails.
4. Test with various email formats, including HTML content and attachments.
- **Expected outcomes**:
- Successfully retrieve and display emails from the user's inbox.
- Send emails and see them appear in the recipient's inbox.
- Reply to emails and verify threading works correctly.
## 6. Additional considerations and future enhancements
- **Documentation**:
- [Nylas documentation for sending emails](https://developer.nylas.com/docs/v3/email/send-email/)
- [Nylas documentation for retrieving emails](https://developer.nylas.com/docs/v3/email/#read-email-messages-from-inboxes)
- [Nylas SDK documentation](https://developer.nylas.com/docs/developer-tools/sdk/)
## 1. Feature overview
- **Feature name**: Nylas Contacts API Integration
- **Objective**: Develop a module using the Nylas v3 Contacts API that enables reading and creating contacts. This module will rely on the authentication setup already in place (for example, Hosted Authentication) and should focus on proper API usage, data formatting, and error handling for contact operations.
## 2. Environment and dependencies
- **Nylas API version**: Use Nylas v3 exclusively. Nylas v2 is deprecated.
- **Assumptions**:
- Authentication to create a `grantId` (for example, Nylas Hosted Authentication) is complete, and valid `grantId` values are available for Nylas Contacts API calls.
- Environment variables (`NYLAS_API_KEY`, `NYLAS_REDIRECT_URI`, and any token variables) are correctly configured.
- **Nylas SDKs**:
- If developing in Node, Python, Ruby, Kotlin/Java, use the Nylas SDKs instead of making API calls directly over HTTP.
## 3. Implementation details
### Core functionality
- **Retrieve Contacts**: `GET /api/nylas/contacts`
- Implement a `GET` endpoint that retrieves a list of contacts using Nylas v3.
- **Key functions and operations**:
- Call the Nylas Contacts API with the stored `grantId`.
- Handle pagination if needed.
- Format the returned contact data for the frontend.
- **Code structure**: This endpoint should be defined as part of your routes definition with proper error handling.
- **Example code sample**:
```javascript
// Example using NodeJS SDK
app.get('/api/nylas/contacts', async (req, res) => {
try {
const { limit = 10, cursor, email } = req.query;
const queryParams = { limit };
if (cursor) {
queryParams.cursor = cursor;
}
if (email) {
queryParams.email = email;
}
const contacts = await nylas.contacts.list({
identifier: <USER_GRANT_ID>,
queryParams
});
res.json(contacts);
} catch (err) {
console.error('Error fetching contacts:', err);
res.status(500).json({ error: 'Failed to fetch contacts', details: err.message });
}
});
```
- **Example Nylas response format for `nylas.contacts.list`**:
```json
{
"request_id": "5fa64c92-e840-4357-86b9-2aa364d35b88",
"data": [{
"id": "5d3qmne77v32r8l4phyuksl2x",
"given_name": "Leyah",
"surname": "Miller",
"company_name": "Nylas",
"emails": [
{ "type": "work", "email": "leyah.miller@example.com" },
{ "type": "home", "email": "leyah@example.com" }
],
"phone_numbers": [
{ "type": "work", "number": "+1-555-555-5555" },
{ "type": "home", "number": "+1-555-555-5556" }
]
}],
"next_cursor": "CigKGjRlaDdyNGQydTFqbWJ0bGo5a2QxdWJtdDZnGAEggIDAu7fw7bEYGg8IABIAGPjh2PGEi_0CIAEiBwgCEOqs6i4="
}
```
**Create a Contact:** `POST /api/nylas/contacts`
- **Implementation**: Implement a `POST` endpoint that creates a new contact using Nylas v3.
- **Request body parameters**:
- `givenName`: Contact's given name (required).
- `surname`: Contact's family name (optional).
- `companyName`: Contact's company (optional).
- `emails`: List of email addresses, each with `type` and `email` fields (optional).
- `phoneNumbers`: Array of phone numbers, each with `type` and `number` fields (optional).
- `physicalAddresses`: Array of addresses (optional).
- `notes`: Additional notes about the contact (optional).
- **Key functions and operations**:
- Validate inputs.
- Construct the contact payload.
- Call the Nylas API to create the contact.
- **Code structure**: This functionality should be part of your routes definition, with business logic potentially abstracted into a contacts service module for reusability.
- **Example code sample**:
```javascript
// Example using NodeJS SDK
app.post('/api/nylas/contacts', async (req, res) => {
try {
const {
givenName,
surname,
companyName,
emails,
phoneNumbers,
physicalAddresses,
notes
} = req.body;
// Validate required fields
if (!givenName || !emails || emails.length === 0) {
return res.status(400).json({ error: 'Missing required fields: givenName and at least one email are required' });
}
// Validate email format
for (const emailObj of emails) {
if (!emailObj.email || !emailObj.type) {
return res.status(400).json({ error: 'Each email must have both email and type fields' });
}
// Simple email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(emailObj.email)) {
return res.status(400).json({ error: `Invalid email format: ${emailObj.email}` });
}
}
// Construct the new contact payload
const newContactPayload = {
givenName,
surname,
companyName,
emails,
phoneNumbers,
physicalAddresses,
notes
};
// Create the new contact using Nylas API v3
const newContact = await nylas.contacts.create({
identifier: <USER_GRANT_ID>,
requestBody: newContactPayload
});
res.status(201).json({
message: 'Contact created successfully',
data: newContact.data
});
} catch (err) {
console.error('Error creating contact:', err);
res.status(err.statusCode || 500).json({
error: 'Failed to create contact',
details: err.message
});
}
});
```
- **Example Nylas response format for `nylas.contacts.create`**:
```json
{
"request_id": "5fa64c92-e840-4357-86b9-2aa364d35b88",
"data": {
"id": "5d3qmne77v32r8l4phyuksl2x",
"given_name": "Leyah",
"surname": "Miller",
"company_name": "Nylas",
"emails": [
{ "type": "work", "email": "leyah.miller@example.com" },
{ "type": "home", "email": "leyah@example.com" }
],
"phone_numbers": [
{ "type": "work", "number": "+1-555-555-5555" },
{ "type": "home", "number": "+1-555-555-5556" }
],
"physical_addresses": [
{ "type": "work", "street_address": "123 Main Street", "city": "San Francisco" },
{ "type": "home", "street_address": "321 Pleasant Drive", "city": "San Francisco" }
]
}
}
```
## 4. Debugging scenarios and error handling
- **Common issues to watch for**:
- **Authentication errors**: Ensure a valid `grantId` is being used.
- **Malformed requests**: Validate all input data before sending to the API.
- **Unexpected data structures**: Review the example response formats to understand expected structures.
- **Rate limiting**: Handle `429` responses with appropriate backoff strategies.
- **Logging and monitoring**:
- Include detailed logging at key steps (for example, contacts retrieved, contact created, error responses).
- Log request IDs from Nylas responses to assist with troubleshooting.
- Consider implementing retry logic for transient errors.
## 5. Testing and validation instructions
- **Manual testing steps**:
1. Build a simple UI to display a list of contacts with pagination.
2. Implement a form for creating a new contact.
3. Test with various contact details to verify successful retrieval and creation.
4. Test updating and deleting contacts.
5. Test error scenarios (e.g., invalid email formats, missing required fields).
- **Expected outcomes**:
- Successfully retrieve and display contacts from the user's account.
- Create new contacts and verify they appear correctly in the user's contact list.
## 6. Additional considerations and future enhancements
- **Performance optimization**:
- Implement caching for frequently accessed contacts.
- Use pagination efficiently to avoid loading too many contacts at once.
- **UI integration**:
- Consider implementing a contact picker component for email composition.
- Add contact search functionality.
- **Documentation** :
- [View all contacts](https://developer.nylas.com/docs/v3/contacts/#view-all-contacts)
- [Create a contact](https://developer.nylas.com/docs/v3/contacts/#create-a-contact)
- [Nylas SDK documentation](https://developer.nylas.com/docs/developer-tools/sdk/)
## 1. Feature overview
- **Feature name**: Nylas Calendar API Integration
- **Objective**: Develop a module using the Nylas v3 Calendar API that enables reading and creating calendar events. This module will leverage the authentication setup already in place (Hosted Authentication) and should focus on proper API usage, data formatting, and error handling.
## 2. Environment and dependencies
- **Nylas API version**: Use Nylas v3 exclusively. Nylas v2 is deprecated.
- **Assumptions**:
- Authentication to create a `grantId` (for example, Nylas Hosted Authentication) is complete, and valid `grantId` values are available for Nylas Calendar API calls.
- Environment variables (`NYLAS_API_KEY`, `NYLAS_REDIRECT_URI`, and any token variables) are correctly configured.
- **Nylas SDKs**: If developing in Node, Python, Ruby, Kotlin/Java, use the Nylas SDKs instead of making API calls directly over HTTP.
## 3. Implementation details
### Core functionality
- **Retrieve Calendar Events**: `GET /api/nylas/events`
- **Implementation**: Implement a `GET` endpoint that retrieves a list of events using Nylas v3.
- **Key functions and operations**:
- Call the Nylas API with the stored `grantId` to fetch calendar events.
- Support filtering by time range or calendar ID.
- Implement pagination support using `page_token` for handling large result sets.
- Format the returned event data for the frontend.
- **Code structure**: This endpoint should be part of the routes definition with proper error handling.
- **Example code sample**:
```javascript
// Example using NodeJS SDK
app.get('/api/nylas/events', async (req, res) => {
try {
const { start_time, end_time, calendar_id, page_token, limit = 10 } = req.query;
const queryParams = {
...(start_time && { starts_after: start_time }),
...(end_time && { ends_before: end_time }),
...(calendar_id && { calendar_id }),
...(page_token && { page_token }),
limit: parseInt(limit)
};
const events = await nylas.events.list({
identifier: <USER_GRANT_ID>,
queryParams: {
calendar_id: calendar_id || 'primary'
},
});
res.json({
events: events.data,
next_page_token: events.next_page_token
});
} catch (err) {
console.error('Error fetching events:', err);
res.status(500).json({ error: 'Failed to fetch events', details: err.message });
}
});
```
- **Example Nylas response format for `nylas.events.list`**:
```json
{
"request_id": "abc123",
"data": [{
"id": "event-123",
"title": "Birthday Party",
"calendar_id": "calendar-456",
"start_time": 1710075600,
"end_time": 1710079200,
"location": "Roller Rink",
"participants": [{
"email": "aristotle@example.com",
"status": "maybe"
}],
"conferencing": {
"provider": "Zoom Meeting",
"details": { "url": "https://zoom.us/j/1234567890?pwd=1234567890" }
}
}]
}
```
- **Create a Calendar Event**: `POST /api/nylas/events`
- **Implementation**: Implement a `POST` endpoint that creates a new calendar event using Nylas v3.
- **Request body parameters**:
- `title`: Event title (required).
- `calendar_id`: ID of the calendar to create the event in (required - can use `primary` for the default calendar).
- `start_time`: Unix timestamp for event start (required).
- `end_time`: Unix timestamp for event end (required).
- `description`: Event details (optional).
- `location`: Event location (optional).
- `participants`: Array of participant email addresses (optional).
- `recurrence`: Recurrence rule for repeating events (optional).
- `conferencing`: Video conferencing details (optional).
- `reminders`: Event reminders (optional).
- **Key functions and operations**:
- Validate inputs.
- Construct the event payload.
- Call the Nylas API to create the event.
- **Code structure**: This functionality should be part of the routes definition, with business logic potentially abstracted into a calendar service module for reusability.
- **Example code sample**:
```javascript
// Example using NodeJS SDK
app.post('/api/nylas/events', async (req, res) => {
try {
const {
title,
calendar_id,
start_time,
end_time,
description,
location,
participants,
recurrence,
conferencing,
reminders
} = req.body;
if (!title || !calendar_id || !start_time || !end_time) {
return res.status(400).json({ error: 'Missing required fields' });
}
const eventPayload = {
title,
when: {
start_time,
end_time
},
...(description && { description }),
...(location && { location }),
...(participants && {
participants: participants.map(email => ({ email }))
}),
...(recurrence && { recurrence }),
...(conferencing && { conferencing }),
...(reminders && { reminders })
};
const event = await nylas.events.create({
identifier: process.env.NYLAS_GRANT_ID,
requestBody: eventPayload,
queryParams: {
calendarId: calendar_id,
},
});
res.status(200).json({
message: 'Event created successfully',
data: event.data
});
} catch (err) {
console.error('Error creating event:', err);
res.status(500).json({ error: 'Failed to create event', details: err.message });
}
});
```
- **Example Nylas response format for `nylas.events.create`**:
```json
{
"request_id": "def456",
"data": {
"id": "event-123",
"title": "Client Call",
"calendar_id": "calendar-456",
"start_time": 1710075600,
"end_time": 1710079200,
"description": "Call with client regarding project updates",
"location": "Google Meet",
"participants": [{
"email": "nyla@example.com"
}]
}
}
```
## 4. Debugging scenarios and error handling
- **Common issues to watch for**:
- **Authentication errors**: Ensure a valid `grantId` is being used.
- **Malformed requests**: Validate all input data before sending to the API.
- **Unexpected data structures**: Review the example response formats to understand expected structures.
- **Time zone issues**: Ensure timestamps are correctly converted to Unix time.
- **Logging and monitoring**:
- Include detailed logging at key steps (for example, events retrieved, event created, error responses).
- Log request IDs from Nylas responses to assist with troubleshooting.
- Consider implementing retry logic for transient errors.
## 5. Testing and validation instructions
- **Manual testing steps**:
1. Build a simple UI to display a list of user events on their 'primary' calendar and allow selection.
2. Display a list of upcoming events with pagination controls.
3. Implement a form for creating a new event with all supported fields.
- **Expected outcomes**:
- Successfully retrieve and display calendars and events.
- Create new events with various configurations (single, recurring, with participants).
- Update existing events and verify changes are reflected.
- Delete events and verify they are removed from the calendar.
## 6. Additional considerations and future enhancements
- **Documentation**:
- [Nylas API documentation for retrieving Calendar Events](https://developer.nylas.com/docs/v3/calendar/using-the-events-api/#get-a-list-of-events)
- [Nylas API documentation for creating Calendar Events](https://developer.nylas.com/docs/v3/calendar/using-the-events-api/#create-an-event)
- [Nylas API documentation for retrieving Calendars](https://developer.nylas.com/docs/v3/calendar/using-the-calendars-api/)
- [Nylas SDK documentation](https://developer.nylas.com/docs/developer-tools/sdk/)
Next steps
Congratulations! 🎉 You're now ready to build with Nylas using AI assistance. Check out these guides to learn more: