Skip to content

Add missing endpoints#65

Open
IgorDobryn wants to merge 4 commits intomainfrom
MT-21863-php-sdk-add-webhooks-api-tokens-and-sub-accounts-endpoints
Open

Add missing endpoints#65
IgorDobryn wants to merge 4 commits intomainfrom
MT-21863-php-sdk-add-webhooks-api-tokens-and-sub-accounts-endpoints

Conversation

@IgorDobryn
Copy link
Copy Markdown
Contributor

@IgorDobryn IgorDobryn commented Apr 30, 2026

Motivation

Changes

Webhooks

  • GET /api/accounts/{account_id}/webhooks
  • POST /api/accounts/{account_id}/webhooks
  • GET /api/accounts/{account_id}/webhooks/{webhook_id}
  • PATCH /api/accounts/{account_id}/webhooks/{webhook_id}
  • DELETE /api/accounts/{account_id}/webhooks/{webhook_id}

API Tokens

  • GET /api/accounts/{account_id}/api_tokens
  • POST /api/accounts/{account_id}/api_tokens
  • GET /api/accounts/{account_id}/api_tokens/{id}
  • DELETE /api/accounts/{account_id}/api_tokens/{id}
  • POST /api/accounts/{account_id}/api_tokens/{id}/reset

Sub-Accounts

  • GET /api/organizations/{organization_id}/sub_accounts
  • POST /api/organizations/{organization_id}/sub_accounts

Sandbox Messages

  • POST /api/accounts/{account_id}/inboxes/{inbox_id}/messages/{message_id}/forward
  • GET /api/accounts/{account_id}/inboxes/{inbox_id}/messages/{message_id}/mail_headers

Summary by CodeRabbit

Release Notes

  • New Features

    • API Tokens: Create, manage, and reset account API tokens with fine-grained permissions
    • Sub-Accounts: Manage organization-level sub-accounts
    • Webhooks: Configure and manage webhooks with full CRUD operations
    • Sandbox Enhancements: Retrieve mail headers and forward messages for testing
  • Documentation

    • Added comprehensive examples for API Tokens, Sub-Accounts, Webhooks, and sandbox messaging operations

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 30, 2026

📝 Walkthrough

Walkthrough

This PR adds comprehensive API support for Mailtrap webhooks, API tokens, sub-accounts, and additional sandbox message operations. It introduces new API client classes with corresponding DTOs, wires them into existing and new Mailtrap clients, includes example scripts, updates documentation, and provides full test coverage.

Changes

API Expansion (Webhooks, Tokens, Sub-Accounts, Message Operations)

Layer / File(s) Summary
Data Shapes / DTOs
src/DTO/Request/Webhook/*
Added WebhookInterface, CreateWebhook, and UpdateWebhook DTOs for webhook configuration and updates. Interfaces define webhook types, payload formats, streams, and event constants.
Core API Implementations
src/Api/General/ApiToken.php, src/Api/Organization/SubAccount.php, src/Api/Sending/Webhook.php, src/Api/Sandbox/Message.php
Implemented API client classes for tokens (list/get/create/delete/reset), sub-accounts (list/create), webhooks (CRUD), and message operations (mail headers, forward). Each extends AbstractApi with private getBasePath() helpers and HTTP method routing.
Organization Layer Foundation
src/Api/Organization/OrganizationInterface.php
Established OrganizationInterface as the base contract for organization-scoped API clients.
Client Wiring
src/MailtrapGeneralClient.php, src/MailtrapOrganizationClient.php, src/MailtrapSendingClient.php
Registered API mappings in client classes: apiTokens in MailtrapGeneralClient, new MailtrapOrganizationClient with subAccounts mapping, and webhooks in MailtrapSendingClient.
Examples & Environment Setup
.envrc, examples/api-tokens/all.php, examples/sub-accounts/all.php, examples/webhooks/all.php, examples/testing/messages.php
Added environment variables for Mailtrap credentials and PHP example scripts demonstrating CRUD operations for each new API surface.
Documentation
CHANGELOG.md
Updated [Unreleased] section with entries for Stats API, API Tokens API, Sub-Accounts API, Sandbox message endpoints, and Webhooks API.
Test Coverage
tests/Api/General/ApiTokenTest.php, tests/Api/Organization/SubAccountTest.php, tests/Api/Sending/WebhookTest.php, tests/Api/Sandbox/MessageTest.php, tests/MailtrapGeneralClientTest.php, tests/MailtrapOrganizationClientTest.php, tests/MailtrapSendingClientTest.php
Comprehensive test suites covering success and error scenarios for all new API operations, including mocked HTTP interactions, validation, and response parsing. Helper test class MailtrapOrganizationClientTest wires up organization-scoped client testing.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Improve examples #56 — Modifies the same example scripts (e.g., examples/testing/messages.php) to demonstrate new features.
  • Add support for Email Logs API #62 — Updates MailtrapSendingClient::API_MAPPING with different API mappings, sharing the same client wiring pattern.

Suggested reviewers

  • leonid-shevtsov
  • VladimirTaytor
  • piobeny
  • yanchuk

Poem

🐰 Webhooks dance and tokens spin,
Sub-accounts bloom where they begin,
Messages forwarded with a bound,
CRUD operations all around,
The Mailtrap SDK grows profound!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Add missing endpoints' is vague and generic, using non-descriptive language that doesn't convey which endpoints or what areas are affected. Use a more specific title such as 'Add Webhooks, API Tokens, Sub-Accounts, and Sandbox Message endpoints' to better describe the main changes.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The description provides only a high-level list of endpoints under the Changes section but lacks the Motivation section explaining why these endpoints are needed, and does not include the How to test and Images/GIFs sections from the template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch MT-21863-php-sdk-add-webhooks-api-tokens-and-sub-accounts-endpoints

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 PHPStan (2.1.51)

PHPStan was skipped because the sandbox runner could not parse its output.


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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

Comment @coderabbitai help to get the list of available commands and usage tips.

@IgorDobryn IgorDobryn changed the title Mt 21863 php sdk add webhooks api tokens and sub accounts endpoints Add missing endpoints Apr 30, 2026
@IgorDobryn IgorDobryn force-pushed the MT-21863-php-sdk-add-webhooks-api-tokens-and-sub-accounts-endpoints branch from d240511 to 743ef96 Compare May 1, 2026 06:48
@IgorDobryn IgorDobryn marked this pull request as ready for review May 4, 2026 12:07
Copy link
Copy Markdown

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@examples/api-tokens/all.php`:
- Around line 12-14: Add a guard that checks the required environment variables
before using them: validate $_ENV['MAILTRAP_ACCOUNT_ID'] and
$_ENV['MAILTRAP_API_KEY'] and throw/exit with a clear error message if either is
missing so the example fails fast; update the bootstrap around $accountId, the
Config(...) call, and the MailtrapGeneralClient(...)->apiTokens(...) usage to
rely on the validated values (or sanitized variables) rather than accessing
$_ENV directly.

In `@examples/webhooks/all.php`:
- Around line 12-14: The example currently reads $_ENV['MAILTRAP_ACCOUNT_ID']
and $_ENV['MAILTRAP_API_KEY'] directly which can be null and emit notices; add a
small bootstrap guard before creating Config and calling (new
MailtrapSendingClient($config))->webhooks($accountId) that checks required env
vars (MAILTRAP_ACCOUNT_ID and MAILTRAP_API_KEY), optionally MAILTRAP_DOMAIN_ID
if domain-scoped webhooks are intended, and exits with a clear error message
when any are missing so Config is never constructed with null values and the
script fails fast and informatively.

In `@src/DTO/Request/Webhook/CreateWebhook.php`:
- Around line 21-37: CreateWebhook currently allows building invalid payloads
for type-specific webhooks; add validation in the CreateWebhook constructor (or
in toArray) to enforce required fields based on $webhookType (e.g., when
$webhookType === 'email_sending' require non-null $sendingStream and non-empty
$eventTypes), throw a clear exception (InvalidArgumentException) on violation,
or alternatively refactor by splitting CreateWebhook into separate DTOs per
webhook kind (e.g., EmailSendingWebhook with required $sendingStream and
EventTypes) and use the appropriate DTO where needed; update
CreateWebhook::toArray to assume validated fields so it cannot serialize invalid
requests.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 60e92d97-9770-4f7f-abc9-d3da6787856a

📥 Commits

Reviewing files that changed from the base of the PR and between 84717fd and 743ef96.

📒 Files selected for processing (24)
  • .envrc
  • CHANGELOG.md
  • examples/api-tokens/all.php
  • examples/sub-accounts/all.php
  • examples/testing/messages.php
  • examples/webhooks/all.php
  • src/Api/General/ApiToken.php
  • src/Api/Organization/OrganizationInterface.php
  • src/Api/Organization/SubAccount.php
  • src/Api/Sandbox/Message.php
  • src/Api/Sending/Webhook.php
  • src/DTO/Request/Webhook/CreateWebhook.php
  • src/DTO/Request/Webhook/UpdateWebhook.php
  • src/DTO/Request/Webhook/WebhookInterface.php
  • src/MailtrapGeneralClient.php
  • src/MailtrapOrganizationClient.php
  • src/MailtrapSendingClient.php
  • tests/Api/General/ApiTokenTest.php
  • tests/Api/Organization/SubAccountTest.php
  • tests/Api/Sandbox/MessageTest.php
  • tests/Api/Sending/WebhookTest.php
  • tests/MailtrapGeneralClientTest.php
  • tests/MailtrapOrganizationClientTest.php
  • tests/MailtrapSendingClientTest.php

Comment on lines +12 to +14
$accountId = $_ENV['MAILTRAP_ACCOUNT_ID'];
$config = new Config($_ENV['MAILTRAP_API_KEY']); #your API token from here https://mailtrap.io/api-tokens
$apiTokens = (new MailtrapGeneralClient($config))->apiTokens($accountId);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fail fast when required example env vars are missing.

$_ENV['MAILTRAP_ACCOUNT_ID'] and $_ENV['MAILTRAP_API_KEY'] are accessed directly, so a missing environment setup will surface as notices or a later client error instead of a clear bootstrap failure. A small guard here would make the example much easier to run.

♻️ Suggested bootstrap guard
 require __DIR__ . '/../../vendor/autoload.php';
 
+foreach (['MAILTRAP_ACCOUNT_ID', 'MAILTRAP_API_KEY'] as $envVar) {
+    if (empty($_ENV[$envVar])) {
+        throw new RuntimeException(sprintf('%s must be set for this example.', $envVar));
+    }
+}
+
 $accountId = $_ENV['MAILTRAP_ACCOUNT_ID'];
 $config = new Config($_ENV['MAILTRAP_API_KEY']); `#your` API token from here https://mailtrap.io/api-tokens
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/api-tokens/all.php` around lines 12 - 14, Add a guard that checks
the required environment variables before using them: validate
$_ENV['MAILTRAP_ACCOUNT_ID'] and $_ENV['MAILTRAP_API_KEY'] and throw/exit with a
clear error message if either is missing so the example fails fast; update the
bootstrap around $accountId, the Config(...) call, and the
MailtrapGeneralClient(...)->apiTokens(...) usage to rely on the validated values
(or sanitized variables) rather than accessing $_ENV directly.

Comment thread examples/webhooks/all.php
Comment on lines +12 to +14
$accountId = $_ENV['MAILTRAP_ACCOUNT_ID'];
$config = new Config($_ENV['MAILTRAP_API_KEY']); #your API token from here https://mailtrap.io/api-tokens
$webhooks = (new MailtrapSendingClient($config))->webhooks($accountId);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fail fast when required example env vars are missing.

Reading $_ENV['MAILTRAP_ACCOUNT_ID'] / $_ENV['MAILTRAP_API_KEY'] directly will emit notices and hand null to Config when the example is run without setup. A small bootstrap guard would make the script much more robust. If you want this sample to demonstrate domain-scoped webhooks, consider documenting MAILTRAP_DOMAIN_ID alongside the other env vars as well.

♻️ Suggested bootstrap guard
 <?php
 
 use Mailtrap\Config;
@@
 require __DIR__ . '/../../vendor/autoload.php';
 
+foreach (['MAILTRAP_ACCOUNT_ID', 'MAILTRAP_API_KEY'] as $envVar) {
+    if (empty($_ENV[$envVar])) {
+        throw new RuntimeException(sprintf('%s must be set for this example.', $envVar));
+    }
+}
+
 $accountId = $_ENV['MAILTRAP_ACCOUNT_ID'];
 $config = new Config($_ENV['MAILTRAP_API_KEY']); `#your` API token from here https://mailtrap.io/api-tokens
📝 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
$accountId = $_ENV['MAILTRAP_ACCOUNT_ID'];
$config = new Config($_ENV['MAILTRAP_API_KEY']); #your API token from here https://mailtrap.io/api-tokens
$webhooks = (new MailtrapSendingClient($config))->webhooks($accountId);
<?php
use Mailtrap\Config;
use Mailtrap\MailtrapSendingClient;
require __DIR__ . '/../../vendor/autoload.php';
foreach (['MAILTRAP_ACCOUNT_ID', 'MAILTRAP_API_KEY'] as $envVar) {
if (empty($_ENV[$envVar])) {
throw new RuntimeException(sprintf('%s must be set for this example.', $envVar));
}
}
$accountId = $_ENV['MAILTRAP_ACCOUNT_ID'];
$config = new Config($_ENV['MAILTRAP_API_KEY']); `#your` API token from here https://mailtrap.io/api-tokens
$webhooks = (new MailtrapSendingClient($config))->webhooks($accountId);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/webhooks/all.php` around lines 12 - 14, The example currently reads
$_ENV['MAILTRAP_ACCOUNT_ID'] and $_ENV['MAILTRAP_API_KEY'] directly which can be
null and emit notices; add a small bootstrap guard before creating Config and
calling (new MailtrapSendingClient($config))->webhooks($accountId) that checks
required env vars (MAILTRAP_ACCOUNT_ID and MAILTRAP_API_KEY), optionally
MAILTRAP_DOMAIN_ID if domain-scoped webhooks are intended, and exits with a
clear error message when any are missing so Config is never constructed with
null values and the script fails fast and informatively.

Comment on lines +21 to +37
public function __construct(
private string $url,
private string $webhookType,
private array $eventTypes = [],
private ?string $payloadFormat = null,
private ?string $sendingStream = null,
private ?int $domainId = null,
private ?bool $active = null,
) {
}

public function toArray(): array
{
$payload = [
'url' => $this->url,
'webhook_type' => $this->webhookType,
'event_types' => $this->eventTypes,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Validate type-specific webhook requirements.

eventTypes defaults to an empty array and sendingStream is nullable, so callers can build an email_sending webhook that serializes into an invalid request. Please enforce the required fields when webhookType needs them, or split the DTO by webhook kind.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/DTO/Request/Webhook/CreateWebhook.php` around lines 21 - 37,
CreateWebhook currently allows building invalid payloads for type-specific
webhooks; add validation in the CreateWebhook constructor (or in toArray) to
enforce required fields based on $webhookType (e.g., when $webhookType ===
'email_sending' require non-null $sendingStream and non-empty $eventTypes),
throw a clear exception (InvalidArgumentException) on violation, or
alternatively refactor by splitting CreateWebhook into separate DTOs per webhook
kind (e.g., EmailSendingWebhook with required $sendingStream and EventTypes) and
use the appropriate DTO where needed; update CreateWebhook::toArray to assume
validated fields so it cannot serialize invalid requests.

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