Skip to content

Suppressions Api #52

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Suppressions Api #52

wants to merge 2 commits into from

Conversation

sarco3t
Copy link
Contributor

@sarco3t sarco3t commented Jun 30, 2025

Motivation

Support new functionality (Suppressions API)
https://help.mailtrap.io/article/95-suppressions-list

Changes

  • Added new Mailtrap::SuppressionsAPI entity for interactions with Suppressions API
    • delete
    • list
  • query params handling in Mailtrap::Client#get
  • Mailtrap::Suppression DTO
  • Added new tests
  • Added examples

How to test

rspec

or set yout api key and account id

suppressions = Mailtrap::SuppressionsAPI.new(ENV.fetch('MAILTRAP_ACCOUNT_ID', 1_111_111), client)

# List all suppressions
puts 'Listing all suppressions...'
list = suppressions.list
puts list

# delete suppression
suppressions.delete('123e4567-e89b-12d3-a456-426614174000')

Summary by CodeRabbit

  • New Features

    • Introduced support for managing email suppressions, including listing and deleting suppressions via the API.
    • Added a data model to represent suppression records.
    • Provided an example script demonstrating usage of the suppressions API.
  • Refactor

    • Refactored the email templates API to share common logic with the new suppressions API.
  • Bug Fixes

    • Enabled GET requests to include URL query parameters for more flexible API interactions.
  • Tests

    • Added comprehensive tests for suppression management, including success and error scenarios.
    • Introduced new test fixtures and a custom matcher for object identity checks.

Copy link

coderabbitai bot commented Jun 30, 2025

Warning

Rate limit exceeded

@sarco3t has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 35 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between ea1634f and 93ace20.

📒 Files selected for processing (1)
  • lib/mailtrap/suppressions_api.rb (1 hunks)

Walkthrough

This update introduces a new Suppressions API to the Mailtrap Ruby client. It adds the SuppressionsAPI class and a corresponding Suppression data structure, updates the client to support query parameters, and refactors shared API logic into a new BaseAPI class. Comprehensive RSpec tests and usage examples are included.

Changes

File(s) Change Summary
lib/mailtrap/base_api.rb, lib/mailtrap/suppressions_api.rb, lib/mailtrap/suppression.rb Added BaseAPI superclass, SuppressionsAPI for managing suppressions, and Suppression DTO struct.
lib/mailtrap/email_templates_api.rb Refactored to inherit from BaseAPI, removed redundant methods, and reused shared entity/validation logic.
lib/mailtrap/client.rb Enhanced get and perform_request methods to accept optional query parameters for GET requests.
lib/mailtrap.rb Required new internal files for base API and suppressions API.
examples/suppressions_api.rb Added example script demonstrating usage of the new Suppressions API.
spec/mailtrap/suppressions_api_spec.rb, spec/mailtrap/suppression_spec.rb Added RSpec tests for SuppressionsAPI and Suppression struct.
spec/fixtures/vcr_cassettes/Mailtrap_SuppressionsAPI/vcr_list/maps_response_data_to_Suppression_objects.yml
spec/fixtures/vcr_cassettes/Mailtrap_SuppressionsAPI/vcr_list/when_api_key_is_incorrect/raises_authorization_error.yml
Added VCR cassettes for API success and authorization error scenarios.
spec/spec_helper.rb Added custom RSpec matcher to compare object IDs.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SuppressionsAPI
    participant Client
    participant MailtrapServer

    User->>SuppressionsAPI: list(email: nil)
    SuppressionsAPI->>Client: get("/accounts/:account_id/suppressions", query_params)
    Client->>MailtrapServer: HTTP GET /accounts/:account_id/suppressions
    MailtrapServer-->>Client: JSON array of suppressions
    Client-->>SuppressionsAPI: parsed response
    SuppressionsAPI-->>User: Array of Suppression objects

    User->>SuppressionsAPI: delete(suppression_id)
    SuppressionsAPI->>Client: delete("/accounts/:account_id/suppressions/:suppression_id")
    Client->>MailtrapServer: HTTP DELETE /accounts/:account_id/suppressions/:suppression_id
    MailtrapServer-->>Client: HTTP 204 No Content
    Client-->>SuppressionsAPI: nil
    SuppressionsAPI-->>User: nil
Loading

Suggested reviewers

  • i7an

Poem

A new API hops in, so spry and neat,
Suppressions managed with a single tweet.
With specs and examples, the code is robust,
Query params handled, in Mailtrap we trust.
🐇✨
Refactored and tested, the garden grows bright—
Another fine patch, shipped with delight!

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
spec/spec_helper.rb (1)

52-55: Consider using !equal? for object identity comparison.

The static analysis tool correctly suggests using !equal? instead of != when comparing object identity. This is more semantically appropriate and potentially more performant.

RSpec::Matchers.define :have_different_object_id_than do |expected|
  match do |actual|
-    actual.object_id != expected.object_id
+    !actual.equal?(expected)
  end
lib/mailtrap/base_api.rb (1)

10-15: Handle missing environment variable gracefully.

The current implementation will raise a KeyError if MAILTRAP_ACCOUNT_ID is not set, which may not provide a clear error message to users.

-def initialize(account_id = ENV.fetch('MAILTRAP_ACCOUNT_ID'), client = Mailtrap::Client.new)
+def initialize(account_id = ENV.fetch('MAILTRAP_ACCOUNT_ID', nil), client = Mailtrap::Client.new)

This change would make the error message from line 11 more informative than the default KeyError.

spec/mailtrap/suppressions_api_spec.rb (1)

12-54: Consider reducing test data complexity for maintainability.

While the comprehensive test data coverage is excellent, the extensive attribute definitions (30+ attributes per suppression) might make the tests harder to maintain. Consider extracting common test data to shared examples or factories if this pattern repeats across other test files.

For better maintainability, consider creating a test factory:

+# In spec/support/factories.rb or similar
+def build_suppression_attributes(overrides = {})
+  {
+    'id' => '123e4567-e89b-12d3-a456-426614174000',
+    'type' => 'hard bounce',
+    'created_at' => '2024-06-01T12:00:00Z',
+    'email' => 'user1@example.com',
+    # ... other common attributes
+  }.merge(overrides)
+end
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9429154 and ea1634f.

📒 Files selected for processing (12)
  • examples/suppressions_api.rb (1 hunks)
  • lib/mailtrap.rb (1 hunks)
  • lib/mailtrap/base_api.rb (1 hunks)
  • lib/mailtrap/client.rb (2 hunks)
  • lib/mailtrap/email_templates_api.rb (4 hunks)
  • lib/mailtrap/suppression.rb (1 hunks)
  • lib/mailtrap/suppressions_api.rb (1 hunks)
  • spec/fixtures/vcr_cassettes/Mailtrap_SuppressionsAPI/vcr_list/maps_response_data_to_Suppression_objects.yml (1 hunks)
  • spec/fixtures/vcr_cassettes/Mailtrap_SuppressionsAPI/vcr_list/when_api_key_is_incorrect/raises_authorization_error.yml (1 hunks)
  • spec/mailtrap/suppression_spec.rb (1 hunks)
  • spec/mailtrap/suppressions_api_spec.rb (1 hunks)
  • spec/spec_helper.rb (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
lib/mailtrap/client.rb (1)
lib/mailtrap/email_templates_api.rb (1)
  • get (22-25)
lib/mailtrap/base_api.rb (2)
lib/mailtrap/client.rb (2)
  • attr_reader (8-190)
  • initialize (31-54)
lib/mailtrap/action_mailer/delivery_method.rb (1)
  • client (22-24)
lib/mailtrap/suppressions_api.rb (4)
lib/mailtrap/email_templates_api.rb (4)
  • list (13-16)
  • get (22-25)
  • base_path (72-74)
  • delete (66-68)
lib/mailtrap/action_mailer/delivery_method.rb (1)
  • client (22-24)
lib/mailtrap/client.rb (2)
  • get (73-75)
  • delete (99-101)
lib/mailtrap/base_api.rb (1)
  • build_entity (26-28)
spec/mailtrap/suppression_spec.rb (1)
lib/mailtrap/suppression.rb (1)
  • to_h (42-44)
🪛 RuboCop (1.75.5)
spec/spec_helper.rb

[warning] 54-54: Use !equal? instead of != when comparing object_id.

(Lint/IdentityComparison)

🔇 Additional comments (21)
lib/mailtrap/client.rb (2)

70-75: Excellent implementation of query parameter support.

The addition of optional query_params to the get method is well-designed:

  • Maintains backward compatibility with a sensible default
  • Clear parameter documentation
  • Follows existing method signature patterns

125-128: Clean query parameter handling implementation.

The query parameter encoding logic is implemented correctly:

  • Only processes parameters when present (query_params.any?)
  • Uses standard URI.encode_www_form for proper URL encoding
  • Integrates seamlessly with existing request setup
lib/mailtrap/suppression.rb (2)

3-21: Excellent documentation and API reference.

The comprehensive YARD documentation with proper attribute descriptions and the reference to the official API documentation makes this DTO very maintainable and developer-friendly.


22-45: Well-designed DTO implementation.

Excellent use of Ruby Struct with several good practices:

  • keyword_init: true for better readability and clarity
  • Comprehensive attribute set that matches the API structure
  • Smart to_h override using super.compact to remove nil values, which is perfect for clean JSON serialization
  • Follows immutable data structure patterns
lib/mailtrap.rb (1)

7-9: Proper module dependency management.

The new require statements are correctly placed and follow the logical dependency order (base_api before suppressions_api). This maintains consistency with the existing require pattern in the file.

spec/fixtures/vcr_cassettes/Mailtrap_SuppressionsAPI/vcr_list/maps_response_data_to_Suppression_objects.yml (1)

1-167: Well-structured VCR test fixture.

This VCR cassette properly captures the Suppressions API interaction with:

  • Correct HTTP method and endpoint structure
  • Proper authorization and headers
  • Realistic response data that matches the Suppression DTO structure
  • Appropriate sensitive data filtering (bearer token masked)
  • Comprehensive security headers that reflect production API behavior

The fixture will provide reliable test coverage for the suppressions API functionality.

spec/mailtrap/suppression_spec.rb (1)

1-46: Well-structured test suite with comprehensive coverage.

The test specification effectively covers both initialization and hash conversion functionality. The comprehensive attribute set provides thorough testing of the Suppression DTO, and the use of the custom have_different_object_id_than matcher appropriately verifies that to_h returns a new hash object rather than the original attributes.

spec/fixtures/vcr_cassettes/Mailtrap_SuppressionsAPI/vcr_list/when_api_key_is_incorrect/raises_authorization_error.yml (1)

1-167: Proper VCR recording for authorization error testing.

The VCR cassette correctly captures an HTTP 401 Unauthorized response scenario with appropriate token masking and realistic response structure. This will enable reliable testing of error handling in the API client.

lib/mailtrap/suppressions_api.rb (2)

11-17: Clean implementation of list method with proper parameter handling.

The method correctly handles optional email filtering by building query parameters conditionally and maps the response to Suppression objects using the inherited build_entity method. The implementation is consistent with other API classes in the codebase.


23-25: Simple and correct delete implementation.

The delete method properly constructs the URL path and delegates to the client's delete method. The implementation follows the established pattern from other API classes.

lib/mailtrap/base_api.rb (2)

19-24: Robust options validation with clear error messaging.

The validation method properly identifies invalid options and provides clear error messages including both the invalid options and supported options. This will help developers quickly identify and fix API usage issues.


26-28: Elegant entity building using response class members.

The build_entity method cleverly uses the response class's members to slice only relevant attributes from the options hash. This provides a clean and maintainable way to construct objects while preventing unexpected attributes from being passed through.

spec/mailtrap/suppressions_api_spec.rb (5)

1-10: LGTM! Clean test setup with proper configuration.

The test setup follows RSpec best practices with proper subject definition, environment variable handling with sensible defaults, and clear variable naming.


56-68: Excellent test coverage for the list method.

The test properly verifies both the response structure (array of Suppression objects) and the attribute mapping. The use of all(be_a(Mailtrap::Suppression)) is a clean way to verify the collection type.


70-79: Good error handling test for unauthorized access.

The test correctly verifies that HTTP 401 responses raise Mailtrap::AuthorizationError. This ensures proper error propagation from the API client.


82-114: Comprehensive delete method test coverage.

The tests cover all critical scenarios:

  • Successful deletion (HTTP 204 → nil response)
  • Not found error (HTTP 404 → Mailtrap::Error)
  • Unauthorized error (HTTP 401 → Mailtrap::AuthorizationError)

The error handling distinctions are appropriate for different HTTP status codes.


116-145: Excellent integration testing with VCR.

The VCR tests provide valuable integration coverage and properly test both success and authorization error scenarios. The dynamic attribute checking with be_a(String) is appropriate for integration tests where exact values may vary.

lib/mailtrap/email_templates_api.rb (4)

6-6: Good refactoring to inherit from BaseAPI.

The inheritance change eliminates code duplication and provides a consistent base for API classes. This follows the DRY principle and improves maintainability across the SDK.


15-15: Consistent adoption of the base class build_entity method.

The replacement of build_email_template(template) with build_entity(template, EmailTemplate) is consistent across all methods and leverages the generalized approach from BaseAPI. This maintains the same functionality while using shared code.

Also applies to: 24-24, 41-41, 59-59


38-38: Proper validation method usage with explicit options.

The updated validate_options! calls correctly pass the SUPPORTED_OPTIONS constant to the base class method. This maintains the validation logic while using the generalized implementation.

Also applies to: 56-56


72-74: Appropriate retention of API-specific logic.

The base_path method remains in the class as it contains API-specific logic. This is the correct approach - inherit common functionality while keeping specialized behavior local.

list = suppressions.list

# Delete a suppression
suppressions.delete(list.first.id)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add nil check before accessing list.first.

The code assumes the suppressions list is not empty, which could cause a NoMethodError if no suppressions exist.

-suppressions.delete(list.first.id)
+suppressions.delete(list.first.id) if list.any?
🤖 Prompt for AI Agents
In examples/suppressions_api.rb at line 16, add a nil check before accessing
list.first to prevent a NoMethodError when the suppressions list is empty.
Modify the code to verify that list.first is not nil before calling .id and
passing it to suppressions.delete, ensuring safe handling of empty lists.

Comment on lines +3 to +4
client = Mailtrap::Client.new(api_key: 'your-api-key')
suppressions = Mailtrap::SuppressionsAPI.new 3229, client
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove hardcoded credentials from example.

The example contains hardcoded API credentials which could be accidentally committed or copied by users. Consider using placeholder text or environment variables by default.

-client = Mailtrap::Client.new(api_key: 'your-api-key')
-suppressions = Mailtrap::SuppressionsAPI.new 3229, client
+# Set your API credentials as environment variables
+# export MAILTRAP_API_KEY='your-api-key'
+# export MAILTRAP_ACCOUNT_ID=your-account-id
+suppressions = Mailtrap::SuppressionsAPI.new
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
client = Mailtrap::Client.new(api_key: 'your-api-key')
suppressions = Mailtrap::SuppressionsAPI.new 3229, client
# Set your API credentials as environment variables
# export MAILTRAP_API_KEY='your-api-key'
# export MAILTRAP_ACCOUNT_ID=your-account-id
suppressions = Mailtrap::SuppressionsAPI.new
🤖 Prompt for AI Agents
In examples/suppressions_api.rb around lines 3 to 4, the API key is hardcoded
directly in the code, which risks accidental exposure. Replace the hardcoded API
key string with a placeholder text like 'your-api-key' or fetch it from an
environment variable to avoid embedding sensitive credentials in the example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant