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: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
93 changes: 93 additions & 0 deletions examples/events/event_batch_example.rb
Original file line number Diff line number Diff line change
@@ -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
40 changes: 40 additions & 0 deletions lib/nylas/resources/events.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

require_relative "resource"
require_relative "../handler/api_operations"
require "uri"

module Nylas
# Nylas Events API
Expand Down Expand Up @@ -51,6 +52,45 @@ 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<Hash>] :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<Hash>, 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.
# @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",
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.
Expand Down
163 changes: 163 additions & 0 deletions spec/nylas/resources/events_batch_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# 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 "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" } },
{
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
Loading