From 890c19da134eb0018d52be0e2effbe2ec42fea28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:41:25 +0100 Subject: [PATCH 01/30] test: add JSON fixtures for the email endpoints Add the JSON fixtures for the email, brand style and file endpoints. Add a helper that reads them in the specs. Co-Authored-By: Claude Opus 5.5 --- spec/fixtures/brand_styles.json | 50 ++++++++ spec/fixtures/campaign_simple_editor.json | 24 ++++ spec/fixtures/email.json | 81 +++++++++++++ spec/fixtures/email_block.json | 12 ++ spec/fixtures/email_block_created.json | 12 ++ spec/fixtures/email_block_moved.json | 12 ++ spec/fixtures/email_block_updated.json | 9 ++ .../email_block_validation_invalid.json | 5 + .../email_block_validation_valid.json | 1 + spec/fixtures/email_etag.json | 1 + spec/fixtures/email_html.json | 1 + spec/fixtures/email_settings.json | 111 ++++++++++++++++++ spec/fixtures/email_settings_validation.json | 9 ++ spec/fixtures/email_template.json | 1 + spec/fixtures/email_version.json | 1 + spec/fixtures/email_versions.json | 26 ++++ spec/fixtures/files.json | 44 +++++++ spec/support/json_fixture.rb | 18 +++ 18 files changed, 418 insertions(+) create mode 100644 spec/fixtures/brand_styles.json create mode 100644 spec/fixtures/campaign_simple_editor.json create mode 100644 spec/fixtures/email.json create mode 100644 spec/fixtures/email_block.json create mode 100644 spec/fixtures/email_block_created.json create mode 100644 spec/fixtures/email_block_moved.json create mode 100644 spec/fixtures/email_block_updated.json create mode 100644 spec/fixtures/email_block_validation_invalid.json create mode 100644 spec/fixtures/email_block_validation_valid.json create mode 100644 spec/fixtures/email_etag.json create mode 100644 spec/fixtures/email_html.json create mode 100644 spec/fixtures/email_settings.json create mode 100644 spec/fixtures/email_settings_validation.json create mode 100644 spec/fixtures/email_template.json create mode 100644 spec/fixtures/email_version.json create mode 100644 spec/fixtures/email_versions.json create mode 100644 spec/fixtures/files.json create mode 100644 spec/support/json_fixture.rb diff --git a/spec/fixtures/brand_styles.json b/spec/fixtures/brand_styles.json new file mode 100644 index 0000000..dab5ce3 --- /dev/null +++ b/spec/fixtures/brand_styles.json @@ -0,0 +1,50 @@ +{ + "data": { + "brand": { + "identifier": "account", + "name": "Brand styles", + "font_family": "Inter, sans-serif", + "primary_color": "#2cb191", + "secondary_color": "#1f2937", + "heading_color": "#111827", + "text_color": "#374151", + "border_color": "#e5e7eb", + "background_color": "#ffffff" + }, + "default": { + "identifier": "default-brand", + "name": "Default", + "font_family": "Inter, sans-serif", + "primary_color": "#09c269", + "secondary_color": "#000000", + "heading_color": "#000000", + "text_color": "#000000", + "border_color": "#e5e7eb", + "background_color": "#ffffff" + }, + "presets": [ + { + "identifier": "preset-business-casual", + "name": "Business casual", + "font_family": "Georgia, serif", + "primary_color": "#1d4ed8", + "secondary_color": "#1e3a8a", + "heading_color": "#0f172a", + "text_color": "#334155", + "border_color": "#cbd5e1", + "background_color": "#f8fafc" + }, + { + "identifier": "preset-retro", + "name": "Retro", + "font_family": "Courier New, monospace", + "primary_color": "#d97706", + "secondary_color": "#92400e", + "heading_color": "#451a03", + "text_color": "#78350f", + "border_color": "#fde68a", + "background_color": "#fffbeb" + } + ] + } +} diff --git a/spec/fixtures/campaign_simple_editor.json b/spec/fixtures/campaign_simple_editor.json new file mode 100644 index 0000000..d54f882 --- /dev/null +++ b/spec/fixtures/campaign_simple_editor.json @@ -0,0 +1,24 @@ +{ + "data": { + "id": "456", + "account_id": "1", + "name": "Simple editor campaign", + "type": "regular", + "status": "draft", + "default_email_id": "123", + "emails": [ + { + "id": "123", + "account_id": "1", + "emailable_id": "456", + "emailable_type": "campaigns", + "type": "builder_inline_email", + "from": "sender@example.com", + "from_name": "Sender", + "reply_to": "reply@example.com", + "subject": "Hello", + "is_designed": true + } + ] + } +} diff --git a/spec/fixtures/email.json b/spec/fixtures/email.json new file mode 100644 index 0000000..2762d5b --- /dev/null +++ b/spec/fixtures/email.json @@ -0,0 +1,81 @@ +{ + "data": { + "id": "123", + "type": "builder_inline_email", + "emailable_type": "campaigns", + "emailable_id": "456", + "settings": { + "brand": { + "mode": "account", + "font_family": "Inter, sans-serif", + "background_color": "#ffffff", + "text_color": "#000000", + "border_color": "#e5e7eb" + }, + "layout": {"width_mode": "default", "alignment": "center"}, + "typography": { + "link": {"color": "#2cb191"}, + "heading": { + "font_family": "Inter, sans-serif", + "font_weight": "700", + "line_height": "150%", + "letter_spacing": "0", + "h1": {"color": "#000000", "size": "32"}, + "h2": {"color": "#000000", "size": "24"}, + "h3": {"color": "#000000", "size": "20"} + }, + "paragraph": { + "font_family": "Inter, sans-serif", + "font_weight": "400", + "line_height": "150%", + "letter_spacing": "0", + "p1": {"color": "#000000", "size": "16"} + } + }, + "button": { + "font_family": "Inter, sans-serif", + "font_weight": "600", + "letter_spacing": "0", + "background_color": "#2cb191", + "text_color": "#ffffff", + "border_radius": "4" + }, + "footer": { + "show_preferences": false, + "company_name": { + "editor_content": { + "content": [{"type": "text", "text": "Acme", "marks": [{"type": "bold"}]}] + } + }, + "address": { + "editor_content": {"content": [{"text": "1 Main Street", "type": "text"}]} + }, + "info_text": { + "editor_content": {"content": [{"text": "You signed up on our website.", "type": "text"}]} + }, + "unsubscribe_text": "Unsubscribe", + "preferences_text": "Update your preferences", + "social_links": [ + {"url": "https://example.com", "type": "website", "label": "Website", "link_id": 7} + ] + } + }, + "blocks": [ + { + "id": "1", + "type": "paragraph", + "editor_content": { + "attrs": {"textAlign": "left"}, + "content": [{"text": "Hello", "type": "text"}] + } + }, + { + "id": "2", + "type": "bulleted_list", + "editor_content": {}, + "children": [{"id": "3", "type": "paragraph", "editor_content": {}}] + } + ] + }, + "etag": "42" +} diff --git a/spec/fixtures/email_block.json b/spec/fixtures/email_block.json new file mode 100644 index 0000000..df7d248 --- /dev/null +++ b/spec/fixtures/email_block.json @@ -0,0 +1,12 @@ +{ + "data": { + "id": "57", + "type": "paragraph", + "editor_content": { + "attrs": {"textAlign": "left"}, + "content": [{"text": "Hello", "type": "text"}] + }, + "placement": {"after": "56", "before": null} + }, + "etag": "43" +} diff --git a/spec/fixtures/email_block_created.json b/spec/fixtures/email_block_created.json new file mode 100644 index 0000000..7b52e03 --- /dev/null +++ b/spec/fixtures/email_block_created.json @@ -0,0 +1,12 @@ +{ + "data": { + "id": "58", + "type": "paragraph", + "editor_content": { + "attrs": {"textAlign": "center"}, + "content": [{"text": "Hi", "type": "text"}] + }, + "placement": {"after": "57", "before": null} + }, + "etag": "43" +} diff --git a/spec/fixtures/email_block_moved.json b/spec/fixtures/email_block_moved.json new file mode 100644 index 0000000..3041e81 --- /dev/null +++ b/spec/fixtures/email_block_moved.json @@ -0,0 +1,12 @@ +{ + "data": { + "id": "57", + "type": "paragraph", + "editor_content": { + "attrs": {"textAlign": "left"}, + "content": [{"text": "Hello", "type": "text"}] + }, + "placement": {"after": null, "before": "1"} + }, + "etag": "46" +} diff --git a/spec/fixtures/email_block_updated.json b/spec/fixtures/email_block_updated.json new file mode 100644 index 0000000..cb87a43 --- /dev/null +++ b/spec/fixtures/email_block_updated.json @@ -0,0 +1,9 @@ +{ + "data": { + "id": "57", + "type": "paragraph", + "editor_content": {"content": [{"text": "Hello again", "type": "text"}]}, + "placement": {"after": "56", "before": "58"} + }, + "etag": "44" +} diff --git a/spec/fixtures/email_block_validation_invalid.json b/spec/fixtures/email_block_validation_invalid.json new file mode 100644 index 0000000..c5c04fb --- /dev/null +++ b/spec/fixtures/email_block_validation_invalid.json @@ -0,0 +1,5 @@ +{ + "valid": false, + "errors": {"type": ["The selected type is invalid."]}, + "schema": {"version": "2.73.2", "hash": "0f3a9c"} +} diff --git a/spec/fixtures/email_block_validation_valid.json b/spec/fixtures/email_block_validation_valid.json new file mode 100644 index 0000000..b73c417 --- /dev/null +++ b/spec/fixtures/email_block_validation_valid.json @@ -0,0 +1 @@ +{"valid": true, "errors": {}, "schema": {"version": "2.73.2", "hash": "0f3a9c"}} diff --git a/spec/fixtures/email_etag.json b/spec/fixtures/email_etag.json new file mode 100644 index 0000000..730eaff --- /dev/null +++ b/spec/fixtures/email_etag.json @@ -0,0 +1 @@ +{"etag": "45"} diff --git a/spec/fixtures/email_html.json b/spec/fixtures/email_html.json new file mode 100644 index 0000000..d680c41 --- /dev/null +++ b/spec/fixtures/email_html.json @@ -0,0 +1 @@ +{"data": {"html": "

Hello

"}, "etag": "42"} diff --git a/spec/fixtures/email_settings.json b/spec/fixtures/email_settings.json new file mode 100644 index 0000000..b6193ec --- /dev/null +++ b/spec/fixtures/email_settings.json @@ -0,0 +1,111 @@ +{ + "data": { + "brand": { + "mode": "custom", + "font_family": "Inter, sans-serif", + "background_color": "#f4f4f4", + "text_color": "#000000", + "border_color": "#e5e7eb" + }, + "layout": { + "width_mode": "default", + "alignment": "center" + }, + "typography": { + "link": { + "color": "#2cb191" + }, + "heading": { + "font_family": "Inter, sans-serif", + "font_weight": "700", + "line_height": "150%", + "letter_spacing": "0", + "h1": { + "color": "#000000", + "size": "32" + }, + "h2": { + "color": "#000000", + "size": "24" + }, + "h3": { + "color": "#000000", + "size": "20" + } + }, + "paragraph": { + "font_family": "Inter, sans-serif", + "font_weight": "400", + "line_height": "150%", + "letter_spacing": "0", + "p1": { + "color": "#000000", + "size": "16" + } + } + }, + "button": { + "font_family": "Inter, sans-serif", + "font_weight": "600", + "letter_spacing": "0", + "background_color": "#2cb191", + "text_color": "#ffffff", + "border_radius": "4" + }, + "footer": { + "show_preferences": false, + "company_name": { + "editor_content": { + "content": [ + { + "type": "text", + "text": "Acme", + "marks": [ + { + "type": "bold" + } + ] + } + ] + } + }, + "address": { + "editor_content": { + "content": [ + { + "text": "1 Main Street", + "type": "text" + } + ] + } + }, + "info_text": { + "editor_content": { + "content": [ + { + "text": "You signed up on our website.", + "type": "text" + } + ] + } + }, + "unsubscribe_text": "Unsubscribe", + "preferences_text": "Update your preferences", + "social_links": [ + { + "url": "https://example.com", + "type": "website", + "label": "Website", + "link_id": 7 + } + ] + } + }, + "etag": "47", + "rejected": { + "message": "Some attributes were rejected.", + "keys": [ + "footer.social_links[0].url" + ] + } +} diff --git a/spec/fixtures/email_settings_validation.json b/spec/fixtures/email_settings_validation.json new file mode 100644 index 0000000..d1a571a --- /dev/null +++ b/spec/fixtures/email_settings_validation.json @@ -0,0 +1,9 @@ +{ + "valid": false, + "errors": {"layout.width": ["The layout.width field cannot be changed."]}, + "schema": {"version": "2.73.2", "hash": "0f3a9c"}, + "rejected": { + "message": "Some attributes were rejected.", + "keys": ["footer.social_links[0].url"] + } +} diff --git a/spec/fixtures/email_template.json b/spec/fixtures/email_template.json new file mode 100644 index 0000000..8f44cd4 --- /dev/null +++ b/spec/fixtures/email_template.json @@ -0,0 +1 @@ +{"data": {"id": "789", "name": "Newsletter", "type": "email", "created_at": "2026-10-28 12:00:00"}} diff --git a/spec/fixtures/email_version.json b/spec/fixtures/email_version.json new file mode 100644 index 0000000..8e0ef77 --- /dev/null +++ b/spec/fixtures/email_version.json @@ -0,0 +1 @@ +{"data": {"id": "903", "created_at": "2026-10-28 12:10:00", "current": true}} diff --git a/spec/fixtures/email_versions.json b/spec/fixtures/email_versions.json new file mode 100644 index 0000000..d1881d8 --- /dev/null +++ b/spec/fixtures/email_versions.json @@ -0,0 +1,26 @@ +{ + "data": [ + {"id": "902", "created_at": "2026-10-28 12:05:00", "current": true}, + {"id": "901", "created_at": "2026-10-28 12:00:00", "current": false} + ], + "links": { + "first": "https://connect.mailerlite.com/api/emails/123/versions?page=1", + "last": "https://connect.mailerlite.com/api/emails/123/versions?page=1", + "prev": null, + "next": null + }, + "meta": { + "current_page": 1, + "from": 1, + "last_page": 1, + "links": [ + {"url": null, "label": "« Previous", "page": null, "active": false}, + {"url": "https://connect.mailerlite.com/api/emails/123/versions?page=1", "label": "1", "page": 1, "active": true}, + {"url": null, "label": "Next »", "page": null, "active": false} + ], + "path": "https://connect.mailerlite.com/api/emails/123/versions", + "per_page": 25, + "to": 2, + "total": 2 + } +} diff --git a/spec/fixtures/files.json b/spec/fixtures/files.json new file mode 100644 index 0000000..4bf0846 --- /dev/null +++ b/spec/fixtures/files.json @@ -0,0 +1,44 @@ +{ + "data": [ + { + "id": "301", + "type": "image", + "name": "summer sale banner.png", + "url": "https://storage.example.com/files/summer-sale-banner.png", + "size": 48213, + "width": 1200, + "height": 600, + "created_at": "2026-10-20 09:30:00" + }, + { + "id": "302", + "type": "pdf", + "name": "summer sale terms.pdf", + "url": "https://storage.example.com/files/summer-sale-terms.pdf", + "size": 10240, + "width": null, + "height": null, + "created_at": "2026-10-21 10:00:00" + } + ], + "links": { + "first": "https://connect.mailerlite.com/api/files?page=1", + "last": "https://connect.mailerlite.com/api/files?page=1", + "prev": null, + "next": null + }, + "meta": { + "current_page": 1, + "from": 1, + "last_page": 1, + "links": [ + {"url": null, "label": "« Previous", "page": null, "active": false}, + {"url": "https://connect.mailerlite.com/api/files?page=1", "label": "1", "page": 1, "active": true}, + {"url": null, "label": "Next »", "page": null, "active": false} + ], + "path": "https://connect.mailerlite.com/api/files", + "per_page": 25, + "to": 2, + "total": 2 + } +} diff --git a/spec/support/json_fixture.rb b/spec/support/json_fixture.rb new file mode 100644 index 0000000..236f680 --- /dev/null +++ b/spec/support/json_fixture.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +require 'json' + +# Reads the JSON fixtures in `spec/fixtures` for the specs that use WebMock. +module JsonFixture + FIXTURE_DIR = File.expand_path('../fixtures', __dir__) + + # Returns the decoded content of `spec/fixtures/.json`. + # + # @param name [String] the file name without `.json` + # @return [Hash] a new Hash for each call, so a spec can change it + def load_fixture(name) + JSON.parse(File.read(File.join(FIXTURE_DIR, "#{name}.json"))) + end +end + +RSpec.configure { |config| config.include JsonFixture } if defined?(RSpec) From 7a328bd9d36647b66c4cd9252882e4d5909a965d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:43:17 +0100 Subject: [PATCH 02/30] feat: add shared checks for IDs, etags and idempotency keys Add the error classes for the client-side checks. Add the Params module. It checks path IDs, etags, Hash and String values, block placements, settings and idempotency keys. It also builds query parameters and drops nil values. Co-Authored-By: Claude Opus 5.5 --- lib/mailerlite.rb | 2 + lib/mailerlite/errors.rb | 19 ++++ lib/mailerlite/params.rb | 144 +++++++++++++++++++++++++++ spec/params_rspec.rb | 205 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 370 insertions(+) create mode 100644 lib/mailerlite/errors.rb create mode 100644 lib/mailerlite/params.rb create mode 100644 spec/params_rspec.rb diff --git a/lib/mailerlite.rb b/lib/mailerlite.rb index 634a075..44927ce 100644 --- a/lib/mailerlite.rb +++ b/lib/mailerlite.rb @@ -3,6 +3,8 @@ require_relative 'mailerlite/client' require_relative 'mailerlite/version' require_relative 'mailerlite/query_params' +require_relative 'mailerlite/errors' +require_relative 'mailerlite/params' require_relative 'mailerlite/subscribers/subscribers' require_relative 'mailerlite/campaigns/campaigns' require_relative 'mailerlite/forms/forms' diff --git a/lib/mailerlite/errors.rb b/lib/mailerlite/errors.rb new file mode 100644 index 0000000..c2069df --- /dev/null +++ b/lib/mailerlite/errors.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +module MailerLite + # The base class of the errors of the SDK. + class Error < StandardError; end + + # An ID for the URL path is empty. The SDK sends no request. + class EmptyIdError < ArgumentError; end + + # An ID for the URL path does not contain only the digits 0-9. The SDK sends no request. + class InvalidIdError < ArgumentError; end + + # The etag of a write is empty. The SDK sends no request. + class EmptyEtagError < ArgumentError; end + + # The idempotency key is empty, longer than 255 characters, contains a character that is not printable ASCII, + # or starts or ends with a space. The SDK sends no request. + class InvalidIdempotencyKeyError < ArgumentError; end +end diff --git a/lib/mailerlite/params.rb b/lib/mailerlite/params.rb new file mode 100644 index 0000000..d6e4501 --- /dev/null +++ b/lib/mailerlite/params.rb @@ -0,0 +1,144 @@ +# frozen_string_literal: true + +module MailerLite + # Checks and helpers for the request parameters of the resources. + # Each check raises before the request, so the SDK sends no request when a value is not valid. + module Params + module_function + + # Use \A and \z: `$` and \Z also match before a final new line. + # Use [0-9]: [[:digit:]] also matches digits that are not ASCII. + ID_PATTERN = /\A[0-9]+\z/ + # The API accepts 1 to 255 printable ASCII characters. + IDEMPOTENCY_KEY_PATTERN = /\A[\x20-\x7E]{1,255}\z/ + + # Returns the ID as a String for the URL path. + # + # @param value [String, Integer] the ID + # @param name [String] the name of the argument, for the error message + # @return [String] the ID + # @raise [TypeError] if the ID is not a String or an Integer + # @raise [MailerLite::EmptyIdError] if the ID is nil or empty + # @raise [MailerLite::InvalidIdError] if the ID does not contain only the digits 0-9 + def path_id(value, name) + raise EmptyIdError, "`#{name}` must not be empty." if value.nil? || value == '' + + raise TypeError, "`#{name}` type is not valid. Expected String or Integer, got #{value.class}." unless value.is_a?(String) || value.is_a?(Integer) + + id = value.to_s + # match? raises for a String with invalid bytes, so check the encoding first. + raise InvalidIdError, "`#{name}` must contain only the digits 0-9, got #{id.inspect}." unless id.valid_encoding? && id.ascii_only? && id.match?(ID_PATTERN) + + id + end + + # Returns the etag for the body of a write. + # + # @param value [String] the etag from the last response for the email + # @return [String] the etag + # @raise [MailerLite::EmptyEtagError] if the etag is nil or empty + # @raise [TypeError] if the etag is not a String + def etag(value) + raise EmptyEtagError, '`etag` must not be empty.' if value.nil? || value == '' + raise TypeError, "`etag` type is not valid. Expected String, got #{value.class}." unless value.is_a?(String) + + value + end + + # Returns the value if it is a Hash. + # + # @param value [Hash] the value to check + # @param name [String] the name of the argument, for the error message + # @return [Hash] the value + # @raise [TypeError] if the value is not a Hash + def require_hash(value, name) + raise TypeError, "`#{name}` type is not valid. Expected Hash, got #{value.class}." unless value.is_a?(Hash) + + value + end + + # Returns the String value if it is a String. + # + # @param value [String] the value to check + # @param name [String] the name of the argument, for the error message + # @return [String] the value + # @raise [TypeError] if the value is not a String + def require_string(value, name) + raise TypeError, "`#{name}` type is not valid. Expected String, got #{value.class}." unless value.is_a?(String) + + value + end + + # Returns a copy of the placement of a block with String keys and a valid `block_id`. + # + # @param placement [Hash] `position` and, for `before` and `after`, `block_id` + # @return [Hash] a new Hash. The Hash of the caller does not change. + # @raise [TypeError] if the placement is not a Hash, or `block_id` is not a String or an Integer + # @raise [ArgumentError] if a key is in the Hash as a Symbol and as a String + # @raise [MailerLite::EmptyIdError] if `block_id` is nil or empty + # @raise [MailerLite::InvalidIdError] if `block_id` does not contain only the digits 0-9 + def placement(placement) + require_hash(placement, 'placement') + result = {} + placement.each do |key, value| + name = key.to_s + # {block_id: 1, 'block_id' => 2} has two keys, but JSON can send only one of them. + raise ArgumentError, "`placement` contains the key `#{name}` two times." if result.key?(name) + + result[name] = value + end + result['block_id'] = path_id(result['block_id'], 'block_id') if result.key?('block_id') + result + end + + # Returns the settings of an email, if they do not contain an etag. + # + # @param settings [Hash] the settings to send + # @return [Hash] the settings + # @raise [TypeError] if the settings are not a Hash + # @raise [ArgumentError] if the settings contain an `etag` key + def settings(settings) + require_hash(settings, 'settings') + # The body has the settings and the etag at the same level. An etag key in the settings can hide the etag argument. + raise ArgumentError, '`settings` must not contain `etag`. Use the `etag` argument.' if settings.key?(:etag) || settings.key?('etag') + + settings + end + + # Returns the query parameters for a request. It drops nil values and keeps empty Strings. + # + # @param filter [Hash, nil] the filter values, sent as `filter[key]` + # @param params [Hash] the other query parameters + # @return [Hash] the query parameters + # @raise [TypeError] if the filter is not a Hash + def query(filter: nil, **params) + query = {} + unless filter.nil? + require_hash(filter, 'filter').each do |key, value| + query["filter[#{key}]"] = value unless value.nil? + end + end + params.each { |key, value| query[key.to_s] = value unless value.nil? } + query + end + + # Returns the headers for an idempotency key. + # + # @param key [String, nil] the idempotency key + # @return [Hash] the `Idempotency-Key` header, or an empty Hash if the key is nil + # @raise [TypeError] if the key is not a String + # @raise [MailerLite::InvalidIdempotencyKeyError] if the key is not valid + def idempotency_headers(key) + return {} if key.nil? + raise TypeError, "`idempotency_key` type is not valid. Expected String, got #{key.class}." unless key.is_a?(String) + + # HTTP removes a space at the start and at the end of a header value. Then the API gets a different key. + unless key.valid_encoding? && key.ascii_only? && key.match?(IDEMPOTENCY_KEY_PATTERN) && key == key.strip + raise InvalidIdempotencyKeyError, + '`idempotency_key` must be 1 to 255 printable ASCII characters, without a space at the start or the end.' + end + + { 'Idempotency-Key' => key } + end + end +end diff --git a/spec/params_rspec.rb b/spec/params_rspec.rb new file mode 100644 index 0000000..2905b9c --- /dev/null +++ b/spec/params_rspec.rb @@ -0,0 +1,205 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe MailerLite::Params do + describe 'error classes' do + it 'makes the client-side errors subclasses of ArgumentError' do + expect(MailerLite::EmptyIdError.ancestors).to include(ArgumentError) + expect(MailerLite::InvalidIdError.ancestors).to include(ArgumentError) + expect(MailerLite::EmptyEtagError.ancestors).to include(ArgumentError) + expect(MailerLite::InvalidIdempotencyKeyError.ancestors).to include(ArgumentError) + end + + it 'has a base error class for the SDK' do + expect(MailerLite::Error.ancestors).to include(StandardError) + end + end + + describe '.path_id' do + it 'returns a String of digits as it is' do + expect(described_class.path_id('123', 'email_id')).to eq '123' + end + + it 'returns an Integer as a String' do + expect(described_class.path_id(123, 'email_id')).to eq '123' + end + + it 'raises EmptyIdError for an empty String and for nil' do + expect { described_class.path_id('', 'email_id') }.to raise_error(MailerLite::EmptyIdError, /`email_id`/) + expect { described_class.path_id(nil, 'email_id') }.to raise_error(MailerLite::EmptyIdError, /`email_id`/) + end + + ['123/html', '123%2Fhtml', "123\n", ' 123', '²', '١٢', '1.5', '-5'].each do |value| + it "raises InvalidIdError for #{value.inspect}" do + expect { described_class.path_id(value, 'block_id') }.to raise_error(MailerLite::InvalidIdError, /`block_id`/) + end + end + + it 'raises InvalidIdError for a negative Integer' do + expect { described_class.path_id(-5, 'email_id') }.to raise_error(MailerLite::InvalidIdError) + end + + it 'raises InvalidIdError for a String with invalid bytes' do + value = (+"12\xFF").force_encoding('UTF-8') + expect { described_class.path_id(value, 'email_id') }.to raise_error(MailerLite::InvalidIdError) + end + + it 'raises InvalidIdError for a String in an encoding that is not ASCII compatible' do + expect { described_class.path_id('12'.encode('UTF-16LE'), 'email_id') }.to raise_error(MailerLite::InvalidIdError) + end + + [true, false, 1.5, :'123', ['1']].each do |value| + it "raises TypeError for #{value.inspect}" do + expect { described_class.path_id(value, 'email_id') }.to raise_error(TypeError, /`email_id`/) + end + end + end + + describe '.etag' do + it 'returns the etag' do + expect(described_class.etag('42')).to eq '42' + end + + it 'raises EmptyEtagError for an empty String and for nil' do + expect { described_class.etag('') }.to raise_error(MailerLite::EmptyEtagError) + expect { described_class.etag(nil) }.to raise_error(MailerLite::EmptyEtagError) + end + + it 'raises TypeError for a value that is not a String' do + expect { described_class.etag(42) }.to raise_error(TypeError, /`etag`/) + end + end + + describe '.require_hash' do + it 'returns the Hash' do + value = { 'a' => 1 } + expect(described_class.require_hash(value, 'settings')).to be value + end + + [nil, 'image', [], 1].each do |value| + it "raises TypeError for #{value.inspect}" do + expect { described_class.require_hash(value, 'filter') }.to raise_error(TypeError, /`filter`/) + end + end + end + + describe '.require_string' do + it 'returns the String' do + expect(described_class.require_string('paragraph', 'type')).to eq 'paragraph' + end + + [nil, 1, :paragraph].each do |value| + it "raises TypeError for #{value.inspect}" do + expect { described_class.require_string(value, 'type') }.to raise_error(TypeError, /`type`/) + end + end + end + + describe '.placement' do + it 'returns the placement with String keys' do + expect(described_class.placement({ position: 'end' })).to eq('position' => 'end') + end + + it 'sends an Integer block_id as a String' do + expect(described_class.placement({ position: 'after', block_id: 57 })) + .to eq('position' => 'after', 'block_id' => '57') + end + + it 'accepts a String key for block_id' do + expect(described_class.placement({ 'position' => 'before', 'block_id' => '57' })) + .to eq('position' => 'before', 'block_id' => '57') + end + + it 'does not change the Hash of the caller' do + placement = { position: 'after', block_id: 57 } + described_class.placement(placement) + expect(placement).to eq(position: 'after', block_id: 57) + end + + [:block_id, 'block_id'].each do |key| + it "checks the block_id with a #{key.class} key" do + expect { described_class.placement({ position: 'after', key => '' }) }.to raise_error(MailerLite::EmptyIdError) + expect { described_class.placement({ position: 'after', key => nil }) }.to raise_error(MailerLite::EmptyIdError) + expect { described_class.placement({ position: 'after', key => '1/2' }) }.to raise_error(MailerLite::InvalidIdError) + expect { described_class.placement({ position: 'after', key => "1\n" }) }.to raise_error(MailerLite::InvalidIdError) + expect { described_class.placement({ position: 'after', key => true }) }.to raise_error(TypeError) + end + end + + it 'raises ArgumentError when a key is there as a Symbol and as a String' do + expect { described_class.placement({ block_id: '1', 'block_id' => '2' }) }.to raise_error(ArgumentError, /block_id/) + expect { described_class.placement({ position: 'end', 'position' => 'start' }) }.to raise_error(ArgumentError, /position/) + end + + it 'raises TypeError for a placement that is not a Hash' do + expect { described_class.placement('end') }.to raise_error(TypeError, /`placement`/) + end + end + + describe '.settings' do + it 'returns the settings' do + settings = { brand: { mode: 'account' } } + expect(described_class.settings(settings)).to eq settings + end + + it 'raises ArgumentError for an etag key' do + expect { described_class.settings({ etag: '1' }) }.to raise_error(ArgumentError, /etag/) + expect { described_class.settings({ 'etag' => '1' }) }.to raise_error(ArgumentError, /etag/) + end + + it 'raises TypeError for settings that are not a Hash' do + expect { described_class.settings(nil) }.to raise_error(TypeError, /`settings`/) + end + end + + describe '.query' do + it 'returns an empty Hash with no values' do + expect(described_class.query).to eq({}) + end + + it 'adds a filter[key] value for each filter key' do + expect(described_class.query(filter: { name: 'summer sale', type: 'image' }, sort: '-size')) + .to eq('filter[name]' => 'summer sale', 'filter[type]' => 'image', 'sort' => '-size') + end + + it 'drops nil values, also in the filter' do + expect(described_class.query(filter: { name: nil, type: 'pdf' }, page: nil, limit: 10)) + .to eq('filter[type]' => 'pdf', 'limit' => 10) + end + + it 'keeps empty String values' do + expect(described_class.query(filter: { type: '' }, sort: '')) + .to eq('filter[type]' => '', 'sort' => '') + end + + it 'raises TypeError for a filter that is not a Hash' do + expect { described_class.query(filter: 'image') }.to raise_error(TypeError, /`filter`/) + end + end + + describe '.idempotency_headers' do + it 'returns no headers without a key' do + expect(described_class.idempotency_headers(nil)).to eq({}) + end + + it 'returns the header for a valid key' do + expect(described_class.idempotency_headers('key-1')).to eq('Idempotency-Key' => 'key-1') + end + + it 'accepts a key with 255 characters and a space in the middle' do + expect(described_class.idempotency_headers('a' * 255)).to eq('Idempotency-Key' => 'a' * 255) + expect(described_class.idempotency_headers('a b')).to eq('Idempotency-Key' => 'a b') + end + + ['', 'a' * 256, "a\nb", "a\tb", 'é', "\x7F", ' k', 'k ', (+"k\xFF").force_encoding('UTF-8')].each do |key| + it "raises InvalidIdempotencyKeyError for #{key.inspect[0, 20]}" do + expect { described_class.idempotency_headers(key) }.to raise_error(MailerLite::InvalidIdempotencyKeyError) + end + end + + it 'raises TypeError for a key that is not a String' do + expect { described_class.idempotency_headers(1) }.to raise_error(TypeError, /`idempotency_key`/) + end + end +end From 53d64b44b336563ce49f54db8860cb831681017a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:44:32 +0100 Subject: [PATCH 03/30] feat: expose the status, error fields and replay flag on responses Add the ApiResponse module. The new resources extend each response with it. idempotent_replay? reads the Idempotent-Replayed header without case. api_error returns nil for a 2xx status, and an ApiError for other statuses. ApiError has the status, the API code, the etag, the field errors and the API message. It keeps only plain values, so Marshal works. The SDK does not raise it. Co-Authored-By: Claude Opus 5.5 --- lib/mailerlite.rb | 1 + lib/mailerlite/api_response.rb | 24 ++++++ lib/mailerlite/errors.rb | 77 ++++++++++++++++++ spec/api_response_rspec.rb | 139 +++++++++++++++++++++++++++++++++ 4 files changed, 241 insertions(+) create mode 100644 lib/mailerlite/api_response.rb create mode 100644 spec/api_response_rspec.rb diff --git a/lib/mailerlite.rb b/lib/mailerlite.rb index 44927ce..902b59e 100644 --- a/lib/mailerlite.rb +++ b/lib/mailerlite.rb @@ -5,6 +5,7 @@ require_relative 'mailerlite/query_params' require_relative 'mailerlite/errors' require_relative 'mailerlite/params' +require_relative 'mailerlite/api_response' require_relative 'mailerlite/subscribers/subscribers' require_relative 'mailerlite/campaigns/campaigns' require_relative 'mailerlite/forms/forms' diff --git a/lib/mailerlite/api_response.rb b/lib/mailerlite/api_response.rb new file mode 100644 index 0000000..529f93e --- /dev/null +++ b/lib/mailerlite/api_response.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +module MailerLite + # Helpers that the new resources add to each `HTTP::Response` that they return. + # + # The response is still an `HTTP::Response`. Use `response.code` for the status code, + # `response.headers` for the headers and `response.parse` for the decoded body. + module ApiResponse + # Returns true if the API returned the stored response of an earlier request with the same idempotency key. + # + # @return [Boolean] true if the `Idempotent-Replayed` header is "true" + def idempotent_replay? + # A proxy can change the case of the value, or send the header two times. + headers.get('Idempotent-Replayed').any? { |value| value.strip.casecmp?('true') } + end + + # Returns the error of the response. + # + # @return [MailerLite::ApiError, nil] nil for a 2xx status, otherwise an error that you can raise + def api_error + status.success? ? nil : ApiError.from_response(self) + end + end +end diff --git a/lib/mailerlite/errors.rb b/lib/mailerlite/errors.rb index c2069df..9b49941 100644 --- a/lib/mailerlite/errors.rb +++ b/lib/mailerlite/errors.rb @@ -1,9 +1,86 @@ # frozen_string_literal: true +require 'json' + module MailerLite # The base class of the errors of the SDK. class Error < StandardError; end + # An error response (4xx or 5xx) from the API. + # + # The SDK does not raise it. Get it with `response.api_error` and raise it if you want to. + # It is not an `HTTP::Error`, so code that retries on network errors does not also retry an API error. + # It keeps only plain values, so `Marshal.dump` works. + # + # Note: `HTTP::Response#code` is the numeric status. `ApiError#code` is the String code of the API, + # for example `"version_conflict"`. The numeric status is in `ApiError#status`. + class ApiError < Error + # @return [Integer] the HTTP status code, for example 409 + attr_reader :status + # @return [String, nil] the error code of the API, for example "version_conflict" + attr_reader :code + # @return [String, nil] the current etag of the email, for a 409 version conflict + attr_reader :etag + # @return [Hash, nil] the error messages for each field, for some 422 responses + attr_reader :errors + # @return [String, nil] the message of the API + attr_reader :api_message + # @return [String] the response body as it is + attr_reader :body + # @return [Hash] the response headers + attr_reader :headers + + # Makes an error from a response. It works for the responses of all methods of the SDK. + # A body that is not a JSON object gives nil fields. + # + # @param response [HTTP::Response] the response + # @return [MailerLite::ApiError] the error + def self.from_response(response) + body = response.body.to_s + data = parse(body) + new(status: response.code, reason: response.reason, body: body, headers: response.headers.to_h, + code: data['code'], etag: data['etag'], errors: data['errors'], api_message: data['message']) + end + + # Returns the body as a Hash, or an empty Hash if the body is not a JSON object. + def self.parse(body) + data = JSON.parse(body) + data.is_a?(Hash) ? data : {} + rescue JSON::ParserError, EncodingError + {} + end + private_class_method :parse + + # @param status [Integer] the HTTP status code + # @param reason [String, nil] the reason phrase of the status + # @param code [String, nil] the error code of the API + # @param etag [String, nil] the current etag of the email + # @param errors [Hash, nil] the error messages for each field + # @param api_message [String, nil] the message of the API + # @param body [String] the response body + # @param headers [Hash] the response headers + def initialize(status:, reason: nil, code: nil, etag: nil, errors: nil, api_message: nil, body: '', headers: {}) + @status = status + @code = code + @etag = etag + @errors = errors + @api_message = api_message + @body = body + @headers = headers + super(build_message(reason)) + end + + private + + # For example "409 Conflict (version_conflict): The email was changed." + def build_message(reason) + text = [status, reason].compact.join(' ') + text += " (#{code})" if code + text += ": #{api_message}" if api_message + text + end + end + # An ID for the URL path is empty. The SDK sends no request. class EmptyIdError < ArgumentError; end diff --git a/spec/api_response_rspec.rb b/spec/api_response_rspec.rb new file mode 100644 index 0000000..389d51a --- /dev/null +++ b/spec/api_response_rspec.rb @@ -0,0 +1,139 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' +require 'json' +require_relative 'support/json_fixture' + +RSpec.describe MailerLite::ApiResponse do + let(:url) { "#{MAILERLITE_API_URL}/emails/123" } + + # Returns a real HTTP::Response from WebMock, extended with ApiResponse. + def response_for(status:, body: '', headers: {}) + stub_request(:get, url).to_return(status: status, body: body, headers: headers) + MailerLite::Client.new.http.get(url).extend(described_class) + end + + describe '#idempotent_replay?' do + it 'is true for the value true' do + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => 'true' }).idempotent_replay?).to be(true) + end + + it 'reads the value without case and without spaces' do + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => 'True' }).idempotent_replay?).to be(true) + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => ' TRUE ' }).idempotent_replay?).to be(true) + end + + it 'is false when the header is not there' do + expect(response_for(status: 201).idempotent_replay?).to be(false) + end + + it 'is false for other values' do + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => 'false' }).idempotent_replay?).to be(false) + end + + it 'reads a header that comes two times' do + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => %w[true true] }).idempotent_replay?).to be(true) + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => %w[false false] }).idempotent_replay?).to be(false) + end + end + + describe '#api_error' do + it 'is nil for a 2xx status' do + response = response_for(status: 200, body: load_fixture('email').to_json) + expect(response.api_error).to be_nil + expect(response).to be_a(HTTP::Response) + end + + it 'has the code and the etag of a 409 version conflict' do + body = { message: 'The email was changed.', code: 'version_conflict', etag: '45' }.to_json + error = response_for(status: 409, body: body).api_error + + expect(error).to be_a(MailerLite::ApiError) + expect(error.status).to eq 409 + expect(error.code).to eq 'version_conflict' + expect(error.etag).to eq '45' + expect(error.api_message).to eq 'The email was changed.' + expect(error.errors).to be_nil + expect(error.message).to start_with('409') + expect(error.message).to include('(version_conflict): The email was changed.') + end + + it 'has no code for a 409 without a code' do + error = response_for(status: 409, body: { message: 'The campaign is not a draft.' }.to_json).api_error + + expect(error.status).to eq 409 + expect(error.code).to be_nil + expect(error.etag).to be_nil + expect(error.message).to include(': The campaign is not a draft.') + end + + it 'has the errors of a 422' do + body = { message: 'The etag field is required.', errors: { etag: ['The etag field is required.'] } }.to_json + error = response_for(status: 422, body: body).api_error + + expect(error.status).to eq 422 + expect(error.errors).to eq('etag' => ['The etag field is required.']) + expect(error.api_message).to eq 'The etag field is required.' + end + + it 'has no errors for a 422 with only a message' do + error = response_for(status: 422, body: { message: 'This email was not built with the simple editor.' }.to_json).api_error + + expect(error.errors).to be_nil + expect(error.api_message).to eq 'This email was not built with the simple editor.' + end + + it 'does not raise for a 503 with an HTML body' do + html = 'Service Unavailable' + error = response_for(status: 503, body: html, headers: { 'Content-Type' => 'text/html' }).api_error + + expect(error.status).to eq 503 + expect(error.api_message).to be_nil + expect(error.code).to be_nil + expect(error.body).to eq html + expect(error.headers['Content-Type']).to eq 'text/html' + expect(error.message).to start_with('503') + end + + it 'accepts a JSON body that is not an object' do + error = response_for(status: 500, body: '[1, 2]').api_error + + expect(error.status).to eq 500 + expect(error.api_message).to be_nil + expect(error.body).to eq '[1, 2]' + end + + it 'survives a Marshal round trip' do + body = { message: 'The email was changed.', code: 'version_conflict', etag: '45' }.to_json + error = response_for(status: 409, body: body).api_error + copy = Marshal.load(Marshal.dump(error)) + + expect(copy).to be_a(MailerLite::ApiError) + expect(copy.message).to eq error.message + expect([copy.status, copy.code, copy.etag, copy.api_message, copy.body]).to eq [409, 'version_conflict', '45', 'The email was changed.', body] + end + end + + describe MailerLite::ApiError do + it 'is a MailerLite::Error and not an HTTP::Error' do + expect(described_class.ancestors).to include(MailerLite::Error) + expect(described_class.ancestors).not_to include(HTTP::Error) + end + + it 'builds an error from any HTTP::Response' do + stub_request(:get, url).to_return(status: 404, body: { message: 'Not found.' }.to_json) + error = described_class.from_response(MailerLite::Client.new.http.get(url)) + + expect(error.status).to eq 404 + expect(error.api_message).to eq 'Not found.' + end + + it 'can be raised' do + stub_request(:get, url).to_return(status: 404, body: { message: 'Not found.' }.to_json) + error = described_class.from_response(MailerLite::Client.new.http.get(url)) + + expect { raise error }.to raise_error(described_class, /Not found\./) + end + end +end From 3c4aa722410e6f2f59ed64733984aaa481d9b33e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:45:37 +0100 Subject: [PATCH 04/30] feat: add a request helper for the new resources Add Request.call. It sends a JSON body only when there is one, so a write without a body sends no body. It sends PATCH and DELETE bodies, adds the query, and adds the Idempotency-Key header when the caller gives a key. It reads the base URL when the request runs, and returns the response with the ApiResponse methods. Co-Authored-By: Claude Opus 5.5 --- lib/mailerlite.rb | 1 + lib/mailerlite/request.rb | 34 ++++++++++ spec/request_rspec.rb | 131 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 166 insertions(+) create mode 100644 lib/mailerlite/request.rb create mode 100644 spec/request_rspec.rb diff --git a/lib/mailerlite.rb b/lib/mailerlite.rb index 902b59e..329c26a 100644 --- a/lib/mailerlite.rb +++ b/lib/mailerlite.rb @@ -6,6 +6,7 @@ require_relative 'mailerlite/errors' require_relative 'mailerlite/params' require_relative 'mailerlite/api_response' +require_relative 'mailerlite/request' require_relative 'mailerlite/subscribers/subscribers' require_relative 'mailerlite/campaigns/campaigns' require_relative 'mailerlite/forms/forms' diff --git a/lib/mailerlite/request.rb b/lib/mailerlite/request.rb new file mode 100644 index 0000000..d8aa1a5 --- /dev/null +++ b/lib/mailerlite/request.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require 'uri' + +module MailerLite + # Sends the requests of the new resources. + module Request + module_function + + # Sends a request and returns the response with the `MailerLite::ApiResponse` methods. + # It does not raise for a 4xx or 5xx status. + # + # @param client [MailerLite::Client] the client + # @param method [Symbol] the HTTP method, for example :patch + # @param path [String] the path after the base URL, for example "/emails/123" + # @param json [Hash, nil] the request body. If it is nil, the SDK sends no body. + # @param query [Hash, nil] the query parameters + # @param idempotency_key [String, nil] the value of the `Idempotency-Key` header + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + def call(client, method, path, json: nil, query: nil, idempotency_key: nil) + headers = Params.idempotency_headers(idempotency_key) + # Read the constant here, not when the file loads. + uri = URI("#{MAILERLITE_API_URL}#{path}") + uri.query = URI.encode_www_form(query) if query && !query.empty? + options = {} + # `body: nil.to_json` sends "null", so add `json:` only when there is a body. + options[:json] = json unless json.nil? + http = client.http + http = http.headers(headers) unless headers.empty? + http.request(method, uri, options).extend(ApiResponse) + end + end +end diff --git a/spec/request_rspec.rb b/spec/request_rspec.rb new file mode 100644 index 0000000..c8070a7 --- /dev/null +++ b/spec/request_rspec.rb @@ -0,0 +1,131 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' +require 'json' + +RSpec.describe MailerLite::Request do + let(:client) { MailerLite::Client.new } + let(:api) { MAILERLITE_API_URL } + + # WebMock normalizes the URI (for example `+` becomes `%20`), so keep the raw URI that http.rb sends. + def capture_raw_uris + uris = [] + allow_any_instance_of(HTTP::Client).to receive(:perform).and_wrap_original do |method, request, options| + uris << request.uri.to_s + method.call(request, options) + end + uris + end + + it 'sends a PATCH request with the JSON body' do + stub = stub_request(:patch, "#{api}/emails/1/settings") + .with { |req| req.body == '{"layout":{"alignment":"left"},"etag":"42"}' } + .to_return(status: 200, body: '{}') + + described_class.call(client, :patch, '/emails/1/settings', json: { 'layout' => { 'alignment' => 'left' }, 'etag' => '42' }) + + expect(stub).to have_been_requested + end + + it 'sends a DELETE request with the JSON body' do + stub = stub_request(:delete, "#{api}/emails/1/blocks/2") + .with { |req| req.body == '{"etag":"42"}' } + .to_return(status: 200, body: '{"etag":"43"}') + + described_class.call(client, :delete, '/emails/1/blocks/2', json: { 'etag' => '42' }) + + expect(stub).to have_been_requested + end + + it 'sends no body, not null, when there is no body' do + stub = stub_request(:post, "#{api}/emails/1/versions") + .with { |req| req.body == '' } + .to_return(status: 201, body: '{}') + + described_class.call(client, :post, '/emails/1/versions') + + expect(stub).to have_been_requested + end + + it 'sends the query and encodes a space as +' do + uris = capture_raw_uris + stub = stub_request(:get, "#{api}/files") + .with(query: { 'filter[name]' => 'summer sale', 'filter[type]' => '', 'page' => '2' }) + .to_return(status: 200, body: '{}') + + described_class.call(client, :get, '/files', query: { 'filter[name]' => 'summer sale', 'filter[type]' => '', 'page' => 2 }) + + expect(stub).to have_been_requested + expect(uris).to eq ["#{api}/files?filter%5Bname%5D=summer+sale&filter%5Btype%5D=&page=2"] + end + + it 'sends no query for an empty query' do + uris = capture_raw_uris + stub_request(:get, "#{api}/emails/1/versions").to_return(status: 200, body: '{}') + + described_class.call(client, :get, '/emails/1/versions', query: {}) + + expect(uris).to eq ["#{api}/emails/1/versions"] + end + + it 'sends the Authorization header and no Idempotency-Key header without a key' do + stub = stub_request(:post, "#{api}/emails/1/versions") + .with(headers: { 'Authorization' => 'Bearer dummy_token' }) + .with { |req| !req.headers.key?('Idempotency-Key') } + .to_return(status: 201, body: '{}') + + described_class.call(client, :post, '/emails/1/versions') + + expect(stub).to have_been_requested + end + + it 'sends the Idempotency-Key header with a key' do + stub = stub_request(:post, "#{api}/emails/1/versions") + .with(headers: { 'Idempotency-Key' => 'key-1' }) + .to_return(status: 201, body: '{}') + + described_class.call(client, :post, '/emails/1/versions', idempotency_key: 'key-1') + + expect(stub).to have_been_requested + end + + it 'sends no request for an invalid key' do + expect { described_class.call(client, :post, '/emails/1/versions', idempotency_key: 'a b ') } + .to raise_error(MailerLite::InvalidIdempotencyKeyError) + expect(a_request(:any, /.*/)).not_to have_been_made + end + + it 'returns the HTTP::Response with the ApiResponse methods' do + stub_request(:get, "#{api}/emails/1").to_return(status: 409, body: '{"message":"Conflict.","code":"version_conflict","etag":"9"}') + + response = described_class.call(client, :get, '/emails/1') + + expect(response).to be_a(HTTP::Response) + expect(response.code).to eq 409 + expect(response.api_error.etag).to eq '9' + expect(response.idempotent_replay?).to be(false) + end + + it 'reads the base URL when the request runs' do + original = MAILERLITE_API_URL + Object.send(:remove_const, :MAILERLITE_API_URL) + Object.const_set(:MAILERLITE_API_URL, 'http://api.example.com/api') + stub = stub_request(:get, 'http://api.example.com/api/emails/1').to_return(status: 200, body: '{}') + + described_class.call(client, :get, '/emails/1') + + expect(stub).to have_been_requested + ensure + Object.send(:remove_const, :MAILERLITE_API_URL) + Object.const_set(:MAILERLITE_API_URL, original) + end + + it 'does not change the Hashes of the caller' do + body = { 'etag' => '42' }.freeze + query = { 'page' => 1 }.freeze + stub_request(:delete, "#{api}/emails/1/blocks/2?page=1").to_return(status: 200, body: '{}') + + expect { described_class.call(client, :delete, '/emails/1/blocks/2', json: body, query: query) }.not_to raise_error + end +end From 7fa5890104fb5d8877b2a188f4b214554f2a90e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:47:20 +0100 Subject: [PATCH 05/30] feat: add Emails#get Add the Emails class for the emails built with the simple editor, and the constants for the version conflict code, the block types, the block positions and the brand modes. Add Emails#get and its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 34 +++++++++++ lib/mailerlite.rb | 1 + lib/mailerlite/emails/emails.rb | 76 ++++++++++++++++++++++++ spec/emails_rspec.rb | 102 ++++++++++++++++++++++++++++++++ 4 files changed, 213 insertions(+) create mode 100644 lib/mailerlite/emails/emails.rb create mode 100644 spec/emails_rspec.rb diff --git a/README.md b/README.md index d912e77..7eaeb15 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,8 @@ For more information how to obtain an API key visit the [following link](https:/ - [Cancel a campaign](#cancel-a-campaign) - [Delete a campaign](#delete-a-campaign) - [Get subscribers activity for a campaign](#get-subscribers-activity-for-a-campaign) + - [Emails](#emails) + - [Get an email](#get-an-email) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -576,6 +578,38 @@ campaign_id = 123456 campaigns.activity(campaign_id) ``` +## Emails + + + +These methods edit emails built with the simple editor. To create such an email, create a campaign with `editor: 'simple'` in the email. The ID of the email is in `data.emails[0].id` of the response. + +- IDs are strings of digits. You can also give them as integers. An empty ID raises `MailerLite::EmptyIdError`, and an ID that does not contain only digits raises `MailerLite::InvalidIdError`. The SDK sends no request in these cases. +- The methods return an `HTTP::Response`, like the other methods. Use `response.code` for the status code, `response.headers` for the headers and `JSON.parse(response.body)` for the body. +- The methods do not raise an error for a `4xx` or `5xx` status. `response.api_error` is `nil` for a `2xx` status. For other statuses, it is a `MailerLite::ApiError` with `status`, `code`, `etag`, `api_message` and `errors`. You can raise it. +- Each write needs the etag from the last response for the email, and returns a new etag. The etag covers the whole email, so send the writes to one email one after another. An empty etag raises `MailerLite::EmptyEtagError`, and the SDK sends no request. +- If the email changed after you read it, the write returns `409`, and `response.api_error.code` is `MailerLite::Emails::VERSION_CONFLICT`. Then `response.api_error.etag` is the current etag. Get the email again, and then send the write again with the current etag. +- The keys of `editor_content` are camelCase, for example `textAlign`. The SDK sends them as you give them. + +### Get an email + + + +Returns the email with its settings and blocks, and the etag of the email. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.get('123456') + +body = JSON.parse(response.body) +email = body['data'] +etag = body['etag'] +``` + ## Forms diff --git a/lib/mailerlite.rb b/lib/mailerlite.rb index 329c26a..6b54825 100644 --- a/lib/mailerlite.rb +++ b/lib/mailerlite.rb @@ -23,3 +23,4 @@ require_relative 'mailerlite/batch/batch' require_relative 'mailerlite/timezones/timezones' require_relative 'mailerlite/ecommerce/ecommerce' +require_relative 'mailerlite/emails/emails' diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb new file mode 100644 index 0000000..1beccfa --- /dev/null +++ b/lib/mailerlite/emails/emails.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +module MailerLite + # This is a class for the emails built with the simple editor. + # + # To create such an email, create a campaign with `editor: 'simple'` in the email. + # The ID of the email is in `data.emails[0].id` of the response. + # + # IDs are Strings of the digits 0-9. You can also give them as Integers. An empty ID raises + # `MailerLite::EmptyIdError`, and an ID with other characters raises `MailerLite::InvalidIdError`. + # + # Each method returns the `HTTP::Response` with the `MailerLite::ApiResponse` methods. The methods do not raise + # for a 4xx or 5xx status: use `response.api_error`. A check of an argument raises before the request, and then + # the SDK sends no request. + # + # Each write needs the etag from the last response for the email, and returns a new etag. The etag covers the + # whole email, so send the writes to one email one after another. If the email changed after you read it, the + # API returns 409 and `response.api_error.code` is `VERSION_CONFLICT`. Then `response.api_error.etag` is the + # current etag. + class Emails + # The error code of a write with an etag that is not the current etag of the email. + VERSION_CONFLICT = 'version_conflict' + + # Block types. The API can also return types that are not in this list. + module BlockType + BLOCKQUOTE = 'blockquote' + BULLETED_LIST = 'bulleted_list' + BUTTON = 'button' + CODE = 'code' + DIVIDER = 'divider' + HEADING = 'heading' + IMAGE = 'image' + NUMBERED_LIST = 'numbered_list' + PARAGRAPH = 'paragraph' + SOCIAL_ICON = 'social_icon' + # Only reads return this type. You cannot insert a block of this type. + TITLE = 'title' + VIDEO = 'video' + end + + # Positions of a block, for `placement`. `BEFORE` and `AFTER` also need a `block_id`. + # The names are not `START` and `END`, because `END` is a keyword in Ruby. + module BlockPosition + AT_START = 'start' + AT_END = 'end' + BEFORE = 'before' + AFTER = 'after' + end + + # Where the palette of an email comes from, in `settings[:brand][:mode]`. + module BrandMode + ACCOUNT = 'account' + TEMPLATE = 'template' + CUSTOM = 'custom' + end + + attr_reader :client + + # Inits the `Emails` class with the specified `client`. + # + # @param client [MailerLite::Client] the `Client` instance to use + def initialize(client: MailerLite::Client.new) + @client = client + end + + # Returns the email with its settings and blocks, and the etag of the email. + # + # @param email_id [String, Integer] the ID of the email + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + def get(email_id) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :get, "/emails/#{email_id}") + end + end +end diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb new file mode 100644 index 0000000..57d62e2 --- /dev/null +++ b/spec/emails_rspec.rb @@ -0,0 +1,102 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' +require 'json' +require_relative 'support/json_fixture' + +RSpec.describe MailerLite::Emails do + let(:client) { MailerLite::Client.new } + let(:emails) { described_class.new(client: client) } + + # Stubs one request. The stub matches only the exact raw body, the Authorization header, + # and the Idempotency-Key header (or no such header when `key` is nil). + def stub_api(method, path, body: '', response: {}, status: 200, query: nil, key: nil) + pattern = { headers: { 'Authorization' => 'Bearer dummy_token' } } + pattern[:query] = query if query + stub_request(method, "#{MAILERLITE_API_URL}#{path}") + .with(**pattern) { |req| req.body == body && req.headers['Idempotency-Key'] == key } + .to_return(status: status, body: response.to_json, headers: { 'Content-Type' => 'application/json' }) + end + + def decoded(response) + JSON.parse(response.body.to_s) + end + + # Each value raises the error before the request. + def invalid_ids + [ + ['', MailerLite::EmptyIdError], [nil, MailerLite::EmptyIdError], + ['123/html', MailerLite::InvalidIdError], ['123%2Fhtml', MailerLite::InvalidIdError], + ["123\n", MailerLite::InvalidIdError], ['²', MailerLite::InvalidIdError], ['١٢', MailerLite::InvalidIdError], + [-5, MailerLite::InvalidIdError], [(+"12\xFF").force_encoding('UTF-8'), MailerLite::InvalidIdError], + [true, TypeError], [1.5, TypeError] + ] + end + + def expect_invalid_ids(name) + invalid_ids.each do |value, error| + expect { yield value }.to raise_error(error, /`#{name}`/) + end + expect(a_request(:any, /.*/)).not_to have_been_made + end + + describe 'constants' do + it 'has the values of the API' do + expect(described_class::VERSION_CONFLICT).to eq 'version_conflict' + block_types = described_class::BlockType + expect([block_types::BLOCKQUOTE, block_types::BULLETED_LIST, block_types::BUTTON, block_types::CODE, + block_types::DIVIDER, block_types::HEADING, block_types::IMAGE, block_types::NUMBERED_LIST, + block_types::PARAGRAPH, block_types::SOCIAL_ICON, block_types::TITLE, block_types::VIDEO]) + .to eq %w[blockquote bulleted_list button code divider heading image numbered_list paragraph social_icon title video] + positions = described_class::BlockPosition + expect([positions::AT_START, positions::AT_END, positions::BEFORE, positions::AFTER]).to eq %w[start end before after] + modes = described_class::BrandMode + expect([modes::ACCOUNT, modes::TEMPLATE, modes::CUSTOM]).to eq %w[account template custom] + end + end + + describe '#get' do + it 'gets the email' do + stub = stub_api(:get, '/emails/123', response: load_fixture('email')) + + response = emails.get('123') + + expect(stub).to have_been_requested + expect(response).to be_a(HTTP::Response) + expect(response.code).to eq 200 + data = decoded(response) + expect(data['etag']).to eq '42' + expect(data['data']['id']).to eq '123' + expect(data['data']['type']).to eq 'builder_inline_email' + expect(data['data']['emailable_type']).to eq 'campaigns' + expect(data['data']['settings']['brand']['mode']).to eq 'account' + expect(data['data']['settings']['footer']['show_preferences']).to be(false) + expect(data['data']['settings']['footer']['social_links'][0]['link_id']).to eq 7 + expect(data['data']['blocks'][0]['editor_content']['attrs']['textAlign']).to eq 'left' + expect(data['data']['blocks'][1]['children'][0]['id']).to eq '3' + end + + it 'accepts an Integer ID' do + stub = stub_api(:get, '/emails/123', response: load_fixture('email')) + + emails.get(123) + + expect(stub).to have_been_requested + end + + it 'returns the error response and does not raise' do + stub_api(:get, '/emails/123', status: 404, response: { message: 'Resource not found.' }) + + response = emails.get('123') + + expect(response).to be_a(HTTP::Response) + expect(response.code).to eq 404 + expect(response.api_error.api_message).to eq 'Resource not found.' + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.get(id) } + end + end +end From b04303835c2ef2929c3397daec62435356c625b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:48:10 +0100 Subject: [PATCH 06/30] feat: add Emails#get_html Add Emails#get_html. It returns the HTML of an email and its etag. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++++++++++++++++++ lib/mailerlite/emails/emails.rb | 11 +++++++++++ spec/emails_rspec.rb | 28 ++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/README.md b/README.md index 7eaeb15..0b8a018 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Get subscribers activity for a campaign](#get-subscribers-activity-for-a-campaign) - [Emails](#emails) - [Get an email](#get-an-email) + - [Get the HTML of an email](#get-the-html-of-an-email) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -610,6 +611,23 @@ email = body['data'] etag = body['etag'] ``` +### Get the HTML of an email + + + +Returns the HTML that the email sends. The API can return a temporary `503` error. If it does, try again later. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.get_html('123456') + +html = JSON.parse(response.body)['data']['html'] if response.code == 200 +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index 1beccfa..3af4956 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -72,5 +72,16 @@ def get(email_id) email_id = Params.path_id(email_id, 'email_id') Request.call(client, :get, "/emails/#{email_id}") end + + # Returns the HTML that the email sends, and the etag of the email. + # The API can return a temporary 503 error. Then try again later. + # + # @param email_id [String, Integer] the ID of the email + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + def get_html(email_id) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :get, "/emails/#{email_id}/html") + end end end diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 57d62e2..44b4042 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -99,4 +99,32 @@ def expect_invalid_ids(name) expect_invalid_ids('email_id') { |id| emails.get(id) } end end + + describe '#get_html' do + it 'gets the HTML of the email' do + stub = stub_api(:get, '/emails/123/html', response: load_fixture('email_html')) + + response = emails.get_html('123') + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['data']['html']).to eq '

Hello

' + expect(data['etag']).to eq '42' + end + + it 'returns a 503 with an HTML body and does not raise' do + stub_request(:get, "#{MAILERLITE_API_URL}/emails/123/html") + .to_return(status: 503, body: 'Service Unavailable', headers: { 'Content-Type' => 'text/html' }) + + response = emails.get_html('123') + + expect(response.code).to eq 503 + expect(response.api_error.status).to eq 503 + expect(response.api_error.api_message).to be_nil + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.get_html(id) } + end + end end From 605fc620f52d153092bfce9a47fbf11b1b37df74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:48:28 +0100 Subject: [PATCH 07/30] feat: add Emails#get_block Add Emails#get_block. It returns a block of an email, its placement and the etag of the email. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++++++++++++++++++ lib/mailerlite/emails/emails.rb | 13 +++++++++++++ spec/emails_rspec.rb | 23 +++++++++++++++++++++++ 3 files changed, 54 insertions(+) diff --git a/README.md b/README.md index 0b8a018..d5bde21 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Emails](#emails) - [Get an email](#get-an-email) - [Get the HTML of an email](#get-the-html-of-an-email) + - [Get a block](#get-a-block) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -628,6 +629,23 @@ response = emails.get_html('123456') html = JSON.parse(response.body)['data']['html'] if response.code == 200 ``` +### Get a block + + + +Returns the block and its place in the email: `placement` has the IDs of the blocks `after` and `before` it, or `nil`. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.get_block(email_id: '123456', block_id: '57') + +block = JSON.parse(response.body)['data'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index 3af4956..a066282 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -83,5 +83,18 @@ def get_html(email_id) email_id = Params.path_id(email_id, 'email_id') Request.call(client, :get, "/emails/#{email_id}/html") end + + # Returns the block and its place in the email, and the etag of the email. + # `placement` has the IDs of the blocks `after` and `before` it, or nil. + # + # @param email_id [String, Integer] the ID of the email + # @param block_id [String, Integer] the ID of the block + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid + def get_block(email_id:, block_id:) + email_id = Params.path_id(email_id, 'email_id') + block_id = Params.path_id(block_id, 'block_id') + Request.call(client, :get, "/emails/#{email_id}/blocks/#{block_id}") + end end end diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 44b4042..51b5b89 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -127,4 +127,27 @@ def expect_invalid_ids(name) expect_invalid_ids('email_id') { |id| emails.get_html(id) } end end + + describe '#get_block' do + it 'gets the block and its placement' do + stub = stub_api(:get, '/emails/123/blocks/57', response: load_fixture('email_block')) + + response = emails.get_block(email_id: '123', block_id: 57) + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['etag']).to eq '43' + expect(data['data']['id']).to eq '57' + expect(data['data']['type']).to eq 'paragraph' + expect(data['data']['editor_content']['attrs']['textAlign']).to eq 'left' + expect(data['data']['placement']['after']).to eq '56' + expect(data['data']['placement']).to have_key('before') + expect(data['data']['placement']['before']).to be_nil + end + + it 'checks the IDs and sends no request' do + expect_invalid_ids('email_id') { |id| emails.get_block(email_id: id, block_id: '57') } + expect_invalid_ids('block_id') { |id| emails.get_block(email_id: '123', block_id: id) } + end + end end From 0699ba6ae2702c0cec19d97e2544f44846726ded Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:49:09 +0100 Subject: [PATCH 08/30] feat: add Emails#create_block Add Emails#create_block. It inserts a block in an email. It checks the email ID, the etag, the block type, the content and the block_id of the placement before the request. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 29 +++++++++++++ lib/mailerlite/emails/emails.rb | 30 +++++++++++++ spec/emails_rspec.rb | 74 +++++++++++++++++++++++++++++++++ 3 files changed, 133 insertions(+) diff --git a/README.md b/README.md index d5bde21..73e450c 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Get an email](#get-an-email) - [Get the HTML of an email](#get-the-html-of-an-email) - [Get a block](#get-a-block) + - [Insert a block](#insert-a-block) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -646,6 +647,34 @@ response = emails.get_block(email_id: '123456', block_id: '57') block = JSON.parse(response.body)['data'] ``` +### Insert a block + + + +Use the block types in `MailerLite::Emails::BlockType`. `editor_content` can be empty. Without `placement`, the API puts the block at the end of the email. The positions are in `MailerLite::Emails::BlockPosition`. The `BEFORE` and `AFTER` positions also need a `block_id`. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +email_id = '123456' +etag = JSON.parse(emails.get(email_id).body)['etag'] + +response = emails.create_block( + email_id: email_id, + etag: etag, + type: MailerLite::Emails::BlockType::PARAGRAPH, + editor_content: { attrs: { textAlign: 'left' }, content: [{ type: 'text', text: 'Hello' }] }, + placement: { position: MailerLite::Emails::BlockPosition::AT_START } +) + +body = JSON.parse(response.body) +block_id = body['data']['id'] +etag = body['etag'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index a066282..1d790b8 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -96,5 +96,35 @@ def get_block(email_id:, block_id:) block_id = Params.path_id(block_id, 'block_id') Request.call(client, :get, "/emails/#{email_id}/blocks/#{block_id}") end + + # Inserts a block in the email. Returns the new block and the new etag of the email. + # + # @param email_id [String, Integer] the ID of the email + # @param etag [String] the etag from the last response for the email + # @param type [String] the block type, see `BlockType`. You cannot insert `title`. + # @param editor_content [Hash] the content of the block. It can be empty. Its keys are camelCase, for example `textAlign`. + # @param placement [Hash, nil] `position` (see `BlockPosition`) and, for `before` and `after`, `block_id`. + # Without it, the API puts the block at the end of the email. + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid + # @raise [MailerLite::EmptyEtagError] if the etag is empty + # @raise [TypeError] if an argument has a type that is not valid + def create_block(email_id:, etag:, type:, editor_content:, placement: nil) + email_id = Params.path_id(email_id, 'email_id') + body = block_body(type, editor_content, placement).merge('etag' => Params.etag(etag)) + Request.call(client, :post, "/emails/#{email_id}/blocks", json: body) + end + + private + + # Returns the body to insert or to validate a block. + def block_body(type, editor_content, placement) + body = { + 'type' => Params.require_string(type, 'type'), + 'editor_content' => Params.require_hash(editor_content, 'editor_content') + } + body['placement'] = Params.placement(placement) unless placement.nil? + body + end end end diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 51b5b89..b1c43b7 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -150,4 +150,78 @@ def expect_invalid_ids(name) expect_invalid_ids('block_id') { |id| emails.get_block(email_id: '123', block_id: id) } end end + + describe '#create_block' do + let(:content) { { attrs: { textAlign: 'center' }, content: [{ type: 'text', text: 'Hi' }] } } + + it 'inserts the block with the placement and the etag' do + body = '{"type":"paragraph","editor_content":{"attrs":{"textAlign":"center"},"content":[{"type":"text","text":"Hi"}]},' \ + '"placement":{"position":"after","block_id":"57"},"etag":"42"}' + stub = stub_api(:post, '/emails/123/blocks', body: body, status: 201, response: load_fixture('email_block_created')) + placement = { position: described_class::BlockPosition::AFTER, block_id: 57 } + + response = emails.create_block(email_id: '123', etag: '42', type: described_class::BlockType::PARAGRAPH, + editor_content: content, placement: placement) + + expect(stub).to have_been_requested + expect(response.code).to eq 201 + data = decoded(response) + expect(data['etag']).to eq '43' + expect(data['data']['id']).to eq '58' + expect(data['data']['editor_content']['attrs']['textAlign']).to eq 'center' + expect(data['data']['placement']['after']).to eq '57' + expect(placement).to eq(position: 'after', block_id: 57) + end + + it 'sends no placement without a placement, and accepts empty content' do + stub = stub_api(:post, '/emails/123/blocks', body: '{"type":"divider","editor_content":{},"etag":"42"}', + status: 201, response: load_fixture('email_block_created')) + + emails.create_block(email_id: 123, etag: '42', type: 'divider', editor_content: {}) + + expect(stub).to have_been_requested + end + + it 'returns a version conflict with the code and the current etag' do + stub_api(:post, '/emails/123/blocks', body: '{"type":"divider","editor_content":{},"etag":"41"}', status: 409, + response: { message: 'The email was changed.', code: 'version_conflict', etag: '42' }) + + response = emails.create_block(email_id: '123', etag: '41', type: 'divider', editor_content: {}) + + expect(response.code).to eq 409 + expect(response.api_error.status).to eq 409 + expect(response.api_error.code).to eq described_class::VERSION_CONFLICT + expect(response.api_error.etag).to eq '42' + end + + it 'returns the field errors of a 422' do + stub_api(:post, '/emails/123/blocks', body: '{"type":"title","editor_content":{},"etag":"42"}', status: 422, + response: { message: 'The selected type is invalid.', errors: { type: ['The selected type is invalid.'] } }) + + response = emails.create_block(email_id: '123', etag: '42', type: 'title', editor_content: {}) + + expect(response.api_error.errors).to eq('type' => ['The selected type is invalid.']) + end + + it 'checks the email ID and the block_id of the placement, and sends no request' do + expect_invalid_ids('email_id') { |id| emails.create_block(email_id: id, etag: '42', type: 'divider', editor_content: {}) } + expect_invalid_ids('block_id') do |id| + emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, placement: { position: 'after', block_id: id }) + end + expect_invalid_ids('block_id') do |id| + emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, placement: { 'position' => 'after', 'block_id' => id }) + end + end + + it 'checks the etag and the types, and sends no request' do + expect { emails.create_block(email_id: '123', etag: '', type: 'divider', editor_content: {}) }.to raise_error(MailerLite::EmptyEtagError) + expect { emails.create_block(email_id: '123', etag: nil, type: 'divider', editor_content: {}) }.to raise_error(MailerLite::EmptyEtagError) + expect { emails.create_block(email_id: '123', etag: 42, type: 'divider', editor_content: {}) }.to raise_error(TypeError, /`etag`/) + expect { emails.create_block(email_id: '123', etag: '42', type: 1, editor_content: {}) }.to raise_error(TypeError, /`type`/) + expect { emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: nil) }.to raise_error(TypeError, /`editor_content`/) + expect { emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, placement: 'end') } + .to raise_error(TypeError, /`placement`/) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end end From 3bf7c97ac8fb16ff42e15e9b685634e8c40a2344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:49:30 +0100 Subject: [PATCH 09/30] feat: add Emails#update_block Add Emails#update_block. It sends a PATCH request that replaces the content of a block. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 23 +++++++++++++++++++++++ lib/mailerlite/emails/emails.rb | 18 ++++++++++++++++++ spec/emails_rspec.rb | 25 +++++++++++++++++++++++++ 3 files changed, 66 insertions(+) diff --git a/README.md b/README.md index 73e450c..91dbf56 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Get the HTML of an email](#get-the-html-of-an-email) - [Get a block](#get-a-block) - [Insert a block](#insert-a-block) + - [Update a block](#update-a-block) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -675,6 +676,28 @@ block_id = body['data']['id'] etag = body['etag'] ``` +### Update a block + + + +The new `editor_content` replaces the whole content of the block. The API removes the keys that you do not send. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.update_block( + email_id: '123456', + block_id: '57', + etag: 'etag-from-the-last-response', + editor_content: { attrs: { textAlign: 'center' }, content: [{ type: 'text', text: 'Hello again' }] } +) + +etag = JSON.parse(response.body)['etag'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index 1d790b8..c8e367c 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -115,6 +115,24 @@ def create_block(email_id:, etag:, type:, editor_content:, placement: nil) Request.call(client, :post, "/emails/#{email_id}/blocks", json: body) end + # Updates a block of the email. The new content replaces the whole content of the block: the API removes the + # keys that you do not send. Returns the block and the new etag of the email. + # + # @param email_id [String, Integer] the ID of the email + # @param block_id [String, Integer] the ID of the block + # @param etag [String] the etag from the last response for the email + # @param editor_content [Hash] the new content of the block. Its keys are camelCase, for example `textAlign`. + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid + # @raise [MailerLite::EmptyEtagError] if the etag is empty + # @raise [TypeError] if an argument has a type that is not valid + def update_block(email_id:, block_id:, etag:, editor_content:) + email_id = Params.path_id(email_id, 'email_id') + block_id = Params.path_id(block_id, 'block_id') + body = { 'editor_content' => Params.require_hash(editor_content, 'editor_content'), 'etag' => Params.etag(etag) } + Request.call(client, :patch, "/emails/#{email_id}/blocks/#{block_id}", json: body) + end + private # Returns the body to insert or to validate a block. diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index b1c43b7..715a9aa 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -224,4 +224,29 @@ def expect_invalid_ids(name) expect(a_request(:any, /.*/)).not_to have_been_made end end + + describe '#update_block' do + it 'sends a PATCH request with the content and the etag' do + body = '{"editor_content":{"content":[{"type":"text","text":"Hello again"}]},"etag":"43"}' + stub = stub_api(:patch, '/emails/123/blocks/57', body: body, response: load_fixture('email_block_updated')) + + response = emails.update_block(email_id: '123', block_id: '57', etag: '43', + editor_content: { content: [{ type: 'text', text: 'Hello again' }] }) + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['etag']).to eq '44' + expect(data['data']['editor_content']['content'][0]['text']).to eq 'Hello again' + expect(data['data']['placement']).to eq('after' => '56', 'before' => '58') + end + + it 'checks the arguments and sends no request' do + expect_invalid_ids('email_id') { |id| emails.update_block(email_id: id, block_id: '57', etag: '43', editor_content: {}) } + expect_invalid_ids('block_id') { |id| emails.update_block(email_id: '123', block_id: id, etag: '43', editor_content: {}) } + expect { emails.update_block(email_id: '123', block_id: '57', etag: '', editor_content: {}) }.to raise_error(MailerLite::EmptyEtagError) + expect { emails.update_block(email_id: '123', block_id: '57', etag: '43', editor_content: []) } + .to raise_error(TypeError, /`editor_content`/) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end end From cdb9c16c59438ba7d5c97b28a27f33922e50cef5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:49:46 +0100 Subject: [PATCH 10/30] feat: add Emails#delete_block Add Emails#delete_block. It sends a DELETE request with the etag in the body, and returns the response with the new etag. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++++++++++++++++++ lib/mailerlite/emails/emails.rb | 16 ++++++++++++++++ spec/emails_rspec.rb | 19 +++++++++++++++++++ 3 files changed, 53 insertions(+) diff --git a/README.md b/README.md index 91dbf56..6388832 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Get a block](#get-a-block) - [Insert a block](#insert-a-block) - [Update a block](#update-a-block) + - [Delete a block](#delete-a-block) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -698,6 +699,23 @@ response = emails.update_block( etag = JSON.parse(response.body)['etag'] ``` +### Delete a block + + + +Also deletes the blocks in it. The response has only the new etag. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.delete_block(email_id: '123456', block_id: '57', etag: 'etag-from-the-last-response') + +etag = JSON.parse(response.body)['etag'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index c8e367c..4eea998 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -133,6 +133,22 @@ def update_block(email_id:, block_id:, etag:, editor_content:) Request.call(client, :patch, "/emails/#{email_id}/blocks/#{block_id}", json: body) end + # Deletes a block of the email, and the blocks in it. The response has only the new etag of the email, + # so the method returns the response and not true. + # + # @param email_id [String, Integer] the ID of the email + # @param block_id [String, Integer] the ID of the block + # @param etag [String] the etag from the last response for the email + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid + # @raise [MailerLite::EmptyEtagError] if the etag is empty + # @raise [TypeError] if an argument has a type that is not valid + def delete_block(email_id:, block_id:, etag:) + email_id = Params.path_id(email_id, 'email_id') + block_id = Params.path_id(block_id, 'block_id') + Request.call(client, :delete, "/emails/#{email_id}/blocks/#{block_id}", json: { 'etag' => Params.etag(etag) }) + end + private # Returns the body to insert or to validate a block. diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 715a9aa..6b5ca2d 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -249,4 +249,23 @@ def expect_invalid_ids(name) expect(a_request(:any, /.*/)).not_to have_been_made end end + + describe '#delete_block' do + it 'sends a DELETE request with the etag in the body, and returns the new etag' do + stub = stub_api(:delete, '/emails/123/blocks/57', body: '{"etag":"44"}', response: load_fixture('email_etag')) + + response = emails.delete_block(email_id: '123', block_id: '57', etag: '44') + + expect(stub).to have_been_requested + expect(response).to be_a(HTTP::Response) + expect(decoded(response)).to eq('etag' => '45') + end + + it 'checks the arguments and sends no request' do + expect_invalid_ids('email_id') { |id| emails.delete_block(email_id: id, block_id: '57', etag: '44') } + expect_invalid_ids('block_id') { |id| emails.delete_block(email_id: '123', block_id: id, etag: '44') } + expect { emails.delete_block(email_id: '123', block_id: '57', etag: nil) }.to raise_error(MailerLite::EmptyEtagError) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end end From efe667acbb9b1314c2754d4d769e5f5fadc53f04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:50:06 +0100 Subject: [PATCH 11/30] feat: add Emails#move_block Add Emails#move_block. It moves a block to a new placement in the email. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 23 +++++++++++++++++++ lib/mailerlite/emails/emails.rb | 17 ++++++++++++++ spec/emails_rspec.rb | 40 +++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+) diff --git a/README.md b/README.md index 6388832..f3c32b1 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Insert a block](#insert-a-block) - [Update a block](#update-a-block) - [Delete a block](#delete-a-block) + - [Move a block](#move-a-block) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -716,6 +717,28 @@ response = emails.delete_block(email_id: '123456', block_id: '57', etag: 'etag-f etag = JSON.parse(response.body)['etag'] ``` +### Move a block + + + +The `BEFORE` and `AFTER` positions also need a `block_id`. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.move_block( + email_id: '123456', + block_id: '57', + etag: 'etag-from-the-last-response', + placement: { position: MailerLite::Emails::BlockPosition::AFTER, block_id: '12' } +) + +etag = JSON.parse(response.body)['etag'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index 4eea998..b6d3610 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -149,6 +149,23 @@ def delete_block(email_id:, block_id:, etag:) Request.call(client, :delete, "/emails/#{email_id}/blocks/#{block_id}", json: { 'etag' => Params.etag(etag) }) end + # Moves a block of the email. Returns the block, its new place in the email, and the new etag of the email. + # + # @param email_id [String, Integer] the ID of the email + # @param block_id [String, Integer] the ID of the block to move + # @param etag [String] the etag from the last response for the email + # @param placement [Hash] `position` (see `BlockPosition`) and, for `before` and `after`, `block_id` + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid + # @raise [MailerLite::EmptyEtagError] if the etag is empty + # @raise [TypeError] if an argument has a type that is not valid + def move_block(email_id:, block_id:, etag:, placement:) + email_id = Params.path_id(email_id, 'email_id') + block_id = Params.path_id(block_id, 'block_id') + body = { 'placement' => Params.placement(placement), 'etag' => Params.etag(etag) } + Request.call(client, :post, "/emails/#{email_id}/blocks/#{block_id}/move", json: body) + end + private # Returns the body to insert or to validate a block. diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 6b5ca2d..4f0e128 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -268,4 +268,44 @@ def expect_invalid_ids(name) expect(a_request(:any, /.*/)).not_to have_been_made end end + + describe '#move_block' do + it 'sends the placement and the etag' do + stub = stub_api(:post, '/emails/123/blocks/57/move', body: '{"placement":{"position":"before","block_id":"1"},"etag":"45"}', + response: load_fixture('email_block_moved')) + + response = emails.move_block(email_id: '123', block_id: '57', etag: '45', + placement: { 'position' => described_class::BlockPosition::BEFORE, 'block_id' => 1 }) + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['etag']).to eq '46' + expect(data['data']['placement']).to have_key('after') + expect(data['data']['placement']['after']).to be_nil + expect(data['data']['placement']['before']).to eq '1' + end + + it 'sends a placement without a block_id' do + stub = stub_api(:post, '/emails/123/blocks/57/move', body: '{"placement":{"position":"start"},"etag":"45"}', + response: load_fixture('email_block_moved')) + + emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: { position: described_class::BlockPosition::AT_START }) + + expect(stub).to have_been_requested + end + + it 'checks the arguments and sends no request' do + expect_invalid_ids('email_id') { |id| emails.move_block(email_id: id, block_id: '57', etag: '45', placement: { position: 'end' }) } + expect_invalid_ids('block_id') { |id| emails.move_block(email_id: '123', block_id: id, etag: '45', placement: { position: 'end' }) } + expect_invalid_ids('block_id') do |id| + emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: { position: 'after', block_id: id }) + end + expect_invalid_ids('block_id') do |id| + emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: { 'position' => 'after', 'block_id' => id }) + end + expect { emails.move_block(email_id: '123', block_id: '57', etag: '', placement: { position: 'end' }) }.to raise_error(MailerLite::EmptyEtagError) + expect { emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: nil) }.to raise_error(TypeError, /`placement`/) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end end From 03d35cd2e8c265e9671f8a7365d561d60837ac94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:50:27 +0100 Subject: [PATCH 12/30] feat: add Emails#validate_block Add Emails#validate_block. It checks a block without an email and without an etag. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 22 ++++++++++++++++++++ lib/mailerlite/emails/emails.rb | 13 ++++++++++++ spec/emails_rspec.rb | 36 +++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) diff --git a/README.md b/README.md index f3c32b1..2dfe1ff 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Update a block](#update-a-block) - [Delete a block](#delete-a-block) - [Move a block](#move-a-block) + - [Validate a block](#validate-a-block) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -739,6 +740,27 @@ response = emails.move_block( etag = JSON.parse(response.body)['etag'] ``` +### Validate a block + + + +Checks a block before you insert it. It needs no email and no etag. An invalid block is not an error: the response has `valid` set to `false` and the `errors` for each field. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.validate_block( + type: MailerLite::Emails::BlockType::BUTTON, + editor_content: { attrs: { href: 'https://example.com' }, content: [{ type: 'text', text: 'Buy now' }] } +) + +body = JSON.parse(response.body) +puts body['errors'] unless body['valid'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index b6d3610..11d37f3 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -166,6 +166,19 @@ def move_block(email_id:, block_id:, etag:, placement:) Request.call(client, :post, "/emails/#{email_id}/blocks/#{block_id}/move", json: body) end + # Validates a block before you insert it. It needs no email and no etag. An invalid block is not an error: + # the response has `valid` set to false and the `errors` for each field. + # + # @param type [String] the block type, see `BlockType` + # @param editor_content [Hash] the content of the block. Its keys are camelCase, for example `textAlign`. + # @param placement [Hash, nil] `position` (see `BlockPosition`) and, for `before` and `after`, `block_id` + # @return [HTTP::Response] the response from the API, with `valid`, `errors` and `schema` + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if the `block_id` of the placement is not valid + # @raise [TypeError] if an argument has a type that is not valid + def validate_block(type:, editor_content:, placement: nil) + Request.call(client, :post, '/emails/blocks/validate', json: block_body(type, editor_content, placement)) + end + private # Returns the body to insert or to validate a block. diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 4f0e128..29ff63f 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -308,4 +308,40 @@ def expect_invalid_ids(name) expect(a_request(:any, /.*/)).not_to have_been_made end end + + describe '#validate_block' do + it 'sends the block without an etag and returns a valid result' do + body = '{"type":"button","editor_content":{"attrs":{"href":"https://example.com"}},"placement":{"position":"end"}}' + stub = stub_api(:post, '/emails/blocks/validate', body: body, response: load_fixture('email_block_validation_valid')) + + response = emails.validate_block(type: 'button', editor_content: { attrs: { href: 'https://example.com' } }, + placement: { position: described_class::BlockPosition::AT_END }) + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['valid']).to be(true) + expect(data['errors']).to eq({}) + expect(data['schema']['version']).to eq '2.73.2' + end + + it 'returns an invalid result as a 200 response' do + stub = stub_api(:post, '/emails/blocks/validate', body: '{"type":"unknown","editor_content":{}}', + response: load_fixture('email_block_validation_invalid')) + + response = emails.validate_block(type: 'unknown', editor_content: {}) + + expect(stub).to have_been_requested + expect(response.api_error).to be_nil + data = decoded(response) + expect(data['valid']).to be(false) + expect(data['errors']).to eq('type' => ['The selected type is invalid.']) + end + + it 'checks the arguments and sends no request' do + expect_invalid_ids('block_id') { |id| emails.validate_block(type: 'divider', editor_content: {}, placement: { position: 'after', block_id: id }) } + expect { emails.validate_block(type: nil, editor_content: {}) }.to raise_error(TypeError, /`type`/) + expect { emails.validate_block(type: 'divider', editor_content: 'x') }.to raise_error(TypeError, /`editor_content`/) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end end From eb04478688bdac945ea4849e9e587043e2a32f26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:50:57 +0100 Subject: [PATCH 13/30] feat: add Emails#update_settings Add Emails#update_settings. It sends a PATCH request with the keys of the settings Hash and the etag. It rejects settings that contain an etag key. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 35 +++++++++++++++++++++++++ lib/mailerlite/emails/emails.rb | 27 +++++++++++++++++++ spec/emails_rspec.rb | 46 +++++++++++++++++++++++++++++++++ 3 files changed, 108 insertions(+) diff --git a/README.md b/README.md index 2dfe1ff..2f1d743 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Delete a block](#delete-a-block) - [Move a block](#move-a-block) - [Validate a block](#validate-a-block) + - [Update the design settings](#update-the-design-settings) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -761,6 +762,40 @@ body = JSON.parse(response.body) puts body['errors'] unless body['valid'] ``` +### Update the design settings + + + +Send only the keys to change, in the shape of `settings` in the email. The groups are `brand`, `layout`, `typography`, `button` and `footer`. + +- The SDK sends exactly the keys of the Hash. A key that is not in the Hash does not change. An empty string unsets the value. +- Send all style values as strings, for example `'16'` and not `16`. +- The API stores each value that you send, also a value that the email inherits from your account. Then the email no longer follows your account for that value. +- `footer.social_links` replaces the whole list. Keep the `link_id` of each link to keep its click history. +- `brand.mode` is one of `MailerLite::Emails::BrandMode`. To apply a preset palette, send its `identifier` from the brand styles in `brand.style`. +- Do not put `etag` in the settings. Use the `etag` argument. +- If the API removed unsafe values, the response has `rejected` with the keys of these values. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.update_settings( + email_id: '123456', + etag: 'etag-from-the-last-response', + settings: { + brand: { mode: MailerLite::Emails::BrandMode::CUSTOM, background_color: '#f4f4f4' }, + typography: { paragraph: { p1: { size: '18' } } } + } +) + +body = JSON.parse(response.body) +etag = body['etag'] +puts body['rejected']['keys'] if body['rejected'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index 11d37f3..ce2e29a 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -179,6 +179,33 @@ def validate_block(type:, editor_content:, placement: nil) Request.call(client, :post, '/emails/blocks/validate', json: block_body(type, editor_content, placement)) end + # Updates the design settings of the email. Returns the settings and the new etag of the email. + # + # Send only the keys to change, in the shape of `settings` in the response of `get`. The groups are `brand`, + # `layout`, `typography`, `button` and `footer`. The SDK sends exactly the keys of the Hash: + # - a key that is not in the Hash does not change; + # - an empty String unsets the value; + # - any other value is the new value. Send style values as Strings, for example '16'. + # + # The API stores each value that you send, also a value that the email inherits from the account. + # `footer.social_links` replaces the whole list: keep the `link_id` of each link to keep its click history. + # To apply a preset palette, send its `identifier` from `BrandStyles#get` in `brand.style`. + # The response can have `rejected` when the API removed unsafe values. + # + # @param email_id [String, Integer] the ID of the email + # @param etag [String] the etag from the last response for the email + # @param settings [Hash] the settings to change, without `etag` + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if the ID is not valid + # @raise [MailerLite::EmptyEtagError] if the etag is empty + # @raise [ArgumentError] if the settings contain an `etag` key + # @raise [TypeError] if an argument has a type that is not valid + def update_settings(email_id:, etag:, settings:) + email_id = Params.path_id(email_id, 'email_id') + body = Params.settings(settings).merge('etag' => Params.etag(etag)) + Request.call(client, :patch, "/emails/#{email_id}/settings", json: body) + end + private # Returns the body to insert or to validate a block. diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 29ff63f..5abc9ff 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -344,4 +344,50 @@ def expect_invalid_ids(name) expect(a_request(:any, /.*/)).not_to have_been_made end end + + describe '#update_settings' do + it 'sends a PATCH request with only the keys of the caller and the etag' do + body = '{"brand":{"mode":"custom","background_color":"#f4f4f4"},"footer":{"company_name":""},"etag":"46"}' + stub = stub_api(:patch, '/emails/123/settings', body: body, response: load_fixture('email_settings')) + settings = { brand: { mode: described_class::BrandMode::CUSTOM, background_color: '#f4f4f4' }, footer: { company_name: '' } } + + response = emails.update_settings(email_id: '123', etag: '46', settings: settings) + + expect(stub).to have_been_requested + expect(settings).to eq(brand: { mode: 'custom', background_color: '#f4f4f4' }, footer: { company_name: '' }) + data = decoded(response) + expect(data['etag']).to eq '47' + expect(data['data']['brand']['mode']).to eq 'custom' + expect(data['data']['brand']['background_color']).to eq '#f4f4f4' + expect(data['data']['typography']['paragraph']['p1']['size']).to eq '16' + expect(data['rejected']['keys']).to eq ['footer.social_links[0].url'] + end + + it 'sends a nil value as null' do + stub = stub_api(:patch, '/emails/123/settings', body: '{"layout":{"alignment":null},"etag":"46"}', response: load_fixture('email_settings')) + + emails.update_settings(email_id: '123', etag: '46', settings: { 'layout' => { 'alignment' => nil } }) + + expect(stub).to have_been_requested + end + + it 'returns a version conflict' do + stub_api(:patch, '/emails/123/settings', body: '{"layout":{"alignment":"left"},"etag":"40"}', status: 409, + response: { message: 'The email was changed.', code: 'version_conflict', etag: '46' }) + + response = emails.update_settings(email_id: '123', etag: '40', settings: { layout: { alignment: 'left' } }) + + expect(response.api_error.code).to eq described_class::VERSION_CONFLICT + expect(response.api_error.etag).to eq '46' + end + + it 'checks the arguments and sends no request' do + expect_invalid_ids('email_id') { |id| emails.update_settings(email_id: id, etag: '46', settings: {}) } + expect { emails.update_settings(email_id: '123', etag: '', settings: {}) }.to raise_error(MailerLite::EmptyEtagError) + expect { emails.update_settings(email_id: '123', etag: '46', settings: nil) }.to raise_error(TypeError, /`settings`/) + expect { emails.update_settings(email_id: '123', etag: '46', settings: { etag: '1' }) }.to raise_error(ArgumentError, /etag/) + expect { emails.update_settings(email_id: '123', etag: '46', settings: { 'etag' => '1' }) }.to raise_error(ArgumentError, /etag/) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end end From c34b09a7895481072966c65960ff66b88979cb84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:51:17 +0100 Subject: [PATCH 14/30] feat: add Emails#validate_settings Add Emails#validate_settings. It checks a change to the design settings without an etag, and saves nothing. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 19 +++++++++++++++++++ lib/mailerlite/emails/emails.rb | 15 +++++++++++++++ spec/emails_rspec.rb | 23 +++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/README.md b/README.md index 2f1d743..652394b 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Move a block](#move-a-block) - [Validate a block](#validate-a-block) - [Update the design settings](#update-the-design-settings) + - [Validate the design settings](#validate-the-design-settings) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -796,6 +797,24 @@ etag = body['etag'] puts body['rejected']['keys'] if body['rejected'] ``` +### Validate the design settings + + + +Checks a change with the rules of the update, and saves nothing. It needs no etag. Invalid settings are not an error: the response has `valid` set to `false` and the `errors` for each field. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.validate_settings(email_id: '123456', settings: { button: { border_radius: '8' } }) + +body = JSON.parse(response.body) +puts body['errors'] unless body['valid'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index ce2e29a..e0a572f 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -206,6 +206,21 @@ def update_settings(email_id:, etag:, settings:) Request.call(client, :patch, "/emails/#{email_id}/settings", json: body) end + # Validates a change to the design settings of the email with the rules of `update_settings`, and saves nothing. + # It needs no etag. Invalid settings are not an error: the response has `valid` set to false and the `errors` + # for each field. The response can also have `rejected`. + # + # @param email_id [String, Integer] the ID of the email + # @param settings [Hash] the settings that you want to send to `update_settings`, without `etag` + # @return [HTTP::Response] the response from the API, with `valid`, `errors` and `schema` + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if the ID is not valid + # @raise [ArgumentError] if the settings contain an `etag` key + # @raise [TypeError] if an argument has a type that is not valid + def validate_settings(email_id:, settings:) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :post, "/emails/#{email_id}/settings/validate", json: Params.settings(settings)) + end + private # Returns the body to insert or to validate a block. diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 5abc9ff..4dd9bc5 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -390,4 +390,27 @@ def expect_invalid_ids(name) expect(a_request(:any, /.*/)).not_to have_been_made end end + + describe '#validate_settings' do + it 'sends the settings without an etag' do + stub = stub_api(:post, '/emails/123/settings/validate', body: '{"layout":{"width":"700"}}', response: load_fixture('email_settings_validation')) + + response = emails.validate_settings(email_id: '123', settings: { layout: { width: '700' } }) + + expect(stub).to have_been_requested + expect(response.api_error).to be_nil + data = decoded(response) + expect(data['valid']).to be(false) + expect(data['errors']).to eq('layout.width' => ['The layout.width field cannot be changed.']) + expect(data['rejected']['message']).to eq 'Some attributes were rejected.' + end + + it 'checks the arguments and sends no request' do + expect_invalid_ids('email_id') { |id| emails.validate_settings(email_id: id, settings: {}) } + expect { emails.validate_settings(email_id: '123', settings: 'x') }.to raise_error(TypeError, /`settings`/) + expect { emails.validate_settings(email_id: '123', settings: { etag: '1' }) }.to raise_error(ArgumentError, /etag/) + expect { emails.validate_settings(email_id: '123', settings: { 'etag' => '1' }) }.to raise_error(ArgumentError, /etag/) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end end From 92806cec46173916494d8473808b147710c12788 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:51:34 +0100 Subject: [PATCH 15/30] feat: add Emails#create_template Add Emails#create_template. It saves an email as a new template. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++++++++++++++++++ lib/mailerlite/emails/emails.rb | 12 ++++++++++++ spec/emails_rspec.rb | 21 +++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/README.md b/README.md index 652394b..b7354bb 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Validate a block](#validate-a-block) - [Update the design settings](#update-the-design-settings) - [Validate the design settings](#validate-the-design-settings) + - [Save an email as a template](#save-an-email-as-a-template) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -815,6 +816,23 @@ body = JSON.parse(response.body) puts body['errors'] unless body['valid'] ``` +### Save an email as a template + + + +Copies the email to a new template. The API cannot delete templates. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.create_template(email_id: '123456', name: 'Monthly newsletter') + +template_id = JSON.parse(response.body)['data']['id'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index e0a572f..8b0d7a3 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -221,6 +221,18 @@ def validate_settings(email_id:, settings:) Request.call(client, :post, "/emails/#{email_id}/settings/validate", json: Params.settings(settings)) end + # Saves the email as a new template with the name. The API cannot delete templates. + # + # @param email_id [String, Integer] the ID of the email + # @param name [String] the name of the template + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if the ID is not valid + # @raise [TypeError] if an argument has a type that is not valid + def create_template(email_id:, name:) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :post, "/emails/#{email_id}/templates", json: { 'name' => Params.require_string(name, 'name') }) + end + private # Returns the body to insert or to validate a block. diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 4dd9bc5..47c42f8 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -413,4 +413,25 @@ def expect_invalid_ids(name) expect(a_request(:any, /.*/)).not_to have_been_made end end + + describe '#create_template' do + it 'sends the name and returns the template' do + stub = stub_api(:post, '/emails/123/templates', body: '{"name":"Newsletter"}', status: 201, response: load_fixture('email_template')) + + response = emails.create_template(email_id: '123', name: 'Newsletter') + + expect(stub).to have_been_requested + expect(response.code).to eq 201 + data = decoded(response) + expect(data['data']).to eq('id' => '789', 'name' => 'Newsletter', 'type' => 'email', 'created_at' => '2026-10-28 12:00:00') + expect(data).not_to have_key('etag') + end + + it 'checks the arguments and sends no request' do + expect_invalid_ids('email_id') { |id| emails.create_template(email_id: id, name: 'Newsletter') } + expect { emails.create_template(email_id: '123', name: nil) }.to raise_error(TypeError, /`name`/) + expect { emails.create_template(email_id: '123', name: 1) }.to raise_error(TypeError, /`name`/) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end end From 203940ca2de090fbeebb2eb91be4f6fbbec4f417 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:51:51 +0100 Subject: [PATCH 16/30] feat: add Emails#list_versions Add Emails#list_versions. It lists the saved versions of an email, with an optional page and limit. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++++++++++++++++++ lib/mailerlite/emails/emails.rb | 12 ++++++++++++ spec/emails_rspec.rb | 29 +++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/README.md b/README.md index b7354bb..f4550e8 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Update the design settings](#update-the-design-settings) - [Validate the design settings](#validate-the-design-settings) - [Save an email as a template](#save-an-email-as-a-template) + - [List the versions of an email](#list-the-versions-of-an-email) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -833,6 +834,23 @@ response = emails.create_template(email_id: '123456', name: 'Monthly newsletter' template_id = JSON.parse(response.body)['data']['id'] ``` +### List the versions of an email + + + +A version is a saved copy of the content and the settings of an email. The list starts with the newest version. `current` marks the version that the email has now. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.list_versions('123456', page: 1, limit: 10) + +versions = JSON.parse(response.body)['data'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index 8b0d7a3..f279c74 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -233,6 +233,18 @@ def create_template(email_id:, name:) Request.call(client, :post, "/emails/#{email_id}/templates", json: { 'name' => Params.require_string(name, 'name') }) end + # Returns the saved versions of the email, newest first. `current` marks the version that the email has now. + # + # @param email_id [String, Integer] the ID of the email + # @param page [Integer] the page number of the results to return + # @param limit [Integer] the maximum number of versions to return, from 1 to 100 + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + def list_versions(email_id, page: nil, limit: nil) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :get, "/emails/#{email_id}/versions", query: Params.query(page: page, limit: limit)) + end + private # Returns the body to insert or to validate a block. diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 47c42f8..a0d20a4 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -434,4 +434,33 @@ def expect_invalid_ids(name) expect(a_request(:any, /.*/)).not_to have_been_made end end + + describe '#list_versions' do + it 'sends no query without options' do + stub = stub_api(:get, '/emails/123/versions', response: load_fixture('email_versions')) + + response = emails.list_versions('123') + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['data'].map { |version| version['id'] }).to eq %w[902 901] + expect(data['data'][0]['current']).to be(true) + expect(data['data'][1]['current']).to be(false) + expect(data['links']).to have_key('prev') + expect(data['links']['prev']).to be_nil + expect(data['meta']['total']).to eq 2 + end + + it 'sends the page and the limit' do + stub = stub_api(:get, '/emails/123/versions', query: { 'page' => '2', 'limit' => '10' }, response: load_fixture('email_versions')) + + emails.list_versions(123, page: 2, limit: 10) + + expect(stub).to have_been_requested + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.list_versions(id) } + end + end end From e299e85ba21b5ae35ce2ae46bb8f780a1a6bb825 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:52:09 +0100 Subject: [PATCH 17/30] feat: add Emails#create_version Add Emails#create_version. It saves a version of an email and sends no request body. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 19 +++++++++++++++++++ lib/mailerlite/emails/emails.rb | 12 ++++++++++++ spec/emails_rspec.rb | 26 ++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/README.md b/README.md index f4550e8..c1ef686 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Validate the design settings](#validate-the-design-settings) - [Save an email as a template](#save-an-email-as-a-template) - [List the versions of an email](#list-the-versions-of-an-email) + - [Save a version of an email](#save-a-version-of-an-email) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -851,6 +852,24 @@ response = emails.list_versions('123456', page: 1, limit: 10) versions = JSON.parse(response.body)['data'] ``` +### Save a version of an email + + + +Writes through the API do not save versions. If nothing changed after the last version, the API saves no new version and returns the last version. `response.code` is `201` for a new version and `200` for the last version. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.create_version('123456') + +version_id = JSON.parse(response.body)['data']['id'] +is_new = response.code == 201 +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index f279c74..0bb230c 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -245,6 +245,18 @@ def list_versions(email_id, page: nil, limit: nil) Request.call(client, :get, "/emails/#{email_id}/versions", query: Params.query(page: page, limit: limit)) end + # Saves the content and the settings of the email as a new version. If nothing changed after the last version, + # the API saves no new version and returns the last version. The status code (`response.code`) is 201 for a new + # version and 200 for the last version. Both are a success. + # + # @param email_id [String, Integer] the ID of the email + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + def create_version(email_id) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :post, "/emails/#{email_id}/versions") + end + private # Returns the body to insert or to validate a block. diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index a0d20a4..b1e5993 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -463,4 +463,30 @@ def expect_invalid_ids(name) expect_invalid_ids('email_id') { |id| emails.list_versions(id) } end end + + describe '#create_version' do + it 'sends no body and returns 201 for a new version' do + stub = stub_api(:post, '/emails/123/versions', body: '', status: 201, response: load_fixture('email_version')) + + response = emails.create_version('123') + + expect(stub).to have_been_requested + expect(response.code).to eq 201 + expect(decoded(response)['data']).to eq('id' => '903', 'created_at' => '2026-10-28 12:10:00', 'current' => true) + end + + it 'returns 200 for the last version when nothing changed' do + stub_api(:post, '/emails/123/versions', body: '', status: 200, response: load_fixture('email_version')) + + response = emails.create_version(123) + + expect(response.code).to eq 200 + expect(response.api_error).to be_nil + expect(decoded(response)['data']['id']).to eq '903' + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.create_version(id) } + end + end end From 298975a3b5cadf1bbea315683e6a523e0ea86ed1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:52:25 +0100 Subject: [PATCH 18/30] feat: add Emails#restore_version Add Emails#restore_version. It restores an email to a saved version and returns the email with the new etag. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++++++++++++++++++ lib/mailerlite/emails/emails.rb | 16 ++++++++++++++++ spec/emails_rspec.rb | 21 +++++++++++++++++++++ 3 files changed, 55 insertions(+) diff --git a/README.md b/README.md index c1ef686..883fe01 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [Save an email as a template](#save-an-email-as-a-template) - [List the versions of an email](#list-the-versions-of-an-email) - [Save a version of an email](#save-a-version-of-an-email) + - [Restore a version of an email](#restore-a-version-of-an-email) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -870,6 +871,23 @@ version_id = JSON.parse(response.body)['data']['id'] is_new = response.code == 201 ``` +### Restore a version of an email + + + +Puts the email back to the version, and returns the full email with the new etag. Before the restore, the API saves the current state as a version, so you can undo the restore. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.restore_version(email_id: '123456', version_id: '901', etag: 'etag-from-the-last-response') + +etag = JSON.parse(response.body)['etag'] +``` + ## Forms diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index 0bb230c..888e70f 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -257,6 +257,22 @@ def create_version(email_id) Request.call(client, :post, "/emails/#{email_id}/versions") end + # Restores the email to a version. Returns the email in the shape of `get`, with the new etag. Before the + # restore, the API saves the current state as a version, so you can undo the restore. + # + # @param email_id [String, Integer] the ID of the email + # @param version_id [String, Integer] the ID of the version + # @param etag [String] the etag from the last response for the email + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid + # @raise [MailerLite::EmptyEtagError] if the etag is empty + # @raise [TypeError] if an argument has a type that is not valid + def restore_version(email_id:, version_id:, etag:) + email_id = Params.path_id(email_id, 'email_id') + version_id = Params.path_id(version_id, 'version_id') + Request.call(client, :post, "/emails/#{email_id}/versions/#{version_id}/restore", json: { 'etag' => Params.etag(etag) }) + end + private # Returns the body to insert or to validate a block. diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index b1e5993..07f60aa 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -489,4 +489,25 @@ def expect_invalid_ids(name) expect_invalid_ids('email_id') { |id| emails.create_version(id) } end end + + describe '#restore_version' do + it 'sends the etag and returns the email' do + stub = stub_api(:post, '/emails/123/versions/901/restore', body: '{"etag":"47"}', response: load_fixture('email')) + + response = emails.restore_version(email_id: '123', version_id: 901, etag: '47') + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['etag']).to eq '42' + expect(data['data']['id']).to eq '123' + expect(data['data']['blocks'].size).to eq 2 + end + + it 'checks the arguments and sends no request' do + expect_invalid_ids('email_id') { |id| emails.restore_version(email_id: id, version_id: '901', etag: '47') } + expect_invalid_ids('version_id') { |id| emails.restore_version(email_id: '123', version_id: id, etag: '47') } + expect { emails.restore_version(email_id: '123', version_id: '901', etag: '') }.to raise_error(MailerLite::EmptyEtagError) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end end From d2c2fd840fc3eb788e4f3fa8f402018842a8c454 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:52:49 +0100 Subject: [PATCH 19/30] feat: add BrandStyles#get Add the BrandStyles class and BrandStyles#get. It returns the brand, default and preset palettes of the account. Add its README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 23 ++++++++++ lib/mailerlite.rb | 1 + lib/mailerlite/brand_styles/brand_styles.rb | 24 +++++++++++ spec/brand_styles_rspec.rb | 47 +++++++++++++++++++++ 4 files changed, 95 insertions(+) create mode 100644 lib/mailerlite/brand_styles/brand_styles.rb create mode 100644 spec/brand_styles_rspec.rb diff --git a/README.md b/README.md index 883fe01..a177c9e 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,8 @@ For more information how to obtain an API key visit the [following link](https:/ - [List the versions of an email](#list-the-versions-of-an-email) - [Save a version of an email](#save-a-version-of-an-email) - [Restore a version of an email](#restore-a-version-of-an-email) + - [Brand styles](#brand-styles) + - [Get the brand styles](#get-the-brand-styles) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -888,6 +890,27 @@ response = emails.restore_version(email_id: '123456', version_id: '901', etag: ' etag = JSON.parse(response.body)['etag'] ``` +## Brand styles + + + +### Get the brand styles + + + +Returns the palettes of your account: `brand` (your brand styles, or `nil` if your account has none), `default` and the `presets`. Match a palette on its `identifier`, not on its `name`. To apply a preset to an email, [update the design settings](#update-the-design-settings) with `{ brand: { style: identifier } }`. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +brand_styles = MailerLite::BrandStyles.new + +response = brand_styles.get + +identifiers = JSON.parse(response.body)['data']['presets'].map { |preset| preset['identifier'] } +``` + ## Forms diff --git a/lib/mailerlite.rb b/lib/mailerlite.rb index 6b54825..479b553 100644 --- a/lib/mailerlite.rb +++ b/lib/mailerlite.rb @@ -24,3 +24,4 @@ require_relative 'mailerlite/timezones/timezones' require_relative 'mailerlite/ecommerce/ecommerce' require_relative 'mailerlite/emails/emails' +require_relative 'mailerlite/brand_styles/brand_styles' diff --git a/lib/mailerlite/brand_styles/brand_styles.rb b/lib/mailerlite/brand_styles/brand_styles.rb new file mode 100644 index 0000000..a69d961 --- /dev/null +++ b/lib/mailerlite/brand_styles/brand_styles.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +module MailerLite + # This is a class for the brand styles from MailerLite API. + class BrandStyles + attr_reader :client + + # Inits the `BrandStyles` class with the specified `client`. + # + # @param client [MailerLite::Client] the `Client` instance to use + def initialize(client: MailerLite::Client.new) + @client = client + end + + # Returns the palettes of the account: `brand` (the brand styles of the account, or nil if it has none), + # `default` and the `presets`. Match a palette on its `identifier`, not on its `name`. + # To apply a preset to an email, send its `identifier` in `brand.style` with `Emails#update_settings`. + # + # @return [HTTP::Response] the response from the API, with the `MailerLite::ApiResponse` methods + def get + Request.call(client, :get, '/brand-styles') + end + end +end diff --git a/spec/brand_styles_rspec.rb b/spec/brand_styles_rspec.rb new file mode 100644 index 0000000..55edafd --- /dev/null +++ b/spec/brand_styles_rspec.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' +require 'json' +require_relative 'support/json_fixture' + +RSpec.describe MailerLite::BrandStyles do + let(:brand_styles) { described_class.new(client: MailerLite::Client.new) } + let(:url) { "#{MAILERLITE_API_URL}/brand-styles" } + + def stub_brand_styles(response) + stub_request(:get, url) + .with(headers: { 'Authorization' => 'Bearer dummy_token' }) { |req| req.body == '' && !req.headers.key?('Idempotency-Key') } + .to_return(status: 200, body: response.to_json, headers: { 'Content-Type' => 'application/json' }) + end + + describe '#get' do + it 'gets the palettes' do + stub = stub_brand_styles(load_fixture('brand_styles')) + + response = brand_styles.get + + expect(stub).to have_been_requested + expect(response).to be_a(HTTP::Response) + expect(response.api_error).to be_nil + data = JSON.parse(response.body.to_s)['data'] + expect(data['brand']['identifier']).to eq 'account' + expect(data['brand']['primary_color']).to eq '#2cb191' + expect(data['default']['identifier']).to eq 'default-brand' + expect(data['presets'].map { |preset| preset['identifier'] }).to eq %w[preset-business-casual preset-retro] + expect(data['presets'][1]['font_family']).to eq 'Courier New, monospace' + end + + it 'returns a null brand when the account has none' do + body = load_fixture('brand_styles') + body['data']['brand'] = nil + stub_brand_styles(body) + + data = JSON.parse(brand_styles.get.body.to_s)['data'] + + expect(data).to have_key('brand') + expect(data['brand']).to be_nil + expect(data['default']['identifier']).to eq 'default-brand' + end + end +end From efb6631af17484e90d1256c31f0de80a2709b79b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:53:21 +0100 Subject: [PATCH 20/30] feat: add Files#list Add the Files class and Files#list. It lists the files of the media library with an optional filter, sort, page and limit. It drops nil values from the query. Add the constants for the file types and the sort values, and the README section. Co-Authored-By: Claude Opus 5.5 --- README.md | 32 +++++++++++++ lib/mailerlite.rb | 1 + lib/mailerlite/files/files.rb | 46 ++++++++++++++++++ spec/files_rspec.rb | 88 +++++++++++++++++++++++++++++++++++ 4 files changed, 167 insertions(+) create mode 100644 lib/mailerlite/files/files.rb create mode 100644 spec/files_rspec.rb diff --git a/README.md b/README.md index a177c9e..ef431f4 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,8 @@ For more information how to obtain an API key visit the [following link](https:/ - [Restore a version of an email](#restore-a-version-of-an-email) - [Brand styles](#brand-styles) - [Get the brand styles](#get-the-brand-styles) + - [Files](#files) + - [List all files](#list-all-files) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -911,6 +913,36 @@ response = brand_styles.get identifiers = JSON.parse(response.body)['data']['presets'].map { |preset| preset['identifier'] } ``` +## Files + + + +### List all files + + + +Returns the files of your media library. Use their `url` in image blocks. `width` and `height` are `nil` for files that are not images. + +- `filter`: `name` (a part of the file name) and `type` (one of `MailerLite::Files::FileType`). +- `sort`: one of `MailerLite::Files::FileSort`. The default is newest first. +- The SDK does not send `nil` values. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +files = MailerLite::Files.new + +response = files.list( + filter: { name: 'summer sale', type: MailerLite::Files::FileType::IMAGE }, + sort: MailerLite::Files::FileSort::SIZE_DESC, + page: 1, + limit: 25 +) + +urls = JSON.parse(response.body)['data'].map { |file| file['url'] } +``` + ## Forms diff --git a/lib/mailerlite.rb b/lib/mailerlite.rb index 479b553..0fce1f4 100644 --- a/lib/mailerlite.rb +++ b/lib/mailerlite.rb @@ -25,3 +25,4 @@ require_relative 'mailerlite/ecommerce/ecommerce' require_relative 'mailerlite/emails/emails' require_relative 'mailerlite/brand_styles/brand_styles' +require_relative 'mailerlite/files/files' diff --git a/lib/mailerlite/files/files.rb b/lib/mailerlite/files/files.rb new file mode 100644 index 0000000..948cd4d --- /dev/null +++ b/lib/mailerlite/files/files.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +module MailerLite + # This is a class for the files of the media library from MailerLite API. + # The name is `Files`, not `File`, so it does not hide the `File` class of Ruby. + class Files + # File types for `filter: { type: ... }`. The API can also return types that are not in this list. + module FileType + IMAGE = 'image' + PDF = 'pdf' + EPUB = 'epub' + end + + # Sort values. The values that start with `-` sort in descending order. + module FileSort + CREATED_AT = 'created_at' + CREATED_AT_DESC = '-created_at' + NAME = 'name' + NAME_DESC = '-name' + SIZE = 'size' + SIZE_DESC = '-size' + end + + attr_reader :client + + # Inits the `Files` class with the specified `client`. + # + # @param client [MailerLite::Client] the `Client` instance to use + def initialize(client: MailerLite::Client.new) + @client = client + end + + # Returns the files of the media library. Use their `url` in image blocks. + # `width` and `height` are nil for files that are not images. The SDK does not send nil values. + # + # @param filter [Hash, nil] `name` (a part of the file name) and `type` (see `FileType`) + # @param sort [String, nil] see `FileSort`. The default is `-created_at`. + # @param page [Integer, nil] the page number of the results to return + # @param limit [Integer, nil] the maximum number of files to return, from 1 to 100 + # @return [HTTP::Response] the response from the API, with the `MailerLite::ApiResponse` methods + # @raise [TypeError] if the filter is not a Hash + def list(filter: nil, sort: nil, page: nil, limit: nil) + Request.call(client, :get, '/files', query: Params.query(filter: filter, sort: sort, page: page, limit: limit)) + end + end +end diff --git a/spec/files_rspec.rb b/spec/files_rspec.rb new file mode 100644 index 0000000..7d49509 --- /dev/null +++ b/spec/files_rspec.rb @@ -0,0 +1,88 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' +require 'json' +require_relative 'support/json_fixture' + +RSpec.describe MailerLite::Files do + let(:files) { described_class.new(client: MailerLite::Client.new) } + let(:url) { "#{MAILERLITE_API_URL}/files" } + + def stub_files(query: nil, status: 200, response: load_fixture('files')) + stub = stub_request(:get, url).with(headers: { 'Authorization' => 'Bearer dummy_token' }) { |req| req.body == '' } + stub = stub.with(query: query) if query + stub.to_return(status: status, body: response.to_json, headers: { 'Content-Type' => 'application/json' }) + end + + # WebMock normalizes the URI (for example `+` becomes `%20`), so keep the raw URI that http.rb sends. + def capture_raw_uris + uris = [] + allow_any_instance_of(HTTP::Client).to receive(:perform).and_wrap_original do |method, request, options| + uris << request.uri.to_s + method.call(request, options) + end + uris + end + + it 'has the constants of the API' do + expect([described_class::FileType::IMAGE, described_class::FileType::PDF, described_class::FileType::EPUB]).to eq %w[image pdf epub] + sorts = described_class::FileSort + expect([sorts::CREATED_AT, sorts::CREATED_AT_DESC, sorts::NAME, sorts::NAME_DESC, sorts::SIZE, sorts::SIZE_DESC]) + .to eq %w[created_at -created_at name -name size -size] + end + + describe '#list' do + it 'sends no query without arguments' do + uris = capture_raw_uris + stub = stub_files + + response = files.list + + expect(stub).to have_been_requested + expect(uris).to eq [url] + data = JSON.parse(response.body.to_s) + expect(data['data'].map { |file| file['name'] }).to eq ['summer sale banner.png', 'summer sale terms.pdf'] + expect(data['data'][0]['width']).to eq 1200 + expect(data['data'][1]).to have_key('width') + expect(data['data'][1]['width']).to be_nil + expect(data['data'][1]['height']).to be_nil + expect(data['links']).to have_key('next') + expect(data['links']['next']).to be_nil + end + + it 'sends the filter, the sort and the pages, and encodes a space as +' do + uris = capture_raw_uris + stub = stub_files(query: { 'filter[name]' => 'summer sale', 'filter[type]' => 'image', 'sort' => '-size', 'page' => '1', 'limit' => '25' }) + + files.list(filter: { name: 'summer sale', type: described_class::FileType::IMAGE }, sort: described_class::FileSort::SIZE_DESC, page: 1, limit: 25) + + expect(stub).to have_been_requested + expect(uris).to eq ["#{url}?filter%5Bname%5D=summer+sale&filter%5Btype%5D=image&sort=-size&page=1&limit=25"] + end + + it 'drops a nil filter value and keeps an empty one' do + uris = capture_raw_uris + stub_files(query: { 'filter[type]' => '' }) + + files.list(filter: { name: nil, type: '' }) + + expect(uris).to eq ["#{url}?filter%5Btype%5D="] + end + + it 'returns the 422 of a file type that is not valid' do + stub_files(query: { 'filter[type]' => 'video' }, status: 422, + response: { message: 'The selected filter.type is invalid.', errors: { 'filter.type' => ['The selected filter.type is invalid.'] } }) + + response = files.list(filter: { type: 'video' }) + + expect(response.code).to eq 422 + expect(response.api_error.errors).to eq('filter.type' => ['The selected filter.type is invalid.']) + end + + it 'checks the filter and sends no request' do + expect { files.list(filter: 'image') }.to raise_error(TypeError, /`filter`/) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end +end From 5f8976feee0d3562fedaad879781feba394cbf39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:54:42 +0100 Subject: [PATCH 21/30] feat: create campaigns with the simple editor Add the EDITOR_SIMPLE constant to Campaigns. Document the editor and template_id keys of the campaign emails. Campaigns#create already sends each email as it is, so the request code does not change. Add a README section and tests for the request body. Co-Authored-By: Claude Opus 5.5 --- README.md | 33 +++++++++++++++++++++- lib/mailerlite/campaigns/campaigns.rb | 9 +++++- lib/mailerlite/emails/emails.rb | 2 +- spec/campaigns_rspec.rb | 40 +++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ef431f4..7ebe202 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [List all campaigns](#list-all-campaigns) - [Get a campaign](#get-a-campaign) - [Create a campaign](#create-a-campaign) + - [Create a campaign with the simple editor](#create-a-campaign-with-the-simple-editor) - [Update a campaign](#update-a-campaign) - [Schedule a campaign](#schedule-a-campaign) - [Cancel a campaign](#cancel-a-campaign) @@ -506,6 +507,36 @@ campaigns.create( ) ``` +### Create a campaign with the simple editor + + + +To build the email with the simple editor, set `editor` to `MailerLite::Campaigns::EDITOR_SIMPLE`, and do not send `content`. Then edit the email with [the email methods](#emails). + +- `template_id` is optional. It is a shared template of the simple editor that the email starts from. It needs `editor`. +- All emails of a campaign must have the same `editor` and `template_id`. +- Only `create` accepts `editor` and `template_id`. `update` does not. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +campaigns = MailerLite::Campaigns.new + +response = campaigns.create( + name: "Test Campaign", + type: "regular", + emails: [{ + subject: "This is a test campaign", + from_name: "Test Man", + from: "testuser@mailerlite.com", + editor: MailerLite::Campaigns::EDITOR_SIMPLE + }] +) + +email_id = JSON.parse(response.body)['data']['emails'][0]['id'] +``` + ### Update a campaign @@ -599,7 +630,7 @@ campaigns.activity(campaign_id) -These methods edit emails built with the simple editor. To create such an email, create a campaign with `editor: 'simple'` in the email. The ID of the email is in `data.emails[0].id` of the response. +These methods edit emails built with the simple editor. To create such an email, [create a campaign with the simple editor](#create-a-campaign-with-the-simple-editor). The ID of the email is in `data.emails[0].id` of the response. - IDs are strings of digits. You can also give them as integers. An empty ID raises `MailerLite::EmptyIdError`, and an ID that does not contain only digits raises `MailerLite::InvalidIdError`. The SDK sends no request in these cases. - The methods return an `HTTP::Response`, like the other methods. Use `response.code` for the status code, `response.headers` for the headers and `JSON.parse(response.body)` for the body. diff --git a/lib/mailerlite/campaigns/campaigns.rb b/lib/mailerlite/campaigns/campaigns.rb index dfe2e70..a4d5242 100644 --- a/lib/mailerlite/campaigns/campaigns.rb +++ b/lib/mailerlite/campaigns/campaigns.rb @@ -3,6 +3,9 @@ module MailerLite # This is a class for manipulating the Campaigns from MailerLite API. class Campaigns + # The value of `editor` in the emails of `create` for the simple editor. + EDITOR_SIMPLE = 'simple' + attr_reader :client # Inits the `Campaigns` class with the specified `client`. @@ -34,7 +37,10 @@ def get(filter:, limit: nil, page: nil) # @param name [String] Maximum string length of 255 characters # @param language_id [integer] Used to define the language in the unsubscribe template. Must be a valid language id. Defaults to english # @param type [String] Must be one of the following: regular, ab, resend. Type resend is only available for accounts on growing or advanced plans - # @param emails [Array] Must contain 1 email object item + # @param emails [Array] Must contain 1 email object item. The SDK sends each email as it is. An email can also have these keys: + # - `editor`: the only accepted value is `simple`, which selects the simple editor instead of the drag-and-drop builder. It has to be the same across every email in the payload; a mixed array is rejected. Setting it prohibits `emails.*.content`. Use `EDITOR_SIMPLE`. + # - `template_id`: the template the new email starts from. Allowed only when `editor` is `simple`, accepts only a template from the shared gallery, and also has to be the same across every email. + # Then edit the email with `MailerLite::Emails`. Its ID is in `data.emails[0].id` of the response. # @param groups [Array] Must contain valid group ids belonging to the account # @param segments [Array] Must contain valid segment ids belonging to the account. If both groups and segments are provided, only segments are used # @param ab_settings [Array] only if type is ab - All items of the array are required @@ -82,6 +88,7 @@ def create(name:, type:, emails:, language_id: nil, groups: nil, segments: nil, end # Update a new campaign with the specified details. + # Only `create` accepts `editor` and `template_id`. # # @param campaign_id [Integer] the ID of the campaign to update # @param name [String] Maximum string length of 255 characters diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index 888e70f..d0dbdef 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -3,7 +3,7 @@ module MailerLite # This is a class for the emails built with the simple editor. # - # To create such an email, create a campaign with `editor: 'simple'` in the email. + # To create such an email, create a campaign with `editor: MailerLite::Campaigns::EDITOR_SIMPLE` in the email. # The ID of the email is in `data.emails[0].id` of the response. # # IDs are Strings of the digits 0-9. You can also give them as Integers. An empty ID raises diff --git a/spec/campaigns_rspec.rb b/spec/campaigns_rspec.rb index b66d86e..4e2ef92 100644 --- a/spec/campaigns_rspec.rb +++ b/spec/campaigns_rspec.rb @@ -4,6 +4,8 @@ require 'spec_helper' require 'vcr' require 'json' +require 'webmock/rspec' +require_relative 'support/json_fixture' # require "webmock/rspec" # Import the `Campaigns` class @@ -152,4 +154,42 @@ end end end + + describe '#create with the simple editor' do + let(:url) { "#{MAILERLITE_API_URL}/campaigns" } + + def stub_create(body) + stub_request(:post, url) + .with(headers: { 'Authorization' => 'Bearer dummy_token' }) { |req| req.body == body } + .to_return(status: 201, body: load_fixture('campaign_simple_editor').to_json, headers: { 'Content-Type' => 'application/json' }) + end + + it 'has the value of the simple editor' do + expect(MailerLite::Campaigns::EDITOR_SIMPLE).to eq 'simple' + end + + it 'sends editor, template_id and reply_to, and no content' do + stub = stub_create('{"name":"Simple editor campaign","type":"regular","emails":[{"subject":"Hello","from_name":"Sender",' \ + '"from":"sender@example.com","reply_to":"reply@example.com","editor":"simple","template_id":789}]}') + + response = campaigns.create(name: 'Simple editor campaign', type: 'regular', + emails: [{ subject: 'Hello', from_name: 'Sender', from: 'sender@example.com', + reply_to: 'reply@example.com', editor: MailerLite::Campaigns::EDITOR_SIMPLE, template_id: 789 }]) + + expect(stub).to have_been_requested + email = JSON.parse(response.body.to_s)['data']['emails'][0] + expect(email['id']).to eq '123' + expect(email['type']).to eq 'builder_inline_email' + end + + it 'sends the same body as before without editor' do + stub = stub_create('{"name":"HTML campaign","type":"regular","emails":[{"subject":"Hello","from_name":"Sender",' \ + '"from":"sender@example.com","content":"

Hi

"}]}') + + campaigns.create(name: 'HTML campaign', type: 'regular', + emails: [{ subject: 'Hello', from_name: 'Sender', from: 'sender@example.com', content: '

Hi

' }]) + + expect(stub).to have_been_requested + end + end end From 14de4080b5593a93a34f0ee34e9482ff8288a044 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:55:50 +0100 Subject: [PATCH 22/30] feat: add idempotency keys to email writes Add the optional idempotency_key keyword to the 8 email writes. The SDK checks the key and sends it in the Idempotency-Key header. The two validate methods do not accept a key. Add a README section that shows a retry with the same key after a network error. Co-Authored-By: Claude Opus 5.5 --- README.md | 40 +++++++++++++++++ lib/mailerlite/emails/emails.rb | 62 +++++++++++++++++++------- spec/emails_rspec.rb | 78 ++++++++++++++++++++++++++++++++- 3 files changed, 162 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 7ebe202..f540719 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ For more information how to obtain an API key visit the [following link](https:/ - [List the versions of an email](#list-the-versions-of-an-email) - [Save a version of an email](#save-a-version-of-an-email) - [Restore a version of an email](#restore-a-version-of-an-email) + - [Retry a write with an idempotency key](#retry-a-write-with-an-idempotency-key) - [Brand styles](#brand-styles) - [Get the brand styles](#get-the-brand-styles) - [Files](#files) @@ -923,6 +924,45 @@ response = emails.restore_version(email_id: '123456', version_id: '901', etag: ' etag = JSON.parse(response.body)['etag'] ``` +### Retry a write with an idempotency key + + + +If a write fails with a network error, you do not know if the API did the write. Give the write an `idempotency_key`, and send it again with the same key and the same arguments. If the first request was a success, the API returns the stored response and does not do the write two times. Then `response.idempotent_replay?` is `true`. + +- Use a new key for each write. The API keeps a key for 24 hours. +- The key must be 1 to 255 printable ASCII characters, without a space at the start or the end. Otherwise the SDK raises `MailerLite::InvalidIdempotencyKeyError` and sends no request. +- The same key with different arguments returns `422`. If the first request is still running, the API returns `409` without a `code`. +- These methods accept a key: `create_block`, `update_block`, `delete_block`, `move_block`, `update_settings`, `create_template`, `create_version` and `restore_version`. + +```ruby +require "mailerlite-ruby" +require "securerandom" + +# Initialize the class +emails = MailerLite::Emails.new + +args = { + email_id: '123456', + etag: 'etag-from-the-last-response', + type: MailerLite::Emails::BlockType::DIVIDER, + editor_content: {}, + idempotency_key: SecureRandom.uuid +} + +begin + response = emails.create_block(**args) +rescue HTTP::ConnectionError, HTTP::TimeoutError + # Network error: send the write again with the same key and the same arguments. + response = emails.create_block(**args) +end + +error = response.api_error +raise error if error + +puts JSON.parse(response.body)['data']['id'], response.idempotent_replay? +``` + ## Brand styles diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index d0dbdef..d69f795 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -17,6 +17,12 @@ module MailerLite # whole email, so send the writes to one email one after another. If the email changed after you read it, the # API returns 409 and `response.api_error.code` is `VERSION_CONFLICT`. Then `response.api_error.etag` is the # current etag. + # + # Idempotency keys: if a write fails with a network error, you do not know if the API did the write. Give an + # `idempotency_key` to the write, and send it again with the same key and the same arguments. If the first request + # was a success, the API returns the stored response and does not do the write two times. Then + # `response.idempotent_replay?` is true. Use a new key for each write. The API keeps a key for 24 hours. + # The key must be 1 to 255 printable ASCII characters, without a space at the start or the end. class Emails # The error code of a write with an etag that is not the current etag of the email. VERSION_CONFLICT = 'version_conflict' @@ -105,14 +111,17 @@ def get_block(email_id:, block_id:) # @param editor_content [Hash] the content of the block. It can be empty. Its keys are camelCase, for example `textAlign`. # @param placement [Hash, nil] `position` (see `BlockPosition`) and, for `before` and `after`, `block_id`. # Without it, the API puts the block at the end of the email. + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation # @return [HTTP::Response] the response from the API # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid # @raise [MailerLite::EmptyEtagError] if the etag is empty # @raise [TypeError] if an argument has a type that is not valid - def create_block(email_id:, etag:, type:, editor_content:, placement: nil) + # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + def create_block(email_id:, etag:, type:, editor_content:, placement: nil, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') body = block_body(type, editor_content, placement).merge('etag' => Params.etag(etag)) - Request.call(client, :post, "/emails/#{email_id}/blocks", json: body) + Request.call(client, :post, "/emails/#{email_id}/blocks", json: body, idempotency_key: idempotency_key) end # Updates a block of the email. The new content replaces the whole content of the block: the API removes the @@ -122,15 +131,18 @@ def create_block(email_id:, etag:, type:, editor_content:, placement: nil) # @param block_id [String, Integer] the ID of the block # @param etag [String] the etag from the last response for the email # @param editor_content [Hash] the new content of the block. Its keys are camelCase, for example `textAlign`. + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation # @return [HTTP::Response] the response from the API # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid # @raise [MailerLite::EmptyEtagError] if the etag is empty # @raise [TypeError] if an argument has a type that is not valid - def update_block(email_id:, block_id:, etag:, editor_content:) + # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + def update_block(email_id:, block_id:, etag:, editor_content:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') block_id = Params.path_id(block_id, 'block_id') body = { 'editor_content' => Params.require_hash(editor_content, 'editor_content'), 'etag' => Params.etag(etag) } - Request.call(client, :patch, "/emails/#{email_id}/blocks/#{block_id}", json: body) + Request.call(client, :patch, "/emails/#{email_id}/blocks/#{block_id}", json: body, idempotency_key: idempotency_key) end # Deletes a block of the email, and the blocks in it. The response has only the new etag of the email, @@ -139,14 +151,17 @@ def update_block(email_id:, block_id:, etag:, editor_content:) # @param email_id [String, Integer] the ID of the email # @param block_id [String, Integer] the ID of the block # @param etag [String] the etag from the last response for the email + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation # @return [HTTP::Response] the response from the API # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid # @raise [MailerLite::EmptyEtagError] if the etag is empty # @raise [TypeError] if an argument has a type that is not valid - def delete_block(email_id:, block_id:, etag:) + # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + def delete_block(email_id:, block_id:, etag:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') block_id = Params.path_id(block_id, 'block_id') - Request.call(client, :delete, "/emails/#{email_id}/blocks/#{block_id}", json: { 'etag' => Params.etag(etag) }) + Request.call(client, :delete, "/emails/#{email_id}/blocks/#{block_id}", json: { 'etag' => Params.etag(etag) }, idempotency_key: idempotency_key) end # Moves a block of the email. Returns the block, its new place in the email, and the new etag of the email. @@ -155,15 +170,18 @@ def delete_block(email_id:, block_id:, etag:) # @param block_id [String, Integer] the ID of the block to move # @param etag [String] the etag from the last response for the email # @param placement [Hash] `position` (see `BlockPosition`) and, for `before` and `after`, `block_id` + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation # @return [HTTP::Response] the response from the API # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid # @raise [MailerLite::EmptyEtagError] if the etag is empty # @raise [TypeError] if an argument has a type that is not valid - def move_block(email_id:, block_id:, etag:, placement:) + # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + def move_block(email_id:, block_id:, etag:, placement:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') block_id = Params.path_id(block_id, 'block_id') body = { 'placement' => Params.placement(placement), 'etag' => Params.etag(etag) } - Request.call(client, :post, "/emails/#{email_id}/blocks/#{block_id}/move", json: body) + Request.call(client, :post, "/emails/#{email_id}/blocks/#{block_id}/move", json: body, idempotency_key: idempotency_key) end # Validates a block before you insert it. It needs no email and no etag. An invalid block is not an error: @@ -195,15 +213,18 @@ def validate_block(type:, editor_content:, placement: nil) # @param email_id [String, Integer] the ID of the email # @param etag [String] the etag from the last response for the email # @param settings [Hash] the settings to change, without `etag` + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation # @return [HTTP::Response] the response from the API # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if the ID is not valid # @raise [MailerLite::EmptyEtagError] if the etag is empty # @raise [ArgumentError] if the settings contain an `etag` key # @raise [TypeError] if an argument has a type that is not valid - def update_settings(email_id:, etag:, settings:) + # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + def update_settings(email_id:, etag:, settings:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') body = Params.settings(settings).merge('etag' => Params.etag(etag)) - Request.call(client, :patch, "/emails/#{email_id}/settings", json: body) + Request.call(client, :patch, "/emails/#{email_id}/settings", json: body, idempotency_key: idempotency_key) end # Validates a change to the design settings of the email with the rules of `update_settings`, and saves nothing. @@ -225,12 +246,15 @@ def validate_settings(email_id:, settings:) # # @param email_id [String, Integer] the ID of the email # @param name [String] the name of the template + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation # @return [HTTP::Response] the response from the API # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if the ID is not valid # @raise [TypeError] if an argument has a type that is not valid - def create_template(email_id:, name:) + # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + def create_template(email_id:, name:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') - Request.call(client, :post, "/emails/#{email_id}/templates", json: { 'name' => Params.require_string(name, 'name') }) + Request.call(client, :post, "/emails/#{email_id}/templates", json: { 'name' => Params.require_string(name, 'name') }, idempotency_key: idempotency_key) end # Returns the saved versions of the email, newest first. `current` marks the version that the email has now. @@ -250,11 +274,14 @@ def list_versions(email_id, page: nil, limit: nil) # version and 200 for the last version. Both are a success. # # @param email_id [String, Integer] the ID of the email + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation # @return [HTTP::Response] the response from the API # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid - def create_version(email_id) + # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + def create_version(email_id, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') - Request.call(client, :post, "/emails/#{email_id}/versions") + Request.call(client, :post, "/emails/#{email_id}/versions", idempotency_key: idempotency_key) end # Restores the email to a version. Returns the email in the shape of `get`, with the new etag. Before the @@ -263,14 +290,17 @@ def create_version(email_id) # @param email_id [String, Integer] the ID of the email # @param version_id [String, Integer] the ID of the version # @param etag [String] the etag from the last response for the email + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation # @return [HTTP::Response] the response from the API # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid # @raise [MailerLite::EmptyEtagError] if the etag is empty # @raise [TypeError] if an argument has a type that is not valid - def restore_version(email_id:, version_id:, etag:) + # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + def restore_version(email_id:, version_id:, etag:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') version_id = Params.path_id(version_id, 'version_id') - Request.call(client, :post, "/emails/#{email_id}/versions/#{version_id}/restore", json: { 'etag' => Params.etag(etag) }) + Request.call(client, :post, "/emails/#{email_id}/versions/#{version_id}/restore", json: { 'etag' => Params.etag(etag) }, idempotency_key: idempotency_key) end private diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 07f60aa..c1973f6 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -11,12 +11,12 @@ # Stubs one request. The stub matches only the exact raw body, the Authorization header, # and the Idempotency-Key header (or no such header when `key` is nil). - def stub_api(method, path, body: '', response: {}, status: 200, query: nil, key: nil) + def stub_api(method, path, body: '', response: {}, status: 200, query: nil, key: nil, headers: {}) pattern = { headers: { 'Authorization' => 'Bearer dummy_token' } } pattern[:query] = query if query stub_request(method, "#{MAILERLITE_API_URL}#{path}") .with(**pattern) { |req| req.body == body && req.headers['Idempotency-Key'] == key } - .to_return(status: status, body: response.to_json, headers: { 'Content-Type' => 'application/json' }) + .to_return(status: status, body: response.to_json, headers: { 'Content-Type' => 'application/json' }.merge(headers)) end def decoded(response) @@ -510,4 +510,78 @@ def expect_invalid_ids(name) expect(a_request(:any, /.*/)).not_to have_been_made end end + + describe 'idempotency keys' do + # The 8 writes that accept a key: the method, the path, the raw body, and a call with the key. + def writes + [ + [:post, '/emails/123/blocks', '{"type":"divider","editor_content":{},"etag":"42"}', + ->(key) { emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, idempotency_key: key) }], + [:patch, '/emails/123/blocks/57', '{"editor_content":{},"etag":"42"}', + ->(key) { emails.update_block(email_id: '123', block_id: '57', etag: '42', editor_content: {}, idempotency_key: key) }], + [:delete, '/emails/123/blocks/57', '{"etag":"42"}', + ->(key) { emails.delete_block(email_id: '123', block_id: '57', etag: '42', idempotency_key: key) }], + [:post, '/emails/123/blocks/57/move', '{"placement":{"position":"end"},"etag":"42"}', + ->(key) { emails.move_block(email_id: '123', block_id: '57', etag: '42', placement: { position: 'end' }, idempotency_key: key) }], + [:patch, '/emails/123/settings', '{"etag":"42"}', + ->(key) { emails.update_settings(email_id: '123', etag: '42', settings: {}, idempotency_key: key) }], + [:post, '/emails/123/templates', '{"name":"Newsletter"}', + ->(key) { emails.create_template(email_id: '123', name: 'Newsletter', idempotency_key: key) }], + [:post, '/emails/123/versions', '', + ->(key) { emails.create_version('123', idempotency_key: key) }], + [:post, '/emails/123/versions/901/restore', '{"etag":"42"}', + ->(key) { emails.restore_version(email_id: '123', version_id: '901', etag: '42', idempotency_key: key) }] + ] + end + + it 'sends the Idempotency-Key header on each write' do + writes.each do |method, path, body, call| + stub = stub_api(method, path, body: body, key: 'key-1', response: { etag: '43' }) + call.call('key-1') + expect(stub).to have_been_requested + end + end + + it 'sends no Idempotency-Key header without a key' do + writes.each do |method, path, body, call| + stub = stub_api(method, path, body: body, response: { etag: '43' }) + call.call(nil) + expect(stub).to have_been_requested + end + end + + it 'accepts a key with 255 characters' do + stub = stub_api(:post, '/emails/123/versions', key: 'k' * 255, status: 201, response: load_fixture('email_version')) + + emails.create_version('123', idempotency_key: 'k' * 255) + + expect(stub).to have_been_requested + end + + it 'checks the key and sends no request' do + writes.each do |_method, _path, _body, call| + ['', 'k' * 256, "a\nb", "a\tb", 'é', "\x7F", ' k', 'k '].each do |key| + expect { call.call(key) }.to raise_error(MailerLite::InvalidIdempotencyKeyError) + end + expect { call.call(1) }.to raise_error(TypeError, /`idempotency_key`/) + end + expect(a_request(:any, /.*/)).not_to have_been_made + end + + it 'shows a replay of a stored response' do + stub_api(:post, '/emails/123/blocks', body: '{"type":"divider","editor_content":{},"etag":"42"}', key: 'key-1', status: 201, + response: load_fixture('email_block_created'), headers: { 'Idempotent-Replayed' => 'True' }) + + response = emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, idempotency_key: 'key-1') + + expect(response.code).to eq 201 + expect(response.idempotent_replay?).to be(true) + expect(decoded(response)['data']['id']).to eq '58' + end + + it 'does not accept a key on the validate methods' do + expect { emails.validate_block(type: 'divider', editor_content: {}, idempotency_key: 'k') }.to raise_error(ArgumentError, /idempotency_key/) + expect { emails.validate_settings(email_id: '123', settings: {}, idempotency_key: 'k') }.to raise_error(ArgumentError, /idempotency_key/) + end + end end From 3e563301b2ae4c313ea1a139b41ddf1b38d5df1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 14:56:09 +0100 Subject: [PATCH 23/30] chore: bump the version to 2.1.0 Set the version to 2.1.0, because the change adds methods and does not break the current methods. Add the CHANGELOG entry. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++++ lib/mailerlite/version.rb | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d86775..6c9db79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ - `Automations#get_subscriber_activity` takes `filter[:search]`, sent as `filter[search]`. The old `filter[:keyword]` is now sent as `filter[search]` too; the API rejected `filter[keyword]` with a 400 - `AutomationReports#step_subscribers` and `#trigger_subscribers` send an Array `filter[:id]` as one comma-separated value - `Automations#get_subscriber_activity` takes `with_subscribers: true` to include each run's subscriber. It sends `with_subscribers=1` only when true, because the API turns it on for any value +- Add the `Emails` class for the emails built with the simple editor: get an email, its HTML and its blocks, insert, update, delete, move and validate blocks, update and validate the design settings, save a template, and list, save and restore versions +- Add `BrandStyles#get` and `Files#list` +- Add `Campaigns::EDITOR_SIMPLE`, and document `editor` and `template_id` for the emails of `Campaigns#create` +- Add the optional `idempotency_key` argument to the email writes +- The new methods return an `HTTP::Response` with `api_error` (a `MailerLite::ApiError` with `status`, `code`, `etag`, `errors` and `api_message`) and `idempotent_replay?`. They do not raise for an API error ## [2.0.0] - 2024-12-11 - *BREAKING CHANGE* - Please check the README file, dotenv is now optional diff --git a/lib/mailerlite/version.rb b/lib/mailerlite/version.rb index 52dda1e..26a17ce 100644 --- a/lib/mailerlite/version.rb +++ b/lib/mailerlite/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module MailerLite - VERSION = '2.0.0' + VERSION = '2.1.0' end From 83d45f9ecce09d7607ac8aebd4d2c83a1a1ab071 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 16:17:02 +0100 Subject: [PATCH 24/30] fix: check placement block_id only for before and after The API uses block_id only for the before and after positions. For the other positions, it discards the value without a check. Before this change, the SDK checked block_id for each position. A placement such as { position: 'end', block_id: nil } raised EmptyIdError, but the API accepts it. Now Params.placement checks block_id only for before and after. For these positions, a missing block_id raises EmptyIdError. For the other positions, the SDK removes block_id from the body that it sends. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- lib/mailerlite/params.rb | 19 +++++++++++++++---- spec/emails_rspec.rb | 10 ++++++++++ spec/params_rspec.rb | 16 ++++++++++++++++ 4 files changed, 43 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f540719..402d322 100644 --- a/README.md +++ b/README.md @@ -697,7 +697,7 @@ block = JSON.parse(response.body)['data'] -Use the block types in `MailerLite::Emails::BlockType`. `editor_content` can be empty. Without `placement`, the API puts the block at the end of the email. The positions are in `MailerLite::Emails::BlockPosition`. The `BEFORE` and `AFTER` positions also need a `block_id`. +Use the block types in `MailerLite::Emails::BlockType`. `editor_content` can be empty. Without `placement`, the API puts the block at the end of the email. The positions are in `MailerLite::Emails::BlockPosition`. The `BEFORE` and `AFTER` positions also need a `block_id`. For the other positions, the SDK does not send `block_id`. ```ruby require "mailerlite-ruby" @@ -764,7 +764,7 @@ etag = JSON.parse(response.body)['etag'] -The `BEFORE` and `AFTER` positions also need a `block_id`. +The `BEFORE` and `AFTER` positions also need a `block_id`. For the other positions, the SDK does not send `block_id`. ```ruby require "mailerlite-ruby" diff --git a/lib/mailerlite/params.rb b/lib/mailerlite/params.rb index d6e4501..35f53e4 100644 --- a/lib/mailerlite/params.rb +++ b/lib/mailerlite/params.rb @@ -69,14 +69,20 @@ def require_string(value, name) value end - # Returns a copy of the placement of a block with String keys and a valid `block_id`. + # Positions of a block that use `block_id`. + SIBLING_POSITIONS = %w[before after].freeze + + # Returns a copy of the placement of a block with String keys. + # For `before` and `after`, it checks `block_id`. For the other positions, the API discards `block_id` + # without a check, so the copy does not contain it. # # @param placement [Hash] `position` and, for `before` and `after`, `block_id` # @return [Hash] a new Hash. The Hash of the caller does not change. # @raise [TypeError] if the placement is not a Hash, or `block_id` is not a String or an Integer # @raise [ArgumentError] if a key is in the Hash as a Symbol and as a String - # @raise [MailerLite::EmptyIdError] if `block_id` is nil or empty - # @raise [MailerLite::InvalidIdError] if `block_id` does not contain only the digits 0-9 + # @raise [MailerLite::EmptyIdError] if the position is `before` or `after` and `block_id` is nil or empty + # @raise [MailerLite::InvalidIdError] if the position is `before` or `after` and `block_id` does not contain + # only the digits 0-9 def placement(placement) require_hash(placement, 'placement') result = {} @@ -87,7 +93,12 @@ def placement(placement) result[name] = value end - result['block_id'] = path_id(result['block_id'], 'block_id') if result.key?('block_id') + # JSON sends a Symbol position as a String, so compare the String. + if SIBLING_POSITIONS.include?(result['position'].to_s) + result['block_id'] = path_id(result['block_id'], 'block_id') + else + result.delete('block_id') + end result end diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index c1973f6..846a91d 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -294,6 +294,16 @@ def expect_invalid_ids(name) expect(stub).to have_been_requested end + it 'does not send the block_id for the end position' do + stub = stub_api(:post, '/emails/123/blocks/57/move', body: '{"placement":{"position":"end"},"etag":"45"}', + response: load_fixture('email_block_moved')) + + emails.move_block(email_id: '123', block_id: '57', etag: '45', + placement: { position: described_class::BlockPosition::AT_END, block_id: '12' }) + + expect(stub).to have_been_requested + end + it 'checks the arguments and sends no request' do expect_invalid_ids('email_id') { |id| emails.move_block(email_id: id, block_id: '57', etag: '45', placement: { position: 'end' }) } expect_invalid_ids('block_id') { |id| emails.move_block(email_id: '123', block_id: id, etag: '45', placement: { position: 'end' }) } diff --git a/spec/params_rspec.rb b/spec/params_rspec.rb index 2905b9c..ffb4966 100644 --- a/spec/params_rspec.rb +++ b/spec/params_rspec.rb @@ -127,6 +127,22 @@ end end + it 'removes the block_id and does not check it for start and end' do + expect(described_class.placement({ position: 'end', block_id: nil })).to eq('position' => 'end') + expect(described_class.placement({ position: 'start', block_id: '' })).to eq('position' => 'start') + expect(described_class.placement({ 'position' => 'end', 'block_id' => '1/2' })).to eq('position' => 'end') + end + + it 'checks the block_id for before and after' do + expect { described_class.placement({ position: 'after', block_id: nil }) }.to raise_error(MailerLite::EmptyIdError) + expect { described_class.placement({ position: 'before', block_id: '1/2' }) }.to raise_error(MailerLite::InvalidIdError) + end + + it 'raises EmptyIdError for before and after without a block_id' do + expect { described_class.placement({ position: 'after' }) }.to raise_error(MailerLite::EmptyIdError) + expect { described_class.placement({ position: :before }) }.to raise_error(MailerLite::EmptyIdError) + end + it 'raises ArgumentError when a key is there as a Symbol and as a String' do expect { described_class.placement({ block_id: '1', 'block_id' => '2' }) }.to raise_error(ArgumentError, /block_id/) expect { described_class.placement({ position: 'end', 'position' => 'start' }) }.to raise_error(ArgumentError, /position/) From 784619b2a8767f2d63f57a83298809fa43b111f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 16:17:41 +0100 Subject: [PATCH 25/30] docs: show an invalid block in the validate example The validate example used a button with attrs.href and content. The API does not document this shape. Now the example sends a paragraph with textAlign set to sideways, as in the API documentation. A note tells that the block is not valid, so the response has valid: false and errors. The matching spec sends the same block and gets an invalid result. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++++-- spec/emails_rspec.rb | 15 +++++++++------ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 402d322..0d0352b 100644 --- a/README.md +++ b/README.md @@ -788,6 +788,8 @@ etag = JSON.parse(response.body)['etag'] Checks a block before you insert it. It needs no email and no etag. An invalid block is not an error: the response has `valid` set to `false` and the `errors` for each field. +The block in this example is not valid, because `sideways` is not a valid `textAlign`. The response has `valid: false` and `errors`. + ```ruby require "mailerlite-ruby" @@ -795,8 +797,8 @@ require "mailerlite-ruby" emails = MailerLite::Emails.new response = emails.validate_block( - type: MailerLite::Emails::BlockType::BUTTON, - editor_content: { attrs: { href: 'https://example.com' }, content: [{ type: 'text', text: 'Buy now' }] } + type: MailerLite::Emails::BlockType::PARAGRAPH, + editor_content: { attrs: { textAlign: 'sideways' } } ) body = JSON.parse(response.body) diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 846a91d..034fd73 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -320,17 +320,20 @@ def expect_invalid_ids(name) end describe '#validate_block' do - it 'sends the block without an etag and returns a valid result' do - body = '{"type":"button","editor_content":{"attrs":{"href":"https://example.com"}},"placement":{"position":"end"}}' - stub = stub_api(:post, '/emails/blocks/validate', body: body, response: load_fixture('email_block_validation_valid')) + it 'sends the block without an etag and returns the errors of the content' do + body = '{"type":"paragraph","editor_content":{"attrs":{"textAlign":"sideways"}},"placement":{"position":"end"}}' + result = { valid: false, errors: { 'editor_content.attrs.textAlign' => ['The value is not valid.'] }, + schema: { version: '2.73.2', hash: '0f3a9c' } } + stub = stub_api(:post, '/emails/blocks/validate', body: body, response: result) - response = emails.validate_block(type: 'button', editor_content: { attrs: { href: 'https://example.com' } }, + response = emails.validate_block(type: described_class::BlockType::PARAGRAPH, editor_content: { attrs: { textAlign: 'sideways' } }, placement: { position: described_class::BlockPosition::AT_END }) expect(stub).to have_been_requested + expect(response.api_error).to be_nil data = decoded(response) - expect(data['valid']).to be(true) - expect(data['errors']).to eq({}) + expect(data['valid']).to be(false) + expect(data['errors']).to eq('editor_content.attrs.textAlign' => ['The value is not valid.']) expect(data['schema']['version']).to eq '2.73.2' end From a076c5cca26182ce14d1bdbab13c4bc0d892fba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 16:22:17 +0100 Subject: [PATCH 26/30] test: remove the fixture for a valid block validation No spec uses this fixture now. The validate example and its spec show an invalid block. Co-Authored-By: Claude Opus 5.5 --- spec/fixtures/email_block_validation_valid.json | 1 - 1 file changed, 1 deletion(-) delete mode 100644 spec/fixtures/email_block_validation_valid.json diff --git a/spec/fixtures/email_block_validation_valid.json b/spec/fixtures/email_block_validation_valid.json deleted file mode 100644 index b73c417..0000000 --- a/spec/fixtures/email_block_validation_valid.json +++ /dev/null @@ -1 +0,0 @@ -{"valid": true, "errors": {}, "schema": {"version": "2.73.2", "hash": "0f3a9c"}} From 272bc9a00f8b7689f6bfa256bc6585588b69b04f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 17:05:24 +0100 Subject: [PATCH 27/30] docs: say which settings values an empty value unsets An empty string unsets only a brand colour. An empty editor document unsets a footer text. For other colours, sizes, button.border_radius and brand.style, an empty string gives a 422 error. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 ++++- lib/mailerlite/emails/emails.rb | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0d0352b..2e182df 100644 --- a/README.md +++ b/README.md @@ -811,7 +811,10 @@ puts body['errors'] unless body['valid'] Send only the keys to change, in the shape of `settings` in the email. The groups are `brand`, `layout`, `typography`, `button` and `footer`. -- The SDK sends exactly the keys of the Hash. A key that is not in the Hash does not change. An empty string unsets the value. +- The SDK sends exactly the keys of the Hash. A key that is not in the Hash does not change. +- To unset a brand colour, send an empty string. The API stores the value empty, and the email then uses the account value. +- To unset a footer text, send an empty editor document: `{ editor_content: {} }` or `{ editor_content: { content: [] } }`. +- Other colours, sizes, `button.border_radius` and `brand.style` cannot be empty. An empty string gives a `422` error. - Send all style values as strings, for example `'16'` and not `16`. - The API stores each value that you send, also a value that the email inherits from your account. Then the email no longer follows your account for that value. - `footer.social_links` replaces the whole list. Keep the `link_id` of each link to keep its click history. diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index d69f795..1ddd34f 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -202,7 +202,9 @@ def validate_block(type:, editor_content:, placement: nil) # Send only the keys to change, in the shape of `settings` in the response of `get`. The groups are `brand`, # `layout`, `typography`, `button` and `footer`. The SDK sends exactly the keys of the Hash: # - a key that is not in the Hash does not change; - # - an empty String unsets the value; + # - an empty String unsets a brand colour, and the email then uses the account value; + # - an empty editor document, `{ editor_content: {} }` or `{ editor_content: { content: [] } }`, unsets a footer text; + # - other colours, sizes, `button.border_radius` and `brand.style` cannot be empty: an empty String gives a `422` error; # - any other value is the new value. Send style values as Strings, for example '16'. # # The API stores each value that you send, also a value that the email inherits from the account. From 1ea8601d1698bf207c82151f9e0af228dd103537 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 17:19:20 +0100 Subject: [PATCH 28/30] test: set the API token that the WebMock specs expect The new specs expect the header Authorization: Bearer dummy_token, but only the CI workflow set that token. With a different token or with no token, the WebMock stubs did not match. A shared context now sets the token before each example and restores the old value after it. Co-Authored-By: Claude Opus 5.5 --- spec/api_response_rspec.rb | 2 ++ spec/brand_styles_rspec.rb | 2 ++ spec/campaigns_rspec.rb | 2 ++ spec/emails_rspec.rb | 2 ++ spec/files_rspec.rb | 2 ++ spec/request_rspec.rb | 3 +++ spec/support/json_fixture.rb | 16 +++++++++++++++- 7 files changed, 28 insertions(+), 1 deletion(-) diff --git a/spec/api_response_rspec.rb b/spec/api_response_rspec.rb index 389d51a..181a43b 100644 --- a/spec/api_response_rspec.rb +++ b/spec/api_response_rspec.rb @@ -6,6 +6,8 @@ require_relative 'support/json_fixture' RSpec.describe MailerLite::ApiResponse do + include_context 'with the dummy API token' + let(:url) { "#{MAILERLITE_API_URL}/emails/123" } # Returns a real HTTP::Response from WebMock, extended with ApiResponse. diff --git a/spec/brand_styles_rspec.rb b/spec/brand_styles_rspec.rb index 55edafd..d66b58b 100644 --- a/spec/brand_styles_rspec.rb +++ b/spec/brand_styles_rspec.rb @@ -6,6 +6,8 @@ require_relative 'support/json_fixture' RSpec.describe MailerLite::BrandStyles do + include_context 'with the dummy API token' + let(:brand_styles) { described_class.new(client: MailerLite::Client.new) } let(:url) { "#{MAILERLITE_API_URL}/brand-styles" } diff --git a/spec/campaigns_rspec.rb b/spec/campaigns_rspec.rb index 4e2ef92..ffba47b 100644 --- a/spec/campaigns_rspec.rb +++ b/spec/campaigns_rspec.rb @@ -156,6 +156,8 @@ end describe '#create with the simple editor' do + include_context 'with the dummy API token' + let(:url) { "#{MAILERLITE_API_URL}/campaigns" } def stub_create(body) diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 034fd73..26ecdc4 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -6,6 +6,8 @@ require_relative 'support/json_fixture' RSpec.describe MailerLite::Emails do + include_context 'with the dummy API token' + let(:client) { MailerLite::Client.new } let(:emails) { described_class.new(client: client) } diff --git a/spec/files_rspec.rb b/spec/files_rspec.rb index 7d49509..aa200f9 100644 --- a/spec/files_rspec.rb +++ b/spec/files_rspec.rb @@ -6,6 +6,8 @@ require_relative 'support/json_fixture' RSpec.describe MailerLite::Files do + include_context 'with the dummy API token' + let(:files) { described_class.new(client: MailerLite::Client.new) } let(:url) { "#{MAILERLITE_API_URL}/files" } diff --git a/spec/request_rspec.rb b/spec/request_rspec.rb index c8070a7..7ea2300 100644 --- a/spec/request_rspec.rb +++ b/spec/request_rspec.rb @@ -3,8 +3,11 @@ require 'spec_helper' require 'webmock/rspec' require 'json' +require_relative 'support/json_fixture' RSpec.describe MailerLite::Request do + include_context 'with the dummy API token' + let(:client) { MailerLite::Client.new } let(:api) { MAILERLITE_API_URL } diff --git a/spec/support/json_fixture.rb b/spec/support/json_fixture.rb index 236f680..4dc1ae6 100644 --- a/spec/support/json_fixture.rb +++ b/spec/support/json_fixture.rb @@ -15,4 +15,18 @@ def load_fixture(name) end end -RSpec.configure { |config| config.include JsonFixture } if defined?(RSpec) +if defined?(RSpec) + RSpec.configure { |config| config.include JsonFixture } + + # Sets the API token that the WebMock stubs expect, and restores the old value after each example. + # Then the specs do not depend on the token in the shell. + RSpec.shared_context 'with the dummy API token' do + around do |example| + old_token = ENV.fetch('MAILERLITE_API_TOKEN', nil) + ENV['MAILERLITE_API_TOKEN'] = 'dummy_token' + example.run + ensure + ENV['MAILERLITE_API_TOKEN'] = old_token + end + end +end From 7efb549d08089bc2b19f889cb2f142364aac918e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Thu, 29 Oct 2026 18:45:17 +0100 Subject: [PATCH 29/30] chore: remove redundant comments Remove doc comments that repeat the code in the internal Params and Request helpers and in the specs. Remove notes that only explain names to the reviewer. Co-Authored-By: Claude Opus 5.5 --- lib/mailerlite/api_response.rb | 2 +- lib/mailerlite/emails/emails.rb | 2 -- lib/mailerlite/errors.rb | 1 - lib/mailerlite/files/files.rb | 1 - lib/mailerlite/params.rb | 57 ++------------------------------- lib/mailerlite/request.rb | 12 +------ spec/api_response_rspec.rb | 1 - spec/emails_rspec.rb | 6 ++-- spec/support/json_fixture.rb | 7 +--- 9 files changed, 7 insertions(+), 82 deletions(-) diff --git a/lib/mailerlite/api_response.rb b/lib/mailerlite/api_response.rb index 529f93e..8e22c21 100644 --- a/lib/mailerlite/api_response.rb +++ b/lib/mailerlite/api_response.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module MailerLite - # Helpers that the new resources add to each `HTTP::Response` that they return. + # Helpers that `Emails`, `BrandStyles` and `Files` add to each `HTTP::Response` that they return. # # The response is still an `HTTP::Response`. Use `response.code` for the status code, # `response.headers` for the headers and `response.parse` for the decoded body. diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index 1ddd34f..d806a68 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -45,7 +45,6 @@ module BlockType end # Positions of a block, for `placement`. `BEFORE` and `AFTER` also need a `block_id`. - # The names are not `START` and `END`, because `END` is a keyword in Ruby. module BlockPosition AT_START = 'start' AT_END = 'end' @@ -307,7 +306,6 @@ def restore_version(email_id:, version_id:, etag:, idempotency_key: nil) private - # Returns the body to insert or to validate a block. def block_body(type, editor_content, placement) body = { 'type' => Params.require_string(type, 'type'), diff --git a/lib/mailerlite/errors.rb b/lib/mailerlite/errors.rb index 9b49941..7ae33c7 100644 --- a/lib/mailerlite/errors.rb +++ b/lib/mailerlite/errors.rb @@ -42,7 +42,6 @@ def self.from_response(response) code: data['code'], etag: data['etag'], errors: data['errors'], api_message: data['message']) end - # Returns the body as a Hash, or an empty Hash if the body is not a JSON object. def self.parse(body) data = JSON.parse(body) data.is_a?(Hash) ? data : {} diff --git a/lib/mailerlite/files/files.rb b/lib/mailerlite/files/files.rb index 948cd4d..9965682 100644 --- a/lib/mailerlite/files/files.rb +++ b/lib/mailerlite/files/files.rb @@ -2,7 +2,6 @@ module MailerLite # This is a class for the files of the media library from MailerLite API. - # The name is `Files`, not `File`, so it does not hide the `File` class of Ruby. class Files # File types for `filter: { type: ... }`. The API can also return types that are not in this list. module FileType diff --git a/lib/mailerlite/params.rb b/lib/mailerlite/params.rb index 35f53e4..93e9657 100644 --- a/lib/mailerlite/params.rb +++ b/lib/mailerlite/params.rb @@ -12,14 +12,6 @@ module Params # The API accepts 1 to 255 printable ASCII characters. IDEMPOTENCY_KEY_PATTERN = /\A[\x20-\x7E]{1,255}\z/ - # Returns the ID as a String for the URL path. - # - # @param value [String, Integer] the ID - # @param name [String] the name of the argument, for the error message - # @return [String] the ID - # @raise [TypeError] if the ID is not a String or an Integer - # @raise [MailerLite::EmptyIdError] if the ID is nil or empty - # @raise [MailerLite::InvalidIdError] if the ID does not contain only the digits 0-9 def path_id(value, name) raise EmptyIdError, "`#{name}` must not be empty." if value.nil? || value == '' @@ -32,12 +24,6 @@ def path_id(value, name) id end - # Returns the etag for the body of a write. - # - # @param value [String] the etag from the last response for the email - # @return [String] the etag - # @raise [MailerLite::EmptyEtagError] if the etag is nil or empty - # @raise [TypeError] if the etag is not a String def etag(value) raise EmptyEtagError, '`etag` must not be empty.' if value.nil? || value == '' raise TypeError, "`etag` type is not valid. Expected String, got #{value.class}." unless value.is_a?(String) @@ -45,24 +31,12 @@ def etag(value) value end - # Returns the value if it is a Hash. - # - # @param value [Hash] the value to check - # @param name [String] the name of the argument, for the error message - # @return [Hash] the value - # @raise [TypeError] if the value is not a Hash def require_hash(value, name) raise TypeError, "`#{name}` type is not valid. Expected Hash, got #{value.class}." unless value.is_a?(Hash) value end - # Returns the String value if it is a String. - # - # @param value [String] the value to check - # @param name [String] the name of the argument, for the error message - # @return [String] the value - # @raise [TypeError] if the value is not a String def require_string(value, name) raise TypeError, "`#{name}` type is not valid. Expected String, got #{value.class}." unless value.is_a?(String) @@ -72,17 +46,7 @@ def require_string(value, name) # Positions of a block that use `block_id`. SIBLING_POSITIONS = %w[before after].freeze - # Returns a copy of the placement of a block with String keys. - # For `before` and `after`, it checks `block_id`. For the other positions, the API discards `block_id` - # without a check, so the copy does not contain it. - # - # @param placement [Hash] `position` and, for `before` and `after`, `block_id` - # @return [Hash] a new Hash. The Hash of the caller does not change. - # @raise [TypeError] if the placement is not a Hash, or `block_id` is not a String or an Integer - # @raise [ArgumentError] if a key is in the Hash as a Symbol and as a String - # @raise [MailerLite::EmptyIdError] if the position is `before` or `after` and `block_id` is nil or empty - # @raise [MailerLite::InvalidIdError] if the position is `before` or `after` and `block_id` does not contain - # only the digits 0-9 + # For positions other than `before` and `after`, the API discards `block_id` without a check. Drop it. def placement(placement) require_hash(placement, 'placement') result = {} @@ -102,12 +66,6 @@ def placement(placement) result end - # Returns the settings of an email, if they do not contain an etag. - # - # @param settings [Hash] the settings to send - # @return [Hash] the settings - # @raise [TypeError] if the settings are not a Hash - # @raise [ArgumentError] if the settings contain an `etag` key def settings(settings) require_hash(settings, 'settings') # The body has the settings and the etag at the same level. An etag key in the settings can hide the etag argument. @@ -116,12 +74,7 @@ def settings(settings) settings end - # Returns the query parameters for a request. It drops nil values and keeps empty Strings. - # - # @param filter [Hash, nil] the filter values, sent as `filter[key]` - # @param params [Hash] the other query parameters - # @return [Hash] the query parameters - # @raise [TypeError] if the filter is not a Hash + # It drops nil values and keeps empty Strings. def query(filter: nil, **params) query = {} unless filter.nil? @@ -133,12 +86,6 @@ def query(filter: nil, **params) query end - # Returns the headers for an idempotency key. - # - # @param key [String, nil] the idempotency key - # @return [Hash] the `Idempotency-Key` header, or an empty Hash if the key is nil - # @raise [TypeError] if the key is not a String - # @raise [MailerLite::InvalidIdempotencyKeyError] if the key is not valid def idempotency_headers(key) return {} if key.nil? raise TypeError, "`idempotency_key` type is not valid. Expected String, got #{key.class}." unless key.is_a?(String) diff --git a/lib/mailerlite/request.rb b/lib/mailerlite/request.rb index d8aa1a5..3745410 100644 --- a/lib/mailerlite/request.rb +++ b/lib/mailerlite/request.rb @@ -3,21 +3,11 @@ require 'uri' module MailerLite - # Sends the requests of the new resources. + # Sends the requests of `Emails`, `BrandStyles` and `Files`. module Request module_function - # Sends a request and returns the response with the `MailerLite::ApiResponse` methods. # It does not raise for a 4xx or 5xx status. - # - # @param client [MailerLite::Client] the client - # @param method [Symbol] the HTTP method, for example :patch - # @param path [String] the path after the base URL, for example "/emails/123" - # @param json [Hash, nil] the request body. If it is nil, the SDK sends no body. - # @param query [Hash, nil] the query parameters - # @param idempotency_key [String, nil] the value of the `Idempotency-Key` header - # @return [HTTP::Response] the response from the API - # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid def call(client, method, path, json: nil, query: nil, idempotency_key: nil) headers = Params.idempotency_headers(idempotency_key) # Read the constant here, not when the file loads. diff --git a/spec/api_response_rspec.rb b/spec/api_response_rspec.rb index 181a43b..407cb8f 100644 --- a/spec/api_response_rspec.rb +++ b/spec/api_response_rspec.rb @@ -10,7 +10,6 @@ let(:url) { "#{MAILERLITE_API_URL}/emails/123" } - # Returns a real HTTP::Response from WebMock, extended with ApiResponse. def response_for(status:, body: '', headers: {}) stub_request(:get, url).to_return(status: status, body: body, headers: headers) MailerLite::Client.new.http.get(url).extend(described_class) diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 26ecdc4..99eb3f4 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -11,8 +11,7 @@ let(:client) { MailerLite::Client.new } let(:emails) { described_class.new(client: client) } - # Stubs one request. The stub matches only the exact raw body, the Authorization header, - # and the Idempotency-Key header (or no such header when `key` is nil). + # A nil `key` matches only a request without the Idempotency-Key header. def stub_api(method, path, body: '', response: {}, status: 200, query: nil, key: nil, headers: {}) pattern = { headers: { 'Authorization' => 'Bearer dummy_token' } } pattern[:query] = query if query @@ -25,7 +24,6 @@ def decoded(response) JSON.parse(response.body.to_s) end - # Each value raises the error before the request. def invalid_ids [ ['', MailerLite::EmptyIdError], [nil, MailerLite::EmptyIdError], @@ -527,7 +525,7 @@ def expect_invalid_ids(name) end describe 'idempotency keys' do - # The 8 writes that accept a key: the method, the path, the raw body, and a call with the key. + # Each item: the method, the path, the raw body, and a call with the key. def writes [ [:post, '/emails/123/blocks', '{"type":"divider","editor_content":{},"etag":"42"}', diff --git a/spec/support/json_fixture.rb b/spec/support/json_fixture.rb index 4dc1ae6..45b5368 100644 --- a/spec/support/json_fixture.rb +++ b/spec/support/json_fixture.rb @@ -6,10 +6,6 @@ module JsonFixture FIXTURE_DIR = File.expand_path('../fixtures', __dir__) - # Returns the decoded content of `spec/fixtures/.json`. - # - # @param name [String] the file name without `.json` - # @return [Hash] a new Hash for each call, so a spec can change it def load_fixture(name) JSON.parse(File.read(File.join(FIXTURE_DIR, "#{name}.json"))) end @@ -18,8 +14,7 @@ def load_fixture(name) if defined?(RSpec) RSpec.configure { |config| config.include JsonFixture } - # Sets the API token that the WebMock stubs expect, and restores the old value after each example. - # Then the specs do not depend on the token in the shell. + # The specs do not depend on the token in the shell. RSpec.shared_context 'with the dummy API token' do around do |example| old_token = ENV.fetch('MAILERLITE_API_TOKEN', nil) From 9bc0b51be71d6003e5464d1780d25d854785e42f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Martty?= Date: Fri, 30 Oct 2026 11:54:58 +0100 Subject: [PATCH 30/30] refactor: leave value checks to the API The SDK now checks only the IDs in the URL path and the settings Hash of update_settings. It sends the placement, the etag, the block values, the template name and the idempotency key as the caller gives them, and the API answers with its errors. Remove EmptyEtagError and InvalidIdempotencyKeyError. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +- lib/mailerlite/emails/emails.rb | 70 ++++-------- lib/mailerlite/errors.rb | 7 -- lib/mailerlite/params.rb | 46 +------- spec/emails_rspec.rb | 187 +++++++++++++++++++++----------- spec/params_rspec.rb | 101 +---------------- spec/request_rspec.rb | 13 ++- 7 files changed, 166 insertions(+), 267 deletions(-) diff --git a/README.md b/README.md index 2e182df..48a502a 100644 --- a/README.md +++ b/README.md @@ -634,9 +634,10 @@ campaigns.activity(campaign_id) These methods edit emails built with the simple editor. To create such an email, [create a campaign with the simple editor](#create-a-campaign-with-the-simple-editor). The ID of the email is in `data.emails[0].id` of the response. - IDs are strings of digits. You can also give them as integers. An empty ID raises `MailerLite::EmptyIdError`, and an ID that does not contain only digits raises `MailerLite::InvalidIdError`. The SDK sends no request in these cases. +- The SDK checks only the IDs in the URL path, and the settings of `update_settings`: they must be a Hash without an `etag` key. The SDK sends all other values as you give them, and the API checks them. For a value that is not valid, the API returns `422` with the `errors` for each field. - The methods return an `HTTP::Response`, like the other methods. Use `response.code` for the status code, `response.headers` for the headers and `JSON.parse(response.body)` for the body. - The methods do not raise an error for a `4xx` or `5xx` status. `response.api_error` is `nil` for a `2xx` status. For other statuses, it is a `MailerLite::ApiError` with `status`, `code`, `etag`, `api_message` and `errors`. You can raise it. -- Each write needs the etag from the last response for the email, and returns a new etag. The etag covers the whole email, so send the writes to one email one after another. An empty etag raises `MailerLite::EmptyEtagError`, and the SDK sends no request. +- Each write needs the etag from the last response for the email, and returns a new etag. The etag covers the whole email, so send the writes to one email one after another. - If the email changed after you read it, the write returns `409`, and `response.api_error.code` is `MailerLite::Emails::VERSION_CONFLICT`. Then `response.api_error.etag` is the current etag. Get the email again, and then send the write again with the current etag. - The keys of `editor_content` are camelCase, for example `textAlign`. The SDK sends them as you give them. @@ -697,7 +698,7 @@ block = JSON.parse(response.body)['data'] -Use the block types in `MailerLite::Emails::BlockType`. `editor_content` can be empty. Without `placement`, the API puts the block at the end of the email. The positions are in `MailerLite::Emails::BlockPosition`. The `BEFORE` and `AFTER` positions also need a `block_id`. For the other positions, the SDK does not send `block_id`. +Use the block types in `MailerLite::Emails::BlockType`. `editor_content` can be empty. Without `placement`, the API puts the block at the end of the email. The positions are in `MailerLite::Emails::BlockPosition`. The `BEFORE` and `AFTER` positions also need a `block_id`. The SDK sends `placement` as you give it. ```ruby require "mailerlite-ruby" @@ -764,7 +765,7 @@ etag = JSON.parse(response.body)['etag'] -The `BEFORE` and `AFTER` positions also need a `block_id`. For the other positions, the SDK does not send `block_id`. +The `BEFORE` and `AFTER` positions also need a `block_id`. The SDK sends `placement` as you give it. ```ruby require "mailerlite-ruby" @@ -936,7 +937,7 @@ etag = JSON.parse(response.body)['etag'] If a write fails with a network error, you do not know if the API did the write. Give the write an `idempotency_key`, and send it again with the same key and the same arguments. If the first request was a success, the API returns the stored response and does not do the write two times. Then `response.idempotent_replay?` is `true`. - Use a new key for each write. The API keeps a key for 24 hours. -- The key must be 1 to 255 printable ASCII characters, without a space at the start or the end. Otherwise the SDK raises `MailerLite::InvalidIdempotencyKeyError` and sends no request. +- The key must be 1 to 255 printable ASCII characters. The SDK sends the key as you give it. For a key that is not valid, the API returns `400`. - The same key with different arguments returns `422`. If the first request is still running, the API returns `409` without a `code`. - These methods accept a key: `create_block`, `update_block`, `delete_block`, `move_block`, `update_settings`, `create_template`, `create_version` and `restore_version`. diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb index d806a68..483ef2c 100644 --- a/lib/mailerlite/emails/emails.rb +++ b/lib/mailerlite/emails/emails.rb @@ -10,8 +10,8 @@ module MailerLite # `MailerLite::EmptyIdError`, and an ID with other characters raises `MailerLite::InvalidIdError`. # # Each method returns the `HTTP::Response` with the `MailerLite::ApiResponse` methods. The methods do not raise - # for a 4xx or 5xx status: use `response.api_error`. A check of an argument raises before the request, and then - # the SDK sends no request. + # for a 4xx or 5xx status: use `response.api_error`. The SDK checks only the IDs in the URL path, and the settings + # Hash of `update_settings`. It sends all other values as you give them, and the API checks them. # # Each write needs the etag from the last response for the email, and returns a new etag. The etag covers the # whole email, so send the writes to one email one after another. If the email changed after you read it, the @@ -22,7 +22,7 @@ module MailerLite # `idempotency_key` to the write, and send it again with the same key and the same arguments. If the first request # was a success, the API returns the stored response and does not do the write two times. Then # `response.idempotent_replay?` is true. Use a new key for each write. The API keeps a key for 24 hours. - # The key must be 1 to 255 printable ASCII characters, without a space at the start or the end. + # The key must be 1 to 255 printable ASCII characters. For a key that is not valid, the API returns 400. class Emails # The error code of a write with an etag that is not the current etag of the email. VERSION_CONFLICT = 'version_conflict' @@ -113,13 +113,10 @@ def get_block(email_id:, block_id:) # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class # documentation # @return [HTTP::Response] the response from the API - # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid - # @raise [MailerLite::EmptyEtagError] if the etag is empty - # @raise [TypeError] if an argument has a type that is not valid - # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid def create_block(email_id:, etag:, type:, editor_content:, placement: nil, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') - body = block_body(type, editor_content, placement).merge('etag' => Params.etag(etag)) + body = block_body(type, editor_content, placement).merge('etag' => etag) Request.call(client, :post, "/emails/#{email_id}/blocks", json: body, idempotency_key: idempotency_key) end @@ -133,14 +130,11 @@ def create_block(email_id:, etag:, type:, editor_content:, placement: nil, idemp # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class # documentation # @return [HTTP::Response] the response from the API - # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid - # @raise [MailerLite::EmptyEtagError] if the etag is empty - # @raise [TypeError] if an argument has a type that is not valid - # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid def update_block(email_id:, block_id:, etag:, editor_content:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') block_id = Params.path_id(block_id, 'block_id') - body = { 'editor_content' => Params.require_hash(editor_content, 'editor_content'), 'etag' => Params.etag(etag) } + body = { 'editor_content' => editor_content, 'etag' => etag } Request.call(client, :patch, "/emails/#{email_id}/blocks/#{block_id}", json: body, idempotency_key: idempotency_key) end @@ -153,14 +147,11 @@ def update_block(email_id:, block_id:, etag:, editor_content:, idempotency_key: # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class # documentation # @return [HTTP::Response] the response from the API - # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid - # @raise [MailerLite::EmptyEtagError] if the etag is empty - # @raise [TypeError] if an argument has a type that is not valid - # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid def delete_block(email_id:, block_id:, etag:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') block_id = Params.path_id(block_id, 'block_id') - Request.call(client, :delete, "/emails/#{email_id}/blocks/#{block_id}", json: { 'etag' => Params.etag(etag) }, idempotency_key: idempotency_key) + Request.call(client, :delete, "/emails/#{email_id}/blocks/#{block_id}", json: { 'etag' => etag }, idempotency_key: idempotency_key) end # Moves a block of the email. Returns the block, its new place in the email, and the new etag of the email. @@ -172,14 +163,11 @@ def delete_block(email_id:, block_id:, etag:, idempotency_key: nil) # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class # documentation # @return [HTTP::Response] the response from the API - # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid - # @raise [MailerLite::EmptyEtagError] if the etag is empty - # @raise [TypeError] if an argument has a type that is not valid - # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid def move_block(email_id:, block_id:, etag:, placement:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') block_id = Params.path_id(block_id, 'block_id') - body = { 'placement' => Params.placement(placement), 'etag' => Params.etag(etag) } + body = { 'placement' => placement, 'etag' => etag } Request.call(client, :post, "/emails/#{email_id}/blocks/#{block_id}/move", json: body, idempotency_key: idempotency_key) end @@ -190,8 +178,6 @@ def move_block(email_id:, block_id:, etag:, placement:, idempotency_key: nil) # @param editor_content [Hash] the content of the block. Its keys are camelCase, for example `textAlign`. # @param placement [Hash, nil] `position` (see `BlockPosition`) and, for `before` and `after`, `block_id` # @return [HTTP::Response] the response from the API, with `valid`, `errors` and `schema` - # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if the `block_id` of the placement is not valid - # @raise [TypeError] if an argument has a type that is not valid def validate_block(type:, editor_content:, placement: nil) Request.call(client, :post, '/emails/blocks/validate', json: block_body(type, editor_content, placement)) end @@ -217,14 +203,12 @@ def validate_block(type:, editor_content:, placement: nil) # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class # documentation # @return [HTTP::Response] the response from the API - # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if the ID is not valid - # @raise [MailerLite::EmptyEtagError] if the etag is empty + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid # @raise [ArgumentError] if the settings contain an `etag` key - # @raise [TypeError] if an argument has a type that is not valid - # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + # @raise [TypeError] if the settings are not a Hash def update_settings(email_id:, etag:, settings:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') - body = Params.settings(settings).merge('etag' => Params.etag(etag)) + body = Params.settings(settings).merge('etag' => etag) Request.call(client, :patch, "/emails/#{email_id}/settings", json: body, idempotency_key: idempotency_key) end @@ -235,12 +219,10 @@ def update_settings(email_id:, etag:, settings:, idempotency_key: nil) # @param email_id [String, Integer] the ID of the email # @param settings [Hash] the settings that you want to send to `update_settings`, without `etag` # @return [HTTP::Response] the response from the API, with `valid`, `errors` and `schema` - # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if the ID is not valid - # @raise [ArgumentError] if the settings contain an `etag` key - # @raise [TypeError] if an argument has a type that is not valid + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid def validate_settings(email_id:, settings:) email_id = Params.path_id(email_id, 'email_id') - Request.call(client, :post, "/emails/#{email_id}/settings/validate", json: Params.settings(settings)) + Request.call(client, :post, "/emails/#{email_id}/settings/validate", json: settings) end # Saves the email as a new template with the name. The API cannot delete templates. @@ -250,12 +232,10 @@ def validate_settings(email_id:, settings:) # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class # documentation # @return [HTTP::Response] the response from the API - # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if the ID is not valid - # @raise [TypeError] if an argument has a type that is not valid - # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid def create_template(email_id:, name:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') - Request.call(client, :post, "/emails/#{email_id}/templates", json: { 'name' => Params.require_string(name, 'name') }, idempotency_key: idempotency_key) + Request.call(client, :post, "/emails/#{email_id}/templates", json: { 'name' => name }, idempotency_key: idempotency_key) end # Returns the saved versions of the email, newest first. `current` marks the version that the email has now. @@ -279,7 +259,6 @@ def list_versions(email_id, page: nil, limit: nil) # documentation # @return [HTTP::Response] the response from the API # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid - # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid def create_version(email_id, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') Request.call(client, :post, "/emails/#{email_id}/versions", idempotency_key: idempotency_key) @@ -294,24 +273,21 @@ def create_version(email_id, idempotency_key: nil) # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class # documentation # @return [HTTP::Response] the response from the API - # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError] if an ID is not valid - # @raise [MailerLite::EmptyEtagError] if the etag is empty - # @raise [TypeError] if an argument has a type that is not valid - # @raise [MailerLite::InvalidIdempotencyKeyError] if the idempotency key is not valid + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid def restore_version(email_id:, version_id:, etag:, idempotency_key: nil) email_id = Params.path_id(email_id, 'email_id') version_id = Params.path_id(version_id, 'version_id') - Request.call(client, :post, "/emails/#{email_id}/versions/#{version_id}/restore", json: { 'etag' => Params.etag(etag) }, idempotency_key: idempotency_key) + Request.call(client, :post, "/emails/#{email_id}/versions/#{version_id}/restore", json: { 'etag' => etag }, idempotency_key: idempotency_key) end private def block_body(type, editor_content, placement) body = { - 'type' => Params.require_string(type, 'type'), - 'editor_content' => Params.require_hash(editor_content, 'editor_content') + 'type' => type, + 'editor_content' => editor_content } - body['placement'] = Params.placement(placement) unless placement.nil? + body['placement'] = placement unless placement.nil? body end end diff --git a/lib/mailerlite/errors.rb b/lib/mailerlite/errors.rb index 7ae33c7..9ea949a 100644 --- a/lib/mailerlite/errors.rb +++ b/lib/mailerlite/errors.rb @@ -85,11 +85,4 @@ class EmptyIdError < ArgumentError; end # An ID for the URL path does not contain only the digits 0-9. The SDK sends no request. class InvalidIdError < ArgumentError; end - - # The etag of a write is empty. The SDK sends no request. - class EmptyEtagError < ArgumentError; end - - # The idempotency key is empty, longer than 255 characters, contains a character that is not printable ASCII, - # or starts or ends with a space. The SDK sends no request. - class InvalidIdempotencyKeyError < ArgumentError; end end diff --git a/lib/mailerlite/params.rb b/lib/mailerlite/params.rb index 93e9657..538f1a7 100644 --- a/lib/mailerlite/params.rb +++ b/lib/mailerlite/params.rb @@ -2,6 +2,7 @@ module MailerLite # Checks and helpers for the request parameters of the resources. + # The SDK checks only the IDs in the URL path and the values that its code reads. The API checks all other values. # Each check raises before the request, so the SDK sends no request when a value is not valid. module Params module_function @@ -9,8 +10,6 @@ module Params # Use \A and \z: `$` and \Z also match before a final new line. # Use [0-9]: [[:digit:]] also matches digits that are not ASCII. ID_PATTERN = /\A[0-9]+\z/ - # The API accepts 1 to 255 printable ASCII characters. - IDEMPOTENCY_KEY_PATTERN = /\A[\x20-\x7E]{1,255}\z/ def path_id(value, name) raise EmptyIdError, "`#{name}` must not be empty." if value.nil? || value == '' @@ -24,48 +23,12 @@ def path_id(value, name) id end - def etag(value) - raise EmptyEtagError, '`etag` must not be empty.' if value.nil? || value == '' - raise TypeError, "`etag` type is not valid. Expected String, got #{value.class}." unless value.is_a?(String) - - value - end - def require_hash(value, name) raise TypeError, "`#{name}` type is not valid. Expected Hash, got #{value.class}." unless value.is_a?(Hash) value end - def require_string(value, name) - raise TypeError, "`#{name}` type is not valid. Expected String, got #{value.class}." unless value.is_a?(String) - - value - end - - # Positions of a block that use `block_id`. - SIBLING_POSITIONS = %w[before after].freeze - - # For positions other than `before` and `after`, the API discards `block_id` without a check. Drop it. - def placement(placement) - require_hash(placement, 'placement') - result = {} - placement.each do |key, value| - name = key.to_s - # {block_id: 1, 'block_id' => 2} has two keys, but JSON can send only one of them. - raise ArgumentError, "`placement` contains the key `#{name}` two times." if result.key?(name) - - result[name] = value - end - # JSON sends a Symbol position as a String, so compare the String. - if SIBLING_POSITIONS.include?(result['position'].to_s) - result['block_id'] = path_id(result['block_id'], 'block_id') - else - result.delete('block_id') - end - result - end - def settings(settings) require_hash(settings, 'settings') # The body has the settings and the etag at the same level. An etag key in the settings can hide the etag argument. @@ -88,13 +51,6 @@ def query(filter: nil, **params) def idempotency_headers(key) return {} if key.nil? - raise TypeError, "`idempotency_key` type is not valid. Expected String, got #{key.class}." unless key.is_a?(String) - - # HTTP removes a space at the start and at the end of a header value. Then the API gets a different key. - unless key.valid_encoding? && key.ascii_only? && key.match?(IDEMPOTENCY_KEY_PATTERN) && key == key.strip - raise InvalidIdempotencyKeyError, - '`idempotency_key` must be 1 to 255 printable ASCII characters, without a space at the start or the end.' - end { 'Idempotency-Key' => key } end diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb index 99eb3f4..3a08f0d 100644 --- a/spec/emails_rspec.rb +++ b/spec/emails_rspec.rb @@ -156,7 +156,7 @@ def expect_invalid_ids(name) it 'inserts the block with the placement and the etag' do body = '{"type":"paragraph","editor_content":{"attrs":{"textAlign":"center"},"content":[{"type":"text","text":"Hi"}]},' \ - '"placement":{"position":"after","block_id":"57"},"etag":"42"}' + '"placement":{"position":"after","block_id":57},"etag":"42"}' stub = stub_api(:post, '/emails/123/blocks', body: body, status: 201, response: load_fixture('email_block_created')) placement = { position: described_class::BlockPosition::AFTER, block_id: 57 } @@ -203,25 +203,33 @@ def expect_invalid_ids(name) expect(response.api_error.errors).to eq('type' => ['The selected type is invalid.']) end - it 'checks the email ID and the block_id of the placement, and sends no request' do + it 'checks the email ID and sends no request' do expect_invalid_ids('email_id') { |id| emails.create_block(email_id: id, etag: '42', type: 'divider', editor_content: {}) } - expect_invalid_ids('block_id') do |id| - emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, placement: { position: 'after', block_id: id }) - end - expect_invalid_ids('block_id') do |id| - emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, placement: { 'position' => 'after', 'block_id' => id }) - end end - it 'checks the etag and the types, and sends no request' do - expect { emails.create_block(email_id: '123', etag: '', type: 'divider', editor_content: {}) }.to raise_error(MailerLite::EmptyEtagError) - expect { emails.create_block(email_id: '123', etag: nil, type: 'divider', editor_content: {}) }.to raise_error(MailerLite::EmptyEtagError) - expect { emails.create_block(email_id: '123', etag: 42, type: 'divider', editor_content: {}) }.to raise_error(TypeError, /`etag`/) - expect { emails.create_block(email_id: '123', etag: '42', type: 1, editor_content: {}) }.to raise_error(TypeError, /`type`/) - expect { emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: nil) }.to raise_error(TypeError, /`editor_content`/) - expect { emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, placement: 'end') } - .to raise_error(TypeError, /`placement`/) - expect(a_request(:any, /.*/)).not_to have_been_made + it 'sends an after placement without a block_id as given, and returns the API error' do + stub = stub_api(:post, '/emails/123/blocks', body: '{"type":"divider","editor_content":{},"placement":{"position":"after"},"etag":"42"}', + status: 422, response: { message: 'Invalid.', errors: { 'placement.block_id' => ['Required.'] } }) + + response = emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, placement: { position: 'after' }) + + expect(stub).to have_been_requested + expect(response.api_error.errors).to eq('placement.block_id' => ['Required.']) + end + + it 'sends the values that the API checks, and returns the API error' do + calls = { + '{"type":"divider","editor_content":{},"etag":""}' => -> { emails.create_block(email_id: '123', etag: '', type: 'divider', editor_content: {}) }, + '{"type":"paragraph","editor_content":{},"etag":"42"}' => -> { emails.create_block(email_id: '123', etag: '42', type: :paragraph, editor_content: {}) }, + '{"type":"divider","editor_content":null,"etag":"42"}' => -> { emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: nil) }, + '{"type":"divider","editor_content":{},"placement":"end","etag":"42"}' => + -> { emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, placement: 'end') } + } + calls.each do |body, call| + stub = stub_api(:post, '/emails/123/blocks', body: body, status: 422, response: { message: 'Invalid.' }) + expect(call.call.api_error.status).to eq 422 + expect(stub).to have_been_requested + end end end @@ -240,13 +248,18 @@ def expect_invalid_ids(name) expect(data['data']['placement']).to eq('after' => '56', 'before' => '58') end - it 'checks the arguments and sends no request' do + it 'checks the IDs and sends no request' do expect_invalid_ids('email_id') { |id| emails.update_block(email_id: id, block_id: '57', etag: '43', editor_content: {}) } expect_invalid_ids('block_id') { |id| emails.update_block(email_id: '123', block_id: id, etag: '43', editor_content: {}) } - expect { emails.update_block(email_id: '123', block_id: '57', etag: '', editor_content: {}) }.to raise_error(MailerLite::EmptyEtagError) - expect { emails.update_block(email_id: '123', block_id: '57', etag: '43', editor_content: []) } - .to raise_error(TypeError, /`editor_content`/) - expect(a_request(:any, /.*/)).not_to have_been_made + end + + it 'sends an empty etag and content that is not a Hash, and returns the API error' do + stub = stub_api(:patch, '/emails/123/blocks/57', body: '{"editor_content":[],"etag":""}', status: 422, response: { message: 'Invalid.' }) + + response = emails.update_block(email_id: '123', block_id: '57', etag: '', editor_content: []) + + expect(stub).to have_been_requested + expect(response.api_error.status).to eq 422 end end @@ -261,17 +274,23 @@ def expect_invalid_ids(name) expect(decoded(response)).to eq('etag' => '45') end - it 'checks the arguments and sends no request' do + it 'checks the IDs and sends no request' do expect_invalid_ids('email_id') { |id| emails.delete_block(email_id: id, block_id: '57', etag: '44') } expect_invalid_ids('block_id') { |id| emails.delete_block(email_id: '123', block_id: id, etag: '44') } - expect { emails.delete_block(email_id: '123', block_id: '57', etag: nil) }.to raise_error(MailerLite::EmptyEtagError) - expect(a_request(:any, /.*/)).not_to have_been_made + end + + it 'sends a nil etag as null' do + stub = stub_api(:delete, '/emails/123/blocks/57', body: '{"etag":null}', status: 422, response: { message: 'Invalid.' }) + + emails.delete_block(email_id: '123', block_id: '57', etag: nil) + + expect(stub).to have_been_requested end end describe '#move_block' do it 'sends the placement and the etag' do - stub = stub_api(:post, '/emails/123/blocks/57/move', body: '{"placement":{"position":"before","block_id":"1"},"etag":"45"}', + stub = stub_api(:post, '/emails/123/blocks/57/move', body: '{"placement":{"position":"before","block_id":1},"etag":"45"}', response: load_fixture('email_block_moved')) response = emails.move_block(email_id: '123', block_id: '57', etag: '45', @@ -294,28 +313,35 @@ def expect_invalid_ids(name) expect(stub).to have_been_requested end - it 'does not send the block_id for the end position' do - stub = stub_api(:post, '/emails/123/blocks/57/move', body: '{"placement":{"position":"end"},"etag":"45"}', + it 'sends the block_id for the start and end positions' do + stub = stub_api(:post, '/emails/123/blocks/57/move', body: '{"placement":{"position":"start","block_id":"12"},"etag":"45"}', response: load_fixture('email_block_moved')) emails.move_block(email_id: '123', block_id: '57', etag: '45', - placement: { position: described_class::BlockPosition::AT_END, block_id: '12' }) + placement: { position: described_class::BlockPosition::AT_START, block_id: '12' }) expect(stub).to have_been_requested end - it 'checks the arguments and sends no request' do + it 'checks the IDs in the URL and sends no request' do expect_invalid_ids('email_id') { |id| emails.move_block(email_id: id, block_id: '57', etag: '45', placement: { position: 'end' }) } expect_invalid_ids('block_id') { |id| emails.move_block(email_id: '123', block_id: id, etag: '45', placement: { position: 'end' }) } - expect_invalid_ids('block_id') do |id| - emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: { position: 'after', block_id: id }) - end - expect_invalid_ids('block_id') do |id| - emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: { 'position' => 'after', 'block_id' => id }) + end + + it 'sends the placement and the etag as given, and returns the API error' do + calls = { + '{"placement":{"position":"after","block_id":"1/2"},"etag":"45"}' => + -> { emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: { position: 'after', block_id: '1/2' }) }, + '{"placement":{"position":"before"},"etag":"45"}' => + -> { emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: { 'position' => 'before' }) }, + '{"placement":null,"etag":"45"}' => -> { emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: nil) }, + '{"placement":{"position":"end"},"etag":""}' => -> { emails.move_block(email_id: '123', block_id: '57', etag: '', placement: { position: 'end' }) } + } + calls.each do |body, call| + stub = stub_api(:post, '/emails/123/blocks/57/move', body: body, status: 422, response: { message: 'Invalid.' }) + expect(call.call.api_error.status).to eq 422 + expect(stub).to have_been_requested end - expect { emails.move_block(email_id: '123', block_id: '57', etag: '', placement: { position: 'end' }) }.to raise_error(MailerLite::EmptyEtagError) - expect { emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: nil) }.to raise_error(TypeError, /`placement`/) - expect(a_request(:any, /.*/)).not_to have_been_made end end @@ -350,11 +376,20 @@ def expect_invalid_ids(name) expect(data['errors']).to eq('type' => ['The selected type is invalid.']) end - it 'checks the arguments and sends no request' do - expect_invalid_ids('block_id') { |id| emails.validate_block(type: 'divider', editor_content: {}, placement: { position: 'after', block_id: id }) } - expect { emails.validate_block(type: nil, editor_content: {}) }.to raise_error(TypeError, /`type`/) - expect { emails.validate_block(type: 'divider', editor_content: 'x') }.to raise_error(TypeError, /`editor_content`/) - expect(a_request(:any, /.*/)).not_to have_been_made + it 'sends a block that is not valid, and returns the result of the API' do + calls = { + '{"type":"divider","editor_content":{},"placement":{"position":"after"}}' => + -> { emails.validate_block(type: 'divider', editor_content: {}, placement: { position: 'after' }) }, + '{"type":"divider","editor_content":{},"placement":{"position":"before","block_id":"x"}}' => + -> { emails.validate_block(type: 'divider', editor_content: {}, placement: { position: 'before', block_id: 'x' }) }, + '{"type":null,"editor_content":{}}' => -> { emails.validate_block(type: nil, editor_content: {}) }, + '{"type":"divider","editor_content":"x"}' => -> { emails.validate_block(type: 'divider', editor_content: 'x') } + } + calls.each do |body, call| + stub = stub_api(:post, '/emails/blocks/validate', body: body, response: load_fixture('email_block_validation_invalid')) + expect(decoded(call.call)['valid']).to be(false) + expect(stub).to have_been_requested + end end end @@ -396,12 +431,20 @@ def expect_invalid_ids(name) it 'checks the arguments and sends no request' do expect_invalid_ids('email_id') { |id| emails.update_settings(email_id: id, etag: '46', settings: {}) } - expect { emails.update_settings(email_id: '123', etag: '', settings: {}) }.to raise_error(MailerLite::EmptyEtagError) expect { emails.update_settings(email_id: '123', etag: '46', settings: nil) }.to raise_error(TypeError, /`settings`/) expect { emails.update_settings(email_id: '123', etag: '46', settings: { etag: '1' }) }.to raise_error(ArgumentError, /etag/) expect { emails.update_settings(email_id: '123', etag: '46', settings: { 'etag' => '1' }) }.to raise_error(ArgumentError, /etag/) expect(a_request(:any, /.*/)).not_to have_been_made end + + it 'sends an empty etag, and returns the API error' do + stub = stub_api(:patch, '/emails/123/settings', body: '{"etag":""}', status: 422, response: { message: 'Invalid.' }) + + response = emails.update_settings(email_id: '123', etag: '', settings: {}) + + expect(stub).to have_been_requested + expect(response.api_error.status).to eq 422 + end end describe '#validate_settings' do @@ -418,12 +461,20 @@ def expect_invalid_ids(name) expect(data['rejected']['message']).to eq 'Some attributes were rejected.' end - it 'checks the arguments and sends no request' do + it 'checks the email ID and sends no request' do expect_invalid_ids('email_id') { |id| emails.validate_settings(email_id: id, settings: {}) } - expect { emails.validate_settings(email_id: '123', settings: 'x') }.to raise_error(TypeError, /`settings`/) - expect { emails.validate_settings(email_id: '123', settings: { etag: '1' }) }.to raise_error(ArgumentError, /etag/) - expect { emails.validate_settings(email_id: '123', settings: { 'etag' => '1' }) }.to raise_error(ArgumentError, /etag/) - expect(a_request(:any, /.*/)).not_to have_been_made + end + + it 'sends the settings as given, also with an etag key' do + calls = { + '{"etag":"1"}' => -> { emails.validate_settings(email_id: '123', settings: { etag: '1' }) }, + '"x"' => -> { emails.validate_settings(email_id: '123', settings: 'x') } + } + calls.each do |body, call| + stub = stub_api(:post, '/emails/123/settings/validate', body: body, response: load_fixture('email_settings_validation')) + expect(decoded(call.call)['valid']).to be(false) + expect(stub).to have_been_requested + end end end @@ -440,11 +491,16 @@ def expect_invalid_ids(name) expect(data).not_to have_key('etag') end - it 'checks the arguments and sends no request' do + it 'checks the email ID and sends no request' do expect_invalid_ids('email_id') { |id| emails.create_template(email_id: id, name: 'Newsletter') } - expect { emails.create_template(email_id: '123', name: nil) }.to raise_error(TypeError, /`name`/) - expect { emails.create_template(email_id: '123', name: 1) }.to raise_error(TypeError, /`name`/) - expect(a_request(:any, /.*/)).not_to have_been_made + end + + it 'sends a name that is not a String, and returns the API error' do + { '{"name":null}' => nil, '{"name":1}' => 1 }.each do |body, name| + stub = stub_api(:post, '/emails/123/templates', body: body, status: 422, response: { message: 'Invalid.' }) + expect(emails.create_template(email_id: '123', name: name).api_error.status).to eq 422 + expect(stub).to have_been_requested + end end end @@ -516,11 +572,18 @@ def expect_invalid_ids(name) expect(data['data']['blocks'].size).to eq 2 end - it 'checks the arguments and sends no request' do + it 'checks the IDs and sends no request' do expect_invalid_ids('email_id') { |id| emails.restore_version(email_id: id, version_id: '901', etag: '47') } expect_invalid_ids('version_id') { |id| emails.restore_version(email_id: '123', version_id: id, etag: '47') } - expect { emails.restore_version(email_id: '123', version_id: '901', etag: '') }.to raise_error(MailerLite::EmptyEtagError) - expect(a_request(:any, /.*/)).not_to have_been_made + end + + it 'sends an empty etag, and returns the API error' do + stub = stub_api(:post, '/emails/123/versions/901/restore', body: '{"etag":""}', status: 422, response: { message: 'Invalid.' }) + + response = emails.restore_version(email_id: '123', version_id: '901', etag: '') + + expect(stub).to have_been_requested + expect(response.api_error.status).to eq 422 end end @@ -571,14 +634,14 @@ def writes expect(stub).to have_been_requested end - it 'checks the key and sends no request' do - writes.each do |_method, _path, _body, call| - ['', 'k' * 256, "a\nb", "a\tb", 'é', "\x7F", ' k', 'k '].each do |key| - expect { call.call(key) }.to raise_error(MailerLite::InvalidIdempotencyKeyError) + it 'sends the key as given, and returns the API error' do + writes.each do |method, path, body, call| + ['', ' k', 'k ', 'k' * 256].each do |key| + stub = stub_api(method, path, body: body, key: key, status: 400, response: { message: 'The idempotency key is not valid.' }) + expect(call.call(key).api_error.status).to eq 400 + expect(stub).to have_been_requested end - expect { call.call(1) }.to raise_error(TypeError, /`idempotency_key`/) end - expect(a_request(:any, /.*/)).not_to have_been_made end it 'shows a replay of a stored response' do diff --git a/spec/params_rspec.rb b/spec/params_rspec.rb index ffb4966..5f4c3be 100644 --- a/spec/params_rspec.rb +++ b/spec/params_rspec.rb @@ -7,8 +7,6 @@ it 'makes the client-side errors subclasses of ArgumentError' do expect(MailerLite::EmptyIdError.ancestors).to include(ArgumentError) expect(MailerLite::InvalidIdError.ancestors).to include(ArgumentError) - expect(MailerLite::EmptyEtagError.ancestors).to include(ArgumentError) - expect(MailerLite::InvalidIdempotencyKeyError.ancestors).to include(ArgumentError) end it 'has a base error class for the SDK' do @@ -56,21 +54,6 @@ end end - describe '.etag' do - it 'returns the etag' do - expect(described_class.etag('42')).to eq '42' - end - - it 'raises EmptyEtagError for an empty String and for nil' do - expect { described_class.etag('') }.to raise_error(MailerLite::EmptyEtagError) - expect { described_class.etag(nil) }.to raise_error(MailerLite::EmptyEtagError) - end - - it 'raises TypeError for a value that is not a String' do - expect { described_class.etag(42) }.to raise_error(TypeError, /`etag`/) - end - end - describe '.require_hash' do it 'returns the Hash' do value = { 'a' => 1 } @@ -84,75 +67,6 @@ end end - describe '.require_string' do - it 'returns the String' do - expect(described_class.require_string('paragraph', 'type')).to eq 'paragraph' - end - - [nil, 1, :paragraph].each do |value| - it "raises TypeError for #{value.inspect}" do - expect { described_class.require_string(value, 'type') }.to raise_error(TypeError, /`type`/) - end - end - end - - describe '.placement' do - it 'returns the placement with String keys' do - expect(described_class.placement({ position: 'end' })).to eq('position' => 'end') - end - - it 'sends an Integer block_id as a String' do - expect(described_class.placement({ position: 'after', block_id: 57 })) - .to eq('position' => 'after', 'block_id' => '57') - end - - it 'accepts a String key for block_id' do - expect(described_class.placement({ 'position' => 'before', 'block_id' => '57' })) - .to eq('position' => 'before', 'block_id' => '57') - end - - it 'does not change the Hash of the caller' do - placement = { position: 'after', block_id: 57 } - described_class.placement(placement) - expect(placement).to eq(position: 'after', block_id: 57) - end - - [:block_id, 'block_id'].each do |key| - it "checks the block_id with a #{key.class} key" do - expect { described_class.placement({ position: 'after', key => '' }) }.to raise_error(MailerLite::EmptyIdError) - expect { described_class.placement({ position: 'after', key => nil }) }.to raise_error(MailerLite::EmptyIdError) - expect { described_class.placement({ position: 'after', key => '1/2' }) }.to raise_error(MailerLite::InvalidIdError) - expect { described_class.placement({ position: 'after', key => "1\n" }) }.to raise_error(MailerLite::InvalidIdError) - expect { described_class.placement({ position: 'after', key => true }) }.to raise_error(TypeError) - end - end - - it 'removes the block_id and does not check it for start and end' do - expect(described_class.placement({ position: 'end', block_id: nil })).to eq('position' => 'end') - expect(described_class.placement({ position: 'start', block_id: '' })).to eq('position' => 'start') - expect(described_class.placement({ 'position' => 'end', 'block_id' => '1/2' })).to eq('position' => 'end') - end - - it 'checks the block_id for before and after' do - expect { described_class.placement({ position: 'after', block_id: nil }) }.to raise_error(MailerLite::EmptyIdError) - expect { described_class.placement({ position: 'before', block_id: '1/2' }) }.to raise_error(MailerLite::InvalidIdError) - end - - it 'raises EmptyIdError for before and after without a block_id' do - expect { described_class.placement({ position: 'after' }) }.to raise_error(MailerLite::EmptyIdError) - expect { described_class.placement({ position: :before }) }.to raise_error(MailerLite::EmptyIdError) - end - - it 'raises ArgumentError when a key is there as a Symbol and as a String' do - expect { described_class.placement({ block_id: '1', 'block_id' => '2' }) }.to raise_error(ArgumentError, /block_id/) - expect { described_class.placement({ position: 'end', 'position' => 'start' }) }.to raise_error(ArgumentError, /position/) - end - - it 'raises TypeError for a placement that is not a Hash' do - expect { described_class.placement('end') }.to raise_error(TypeError, /`placement`/) - end - end - describe '.settings' do it 'returns the settings' do settings = { brand: { mode: 'account' } } @@ -203,19 +117,10 @@ expect(described_class.idempotency_headers('key-1')).to eq('Idempotency-Key' => 'key-1') end - it 'accepts a key with 255 characters and a space in the middle' do - expect(described_class.idempotency_headers('a' * 255)).to eq('Idempotency-Key' => 'a' * 255) - expect(described_class.idempotency_headers('a b')).to eq('Idempotency-Key' => 'a b') - end - - ['', 'a' * 256, "a\nb", "a\tb", 'é', "\x7F", ' k', 'k ', (+"k\xFF").force_encoding('UTF-8')].each do |key| - it "raises InvalidIdempotencyKeyError for #{key.inspect[0, 20]}" do - expect { described_class.idempotency_headers(key) }.to raise_error(MailerLite::InvalidIdempotencyKeyError) + ['', 'a' * 256, 'é', ' k', 'k ', 1].each do |key| + it "returns the header with the key as given for #{key.inspect[0, 20]}" do + expect(described_class.idempotency_headers(key)).to eq('Idempotency-Key' => key) end end - - it 'raises TypeError for a key that is not a String' do - expect { described_class.idempotency_headers(1) }.to raise_error(TypeError, /`idempotency_key`/) - end end end diff --git a/spec/request_rspec.rb b/spec/request_rspec.rb index 7ea2300..ce6c0f2 100644 --- a/spec/request_rspec.rb +++ b/spec/request_rspec.rb @@ -93,10 +93,15 @@ def capture_raw_uris expect(stub).to have_been_requested end - it 'sends no request for an invalid key' do - expect { described_class.call(client, :post, '/emails/1/versions', idempotency_key: 'a b ') } - .to raise_error(MailerLite::InvalidIdempotencyKeyError) - expect(a_request(:any, /.*/)).not_to have_been_made + it 'sends a key with a space at the end as given' do + stub = stub_request(:post, "#{api}/emails/1/versions") + .with { |req| req.headers['Idempotency-Key'] == 'a b ' } + .to_return(status: 400, body: '{"message":"The idempotency key is not valid."}') + + response = described_class.call(client, :post, '/emails/1/versions', idempotency_key: 'a b ') + + expect(stub).to have_been_requested + expect(response.api_error.status).to eq 400 end it 'returns the HTTP::Response with the ApiResponse methods' do