From 54977161bfe75c27f0b51448df81e59d047d50f7 Mon Sep 17 00:00:00 2001 From: Aaron de Mello Date: Wed, 4 Nov 2026 14:12:30 -0500 Subject: [PATCH 1/3] feat(events): add batch operations (TT-5546) --- CHANGELOG.md | 3 + README.md | 51 ++++++++ lib/nylas/resources/events.rb | 35 +++++ spec/nylas/resources/events_batch_spec.rb | 153 ++++++++++++++++++++++ 4 files changed, 242 insertions(+) create mode 100644 spec/nylas/resources/events_batch_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 86571aa2..5460d9e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Changelog +### Unreleased +* Added Events batch endpoint (Google and Microsoft). + ### [6.9.0] / 2026-10-26 * Required HTTParty 0.24.0 or later to exclude versions affected by CVE-2025-68696 (potential SSRF and API key leakage) * Treat 207 Multi-Status responses as successful, so a response that carries partial results is returned instead of raising an error diff --git a/README.md b/README.md index 7a44fc0b..e2355700 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,57 @@ For step-by-step walkthroughs, see the developer guides: - [Agent Accounts](https://developer.nylas.com/docs/v3/agent-accounts/) - [Notifications & webhooks](https://developer.nylas.com/docs/v3/notifications/) +### Batch event operations + +For Google and Microsoft calendars, create, update, and delete events in one call. The +`body` hashes use the same fields as `events.create` and `events.update`. Query parameters +apply to every operation: `calendar_id` is required; `notify_participants`, `grant_email`, +`tentative_as_busy`, and `select` (a comma-separated field list) are optional. Omitting +`notify_participants` preserves the server default of `true`; Microsoft rejects `false`. + +```ruby +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" } +] +query_params = { calendar_id: "primary" } +results, request_id, headers = nylas.events.batch( + identifier: "GRANT_ID", + query_params: query_params, + request_body: { operations: operations } +) + +results.each_with_index do |item, index| + puts "Operation #{index}: #{item[:status]}" + # Successful creates/updates have an event in item[:data]; deletes have no data. + next unless item[:error] + + # Never retry these operations: the provider already created the event. + next if item[:provider_event_created] + next unless [429, 503].include?(item[:status]) + delay = item[:retry_after] + next unless delay.is_a?(Numeric) && delay.finite? && delay >= 0 + + # This example retries an eligible operation once, after the provider's delay. + # The SDK leaves retry decisions to your application; inspect this result too. + sleep(delay) + retry_results, _retry_request_id = nylas.events.batch( + identifier: "GRANT_ID", + query_params: query_params, + request_body: { operations: [operations[index]] } + ) + puts "Retry status: #{retry_results.first[:status]}" +end +``` + +The return tuple is `[results, request_id, headers]`, without a pagination cursor. +Results preserve operation order and use symbol keys. HTTP 207 returns normally, even +if all operations failed: check each item's `status` and `error`. Errors contain `type`, +`message`, and optional `provider_error`; retry metadata is available as `retry_after` +(seconds, including zero) and `provider_event_created`. Invalid whole requests raise +the usual `Nylas::NylasApiError`. The API validates batch sizes and operations. + ### Error handling The SDK raises typed errors you can rescue. API failures raise `Nylas::NylasApiError` (with `type`, `status_code`, `request_id`, `provider_error`, `headers`); OAuth failures raise `Nylas::NylasOAuthError`; request timeouts raise `Nylas::NylasSdkTimeoutError`. diff --git a/lib/nylas/resources/events.rb b/lib/nylas/resources/events.rb index f0e091f9..13bc972a 100644 --- a/lib/nylas/resources/events.rb +++ b/lib/nylas/resources/events.rb @@ -2,6 +2,7 @@ require_relative "resource" require_relative "../handler/api_operations" +require "uri" module Nylas # Nylas Events API @@ -51,6 +52,40 @@ def create(identifier:, request_body:, query_params:) ) end + # Create, update, or delete events in one request (Google and Microsoft). + # + # Results follow the operation order. Both 200 and 207 responses return normally; + # inspect each result's status and error, even when every operation failed. + # The API validates the operations and batch size. No operations are retried automatically. + # + # @param identifier [String] Grant ID or email account in which to modify events. + # @param request_body [Hash] The batch request. + # @option request_body [Array] :operations The event operations to execute. + # Each operation has a :method of "create", "update", or "delete". + # Create and update require :body, using the same event Hash as {#create} or {#update}. + # Update and delete require :event_id [String]. + # @param query_params [Hash] Query parameters applied to every operation. + # @option query_params [String] :calendar_id The required calendar ID. + # @option query_params [Boolean] :notify_participants Defaults to true on the server. + # Microsoft does not support false. + # @option query_params [String] :grant_email Optional grant email. + # @option query_params [Boolean] :tentative_as_busy Whether tentative events count as busy. + # @option query_params [String] :select Comma-separated event fields to return. + # @return [Array(Array, String, Hash)] Ordered results, API request ID, and response headers. + # Each result has :status [Integer], optional :data [Hash] with the event for a successful + # create or update, and optional :error [Hash] with :type [String], :message [String], and + # :provider_error [Hash]. A successful delete has no :data. Failed results may include + # :retry_after [Numeric] (seconds, including zero) and :provider_event_created [Boolean]. + # Never retry an operation with :provider_event_created set to true; it would create a duplicate. + def batch(identifier:, request_body:, query_params:) + encoded_identifier = URI.encode_www_form_component(identifier).gsub("+", "%20") + post( + path: "#{api_uri}/v3/grants/#{encoded_identifier}/events/batch", + query_params: query_params, + request_body: request_body + ) + end + # Update an event. # # @param identifier [String] Grant ID or email account in which to update an object. diff --git a/spec/nylas/resources/events_batch_spec.rb b/spec/nylas/resources/events_batch_spec.rb new file mode 100644 index 00000000..b948216a --- /dev/null +++ b/spec/nylas/resources/events_batch_spec.rb @@ -0,0 +1,153 @@ +# frozen_string_literal: true + +require "webmock/rspec" + +describe Nylas::Events do + let(:events) { described_class.new(client) } + let(:path) { "#{api_uri}/v3/grants/grant-123/events/batch" } + let(:query_params) do + { + calendar_id: "primary", + notify_participants: false, + grant_email: "user@example.com", + tentative_as_busy: true, + select: "id,title,when" + } + end + let(:request_body) do + { + operations: [ + { method: "create", + body: { title: "Standup", when: { start_time: 1798794000, end_time: 1798795800 } } }, + { method: "update", event_id: "event-1", body: { title: "Renamed" } }, + { method: "delete", event_id: "event-2" } + ] + } + end + + describe "#batch" do + it "sends snake_case JSON and all query parameters and returns ordered results without a cursor" do + results = [ + { status: 200, + data: { id: "created-event", title: "Standup", when: request_body[:operations][0][:body][:when] } }, + { status: 200, data: { id: "event-1", title: "Renamed" } }, + { status: 200 } + ] + request = stub_request(:post, path) + .with( + query: query_params, + body: request_body.to_json, + headers: { "Content-Type" => "application/json" } + ) + .to_return( + status: 200, + body: { data: results, request_id: "batch-request" }.to_json, + headers: { "Content-Type" => "application/json", "X-Batch-Header" => "test-value" } + ) + + data, request_id, headers = events.batch(identifier: "grant-123", query_params: query_params, + request_body: request_body) + + expect(data).to eq(results) + expect(data.last).not_to have_key(:data) + expect(request_id).to eq("batch-request") + expect(headers["x-batch-header"]).to eq("test-value") + expect(request).to have_been_requested.once + end + + it "leaves optional query parameters unset to preserve server defaults" do + request = stub_request(:post, path) + .with(query: { calendar_id: "primary" }, body: request_body.to_json) + .to_return( + status: 200, + body: { data: [{ status: 200 }], request_id: "batch-request" }.to_json, + headers: { "Content-Type" => "application/json" } + ) + + events.batch(identifier: "grant-123", query_params: { calendar_id: "primary" }, + request_body: request_body) + + expect(request).to have_been_requested.once + end + + it "encodes the grant identifier as a single URL path segment" do + request = stub_request(:post, "#{api_uri}/v3/grants/grant%2Ffixture%3Fquery%23fragment/events/batch") + .with(query: query_params, body: request_body.to_json) + .to_return(status: 200, body: { data: [], request_id: "batch-request" }.to_json, + headers: { "Content-Type" => "application/json" }) + + events.batch(identifier: "grant/fixture?query#fragment", query_params: query_params, + request_body: request_body) + + expect(request).to have_been_requested.once + end + + it "returns mixed 207 results with provider errors and retry metadata without retrying" do + results = [ + { status: 200, data: { id: "created-event", title: "Standup" } }, + { + status: 429, + error: { type: "provider_error", message: "Try later", provider_error: { code: "throttled" } }, + retry_after: 0 + }, + { + status: 503, + error: { type: "provider_error", message: "Event synchronization failed" }, + retry_after: 3.5, + provider_event_created: true + } + ] + request = stub_request(:post, path) + .with(query: query_params, body: request_body.to_json) + .to_return(status: 207, body: { data: results, request_id: "partial-request" }.to_json, + headers: { "Content-Type" => "application/json" }) + + data, request_id = events.batch(identifier: "grant-123", query_params: query_params, + request_body: request_body) + + expect(data).to eq(results) + expect(data[1][:retry_after]).to eq(0) + expect(data[2][:provider_event_created]).to be(true) + expect(request_id).to eq("partial-request") + expect(request).to have_been_requested.once + end + + it "returns 207 normally when every operation failed" do + results = request_body[:operations].map do + { status: 404, error: { type: "not_found_error", message: "Event not found" } } + end + stub_request(:post, path) + .with(query: query_params, body: request_body.to_json) + .to_return(status: 207, body: { data: results, request_id: "failed-items-request" }.to_json, + headers: { "Content-Type" => "application/json" }) + + data, request_id = events.batch(identifier: "grant-123", query_params: query_params, + request_body: request_body) + + expect(data).to eq(results) + expect(request_id).to eq("failed-items-request") + end + + it "raises the normal API error for an invalid whole request" do + stub_request(:post, path) + .with(query: query_params, body: request_body.to_json) + .to_return( + status: 400, + body: { + request_id: "invalid-request", + error: { type: "invalid_request_error", message: "Invalid batch operations" } + }.to_json, + headers: { "Content-Type" => "application/json" } + ) + + expect do + events.batch(identifier: "grant-123", query_params: query_params, request_body: request_body) + end.to raise_error(Nylas::NylasApiError) { |error| + expect(error.status_code).to eq(400) + expect(error.request_id).to eq("invalid-request") + expect(error.type).to eq("invalid_request_error") + expect(error.message).to eq("Invalid batch operations") + } + end + end +end From 8b9c3def976e8e7dd2eba861bd9140439ec6872c Mon Sep 17 00:00:00 2001 From: Aaron de Mello Date: Wed, 4 Nov 2026 14:17:54 -0500 Subject: [PATCH 2/3] docs(events): move batch usage into an example --- README.md | 51 -------------- examples/events/event_batch_example.rb | 93 ++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 51 deletions(-) create mode 100755 examples/events/event_batch_example.rb diff --git a/README.md b/README.md index e2355700..7a44fc0b 100644 --- a/README.md +++ b/README.md @@ -115,57 +115,6 @@ For step-by-step walkthroughs, see the developer guides: - [Agent Accounts](https://developer.nylas.com/docs/v3/agent-accounts/) - [Notifications & webhooks](https://developer.nylas.com/docs/v3/notifications/) -### Batch event operations - -For Google and Microsoft calendars, create, update, and delete events in one call. The -`body` hashes use the same fields as `events.create` and `events.update`. Query parameters -apply to every operation: `calendar_id` is required; `notify_participants`, `grant_email`, -`tentative_as_busy`, and `select` (a comma-separated field list) are optional. Omitting -`notify_participants` preserves the server default of `true`; Microsoft rejects `false`. - -```ruby -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" } -] -query_params = { calendar_id: "primary" } -results, request_id, headers = nylas.events.batch( - identifier: "GRANT_ID", - query_params: query_params, - request_body: { operations: operations } -) - -results.each_with_index do |item, index| - puts "Operation #{index}: #{item[:status]}" - # Successful creates/updates have an event in item[:data]; deletes have no data. - next unless item[:error] - - # Never retry these operations: the provider already created the event. - next if item[:provider_event_created] - next unless [429, 503].include?(item[:status]) - delay = item[:retry_after] - next unless delay.is_a?(Numeric) && delay.finite? && delay >= 0 - - # This example retries an eligible operation once, after the provider's delay. - # The SDK leaves retry decisions to your application; inspect this result too. - sleep(delay) - retry_results, _retry_request_id = nylas.events.batch( - identifier: "GRANT_ID", - query_params: query_params, - request_body: { operations: [operations[index]] } - ) - puts "Retry status: #{retry_results.first[:status]}" -end -``` - -The return tuple is `[results, request_id, headers]`, without a pagination cursor. -Results preserve operation order and use symbol keys. HTTP 207 returns normally, even -if all operations failed: check each item's `status` and `error`. Errors contain `type`, -`message`, and optional `provider_error`; retry metadata is available as `retry_after` -(seconds, including zero) and `provider_event_created`. Invalid whole requests raise -the usual `Nylas::NylasApiError`. The API validates batch sizes and operations. - ### Error handling The SDK raises typed errors you can rescue. API failures raise `Nylas::NylasApiError` (with `type`, `status_code`, `request_id`, `provider_error`, `headers`); OAuth failures raise `Nylas::NylasOAuthError`; request timeouts raise `Nylas::NylasSdkTimeoutError`. diff --git a/examples/events/event_batch_example.rb b/examples/events/event_batch_example.rb new file mode 100755 index 00000000..aed94ee4 --- /dev/null +++ b/examples/events/event_batch_example.rb @@ -0,0 +1,93 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Run from the repository root: +# bundle exec ruby examples/events/event_batch_example.rb +# +# Required environment variables: +# NYLAS_API_KEY, NYLAS_GRANT_ID, NYLAS_CALENDAR_ID, +# NYLAS_UPDATE_EVENT_ID, NYLAS_DELETE_EVENT_ID +# Optional: NYLAS_API_URI (https://api.us.nylas.com or https://api.eu.nylas.com). +# +# Use a Google or Microsoft test calendar. This example creates one event, +# renames NYLAS_UPDATE_EVENT_ID, and deletes NYLAS_DELETE_EVENT_ID. +# The two existing event IDs must be different and belong to that calendar. +# Eligible failed operations are retried once after the provider's delay. + +$LOAD_PATH.unshift File.expand_path("../../lib", __dir__) +require "nylas" + +def main + required_env_vars = %w[ + NYLAS_API_KEY NYLAS_GRANT_ID NYLAS_CALENDAR_ID NYLAS_UPDATE_EVENT_ID NYLAS_DELETE_EVENT_ID + ] + if required_env_vars.any? { |name| ENV[name].nil? || ENV[name].strip.empty? } + warn "Set the required environment variables listed at the top of this example." + return 1 + end + + api_uri = ENV.fetch("NYLAS_API_URI", "https://api.us.nylas.com") + unless %w[https://api.us.nylas.com https://api.eu.nylas.com].include?(api_uri) + warn "Use a supported Nylas API URL." + return 1 + end + + nylas = Nylas::Client.new(api_key: ENV["NYLAS_API_KEY"], api_uri: api_uri) + grant_id = ENV["NYLAS_GRANT_ID"] + # Query parameters apply to every operation. Omit notify_participants to use + # the server default of true; Microsoft rejects false. Optional parameters also + # include grant_email, tentative_as_busy, and select (a comma-separated field list). + query_params = { calendar_id: ENV["NYLAS_CALENDAR_ID"] } + start_time = Time.now.to_i + (24 * 60 * 60) + operations = [ + { + method: "create", + body: { title: "Standup", when: { start_time: start_time, end_time: start_time + 1800 } } + }, + { method: "update", event_id: ENV["NYLAS_UPDATE_EVENT_ID"], body: { title: "Renamed" } }, + { method: "delete", event_id: ENV["NYLAS_DELETE_EVENT_ID"] } + ] + + # Bodies use the same event hashes as events.create and events.update. + # The tuple is [results, request_id, headers], without a pagination cursor. + results, _request_id, _headers = nylas.events.batch( + identifier: grant_id, + query_params: query_params, + request_body: { operations: operations } + ) + + # HTTP 207 returns normally, even if every operation failed. Results preserve + # operation order and use symbol keys. Check every result's status and error. + results.each_with_index do |item, index| + puts "Operation #{index}: #{item[:status]}" + # Successful creates/updates have an event in item[:data]; deletes have no data. + # Failed items have an error hash with type, message, and optional provider_error. + next unless item[:error] + + # Never retry these operations: the provider already created the event. + next if item[:provider_event_created] + next unless [429, 503].include?(item[:status]) + + delay = item[:retry_after] + next unless delay.is_a?(Numeric) && delay.finite? && delay >= 0 + + # Retry this eligible operation once. Zero is a valid delay. The SDK leaves + # retry decisions to the application and does not retry failed batch items. + sleep(delay) + retry_results, _retry_request_id = nylas.events.batch( + identifier: grant_id, + query_params: query_params, + request_body: { operations: [operations[index]] } + ) + puts "Retry status for operation #{index}: #{retry_results.first[:status]}" + end + + 0 +rescue StandardError + # Invalid whole requests raise Nylas::NylasApiError. Keep credentials and API + # response details out of example output, including unexpected failure output. + warn "Unable to complete the batch example." + 1 +end + +exit(main) if __FILE__ == $PROGRAM_NAME From 13fadba0996de71d427d3690d3b75ab2ac8d0884 Mon Sep 17 00:00:00 2001 From: Aaron de Mello Date: Wed, 4 Nov 2026 14:38:55 -0500 Subject: [PATCH 3/3] fix(events): reject invalid batch grant identifiers --- lib/nylas/resources/events.rb | 5 +++++ spec/nylas/resources/events_batch_spec.rb | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/lib/nylas/resources/events.rb b/lib/nylas/resources/events.rb index 13bc972a..5fc63ecc 100644 --- a/lib/nylas/resources/events.rb +++ b/lib/nylas/resources/events.rb @@ -77,7 +77,12 @@ def create(identifier:, request_body:, query_params:) # :provider_error [Hash]. A successful delete has no :data. Failed results may include # :retry_after [Numeric] (seconds, including zero) and :provider_event_created [Boolean]. # Never retry an operation with :provider_event_created set to true; it would create a duplicate. + # @raise [ArgumentError] If the grant identifier is not a nonblank String or is a URL dot segment. def batch(identifier:, request_body:, query_params:) + unless identifier.is_a?(String) && !identifier.strip.empty? && !%w[. ..].include?(identifier.strip) + raise ArgumentError, "Invalid grant identifier." + end + encoded_identifier = URI.encode_www_form_component(identifier).gsub("+", "%20") post( path: "#{api_uri}/v3/grants/#{encoded_identifier}/events/batch", diff --git a/spec/nylas/resources/events_batch_spec.rb b/spec/nylas/resources/events_batch_spec.rb index b948216a..fdc0ae3e 100644 --- a/spec/nylas/resources/events_batch_spec.rb +++ b/spec/nylas/resources/events_batch_spec.rb @@ -82,6 +82,16 @@ expect(request).to have_been_requested.once end + it "rejects blank, dot-segment, and non-string grant identifiers before sending any HTTP request" do + [nil, true, false, 123, {}, [], "", " ", "\t\n", ".", "..", " . ", "\t..\n"].each do |identifier| + expect do + events.batch(identifier: identifier, query_params: query_params, request_body: request_body) + end.to raise_error(ArgumentError, "Invalid grant identifier.") + end + + expect(WebMock).not_to have_requested(:any, /.*/) + end + it "returns mixed 207 results with provider errors and retry metadata without retrying" do results = [ { status: 200, data: { id: "created-event", title: "Standup" } },