Skip to content
v1
Docs

PHP SDK

The REST API from PHP

Every /v1 operation is a method on a service named after its area. The method is the action of the operation’s id (public.servers.systemServices is $wt15->servers->systemServices($serverUuid)). The services are alarms, customMetrics, databases, domains, health, incidents, logs, scans, servers, services and tags; me() stays on the client. The API reference lists the operations. You need an API key: see authentication and keys.

$wt15 = WatchTower15\Client::fromEnvironment();
$me = $wt15->me();
echo $me->keyName, ' in ', $me->organisationName, ' (', implode(', ', $me->scopes), ')';
$page = $wt15->servers->list(['health' => ['critical', 'warning'], 'per_page' => 50]);
foreach ($page->data as $server) {
echo $server->name, ' ', $server->healthStatus, ' last seen ', $server->agentLastSeenAt?->format('c'), "\n";
}
echo $page->total, ' servers; more: ', $page->hasMore() ? 'yes' : 'no';
$metrics = $wt15->servers->metrics($serverUuid, ['family' => 'cpu', 'period' => '1h']);

The ids in the path come first, as strings. The filters are one $params array, whose keys your IDE and PHPStan know. The $params array is there even for an operation with no filter yet, so a filter the API adds later changes no signature. The per-call options (timeout, connect_timeout, max_retries, max_retry_wait) come last. A filter newer than the SDK is sent as you give it.

An answer is a readonly object with typed properties. A time is a UTC DateTimeImmutable. A value that can be one of a set of words stays a string, so a word the API adds later never breaks your code; beside it, an enum of the words this SDK version knows (for example WatchTower15\Api\Generated\Enums\ServersMetricsFamily) helps you compare. toArray() returns exactly what the server sent, fields newer than the SDK included.

A list is a Page: data, meta, total and its paging fields. Most lists page by number: a page carries currentPage, perPage and lastPage, and the next one is asked for with page, your other parameters kept (per_page sets the page size; limit is the same). Log search and a service’s scans and runs page by time: a page carries nextCursor, sent back as cursor. total is always set on a page list; log search answers null. hasMore() and autoPaging() follow whichever form the answer has, and autoPaging() walks every item of every page, fetching the next page only when you reach it:

foreach ($wt15->servers->list(['per_page' => 100, 'sort' => 'name'])->autoPaging() as $server) {
// ...
}

When a response says the rate limit is spent, autoPaging() waits for its reset if that is at most max_retry_wait seconds away (60 unless you set it), and otherwise throws RateLimitException without sending a request that could only earn a 429. See also pagination.

acknowledge, resolve and runScan send an Idempotency-Key, a random one unless you give your own:

$wt15->incidents->acknowledge($incidentUuid, ['idempotency_key' => 'ack-incident-42']);

A key is 1 to 255 visible ASCII characters. A retry sends the same key, so a write retries like a read, and an answer replayed from the first try ($wt15->lastResponse()->replayed) is a success. See acting on incidents and scans.

A service is one to ten steps (multi-step services). create and update take the definition as an array; a kept step carries its uuid and leaves out its headers, body, query and auth, which are kept as saved.

$service = $wt15->services->create([
'name' => 'Orders journey',
'collectors' => ['selection' => 'servers', 'servers' => [$serverUuid]],
'steps' => [[
'name' => 'Health',
'type' => 'http',
'request' => ['method' => 'GET', 'url' => 'https://orders.example.com/health'],
'assertions' => [['target' => 'status', 'operator' => 'in', 'value' => [200]]],
]],
]);

Test a definition before you save it, then read the test until it ends. A test is waiting or picked_up while it is in flight, and ends passed, failed or no_answer:

$test = $wt15->services->testRunsStartNew($definition);
do {
sleep(5);
$test = $wt15->services->testRunsView($test->uuid);
} while (in_array($test->status, ['waiting', 'picked_up'], true));

Read a service’s runs and versions:

foreach ($wt15->services->runsList($serviceUuid, ['period' => '1d', 'status' => 'failed']) as $run) {
echo $run->failedStepUuid, ' ', $run->failedReason, "\n";
}
$run = $wt15->services->runsView($serviceUuid, $runUuid);
$versions = $wt15->services->versions($serviceUuid);

A step’s uuid, name, type, destination, assertions and on_failure are on the models; its headers, body and credentials never are.

runScan answers at once with a scan that is queued:

$scan = $wt15->domains->runScan($domainUuid, 'ssl');
$done = $wt15->scans->waitUntilFinished($scan->scanUuid, timeoutSeconds: 120, pollSeconds: 5);
echo $done->status; // completed, failed or timeout

Past the timeout it throws WaiterTimeoutException, whose scan() is the last scan read.

request() calls it with the same key, retries, errors and lastResponse():

$envelope = $wt15->request('GET', '/servers/{server_uuid}/ports', ['server_uuid' => $serverUuid, 'limit' => 5]);
$ports = $envelope['data'];

{name} placeholders are filled from the array and URL-encoded; the rest goes to the query (GET, DELETE) or a JSON body. A path that is not under /v1, an unfilled placeholder or an unknown method is refused with a ConfigurationException before anything is sent.

Everything the SDK throws implements WatchTower15\Exception\WatchTower15Exception. catch (ApiException) handles the API’s answers, and catch (WatchTower15Exception) handles everything. See errors for the codes.

Exception When
AuthenticationException 401
PermissionException 403 on /v1
NotFoundException 404
InvalidRequestException 400, and 422 other than a limit (errors())
LimitReachedException 422 limit_reached (limit(), used())
PaymentRequiredException 402
RateLimitException 429 (getRetryAfter())
PayloadTooLargeException 413
ServiceUnavailableException, ServerException 503; other 5xx
ApiConnectionException no answer: DNS, connect, TLS, a timeout (wasSent())
UnexpectedResponseException an edge or proxy answered, a redirect, an empty 200
ApiException any other 4xx; the base of the family
ConfigurationException a bad option, argument, path, or a credential in the wrong slot

An ApiException gives getStatusCode(), getErrorCode(), getDetail(), getRequestId(), getRetryAfter() and getProblem().

A read (me(), list() and the other reads) is retried on no answer, 408, 429, 502, 503 and 504, and never on 500 or any other 4xx. A write is retried the same way, with the same Idempotency-Key. There are up to maxRetries more attempts. A wait is the server’s Retry-After, or a random wait of up to min(8 s, 0.5 s × 2^(attempt−1)). A wait longer than max_retry_wait is not taken: the error is thrown at once.

$wt15->lastResponse() returns the status, headers, request id and rate limit of the last exchange, a failed one included. A Deprecation or Sunset header is logged once per operation at warning: see versioning and deprecation.