Python SDK
The REST API from Python
Every /v1 operation is a method on a resource of the client, named as in the API reference: client.servers.list(), client.custom_metrics.series(uuid, period="1h"). You need an API key: see
authentication and keys. The same methods exist on AsyncClient, as coroutines (a paged one returns an async paginator). A method takes its path parameters positionally, in path
order and percent-encoded (an empty one is refused), then the query and body parameters as keyword arguments, then request_options:
server = client.servers.view(server_uuid)client.domains.run_scan(domain_uuid, "dns", request_options={"idempotency_key": "scan-dns-42"})A parameter that clashes with a Python keyword takes a trailing underscore (from_). A parameter you leave out is never sent: NOT_GIVEN is the default, and an explicit None is sent as JSON null.
NOT_GIVEN is importable from watchtower15 for code that forwards an optional value. A list goes as name[]=v once per value, a bool as 1 or 0, a timezone-aware datetime as epoch milliseconds
(a naive one is refused, since it would mean the host’s zone); any other value is refused naming the parameter.
Models
Section titled “Models”Models are frozen dataclasses with the wire’s names (server.health_status). Model.from_dict(mapping) decodes what the server sent and model.to_dict() writes it back, keeping every field the server sent
that the SDK does not know, so a model read, changed (dataclasses.replace) and sent back keeps them all. Enums are open: a field is typed HealthValue, a Literal of the known strings or any str, with a
StrEnum (Health.CRITICAL) beside it, so a new server value never breaks you. An instant is a timezone-aware UTC datetime.
A list returns a page. Iterate it for every item, a page fetched only when the last is used up, or use the page itself. Most lists page by number: a page carries current_page, per_page and last_page, and the next one is asked for with page, your other params 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 next_cursor, sent back as cursor. has_next_page(), get_next_page() and iteration follow whichever form the answer has:
for server in client.servers.list(per_page=100, health=["critical"]): ...
page = client.incidents.list(per_page=25)page.data, page.current_page, page.per_page, page.last_page, page.total, page.metaif page.has_next_page(): page = page.get_next_page()On AsyncClient, async for walks every item and await gives the first AsyncPage. Paging is paced: when an answer says no request is left, the next page waits for the limit’s reset if that is
within max_retry_wait, and otherwise raises a RateLimitError without sending.
Options of a call
Section titled “Options of a call”request_options is a dictionary: timeout, connect_timeout, max_retries, max_retry_wait (seconds, 60 by default: a longer wait is not taken and the answer is raised), and on a write
idempotency_key (1 to 255 visible ASCII characters). Each is checked before anything is sent.
Errors
Section titled “Errors”Everything the SDK raises is a WatchTower15Error. A ConfigurationError or InvalidPayloadError (both ValueErrors) is raised before anything is sent. An APIError carries status, code, detail,
request_id, retry_after (seconds), operation and response (the answer’s facts, with its rate limit). Its subclasses: APIStatusError and, under it, AuthenticationError (401, and an ingest 403),
PermissionDeniedError, NotFoundError, InvalidRequestError (errors), LimitReachedError (limit, used), PaymentRequiredError, PayloadTooLargeError, RateLimitError (DailyLimitError and
LogVolumeLimitError, with resumes_at), ServiceUnavailableError, ServerError and UnexpectedResponseError (an edge or proxy answered, or a redirect: cf_ray, content_type); APIConnectionError
(was_sent, response_too_large, reason) and its APITimeoutError; and WaiterTimeoutError, which carries the scan.
from watchtower15 import NotFoundError, RateLimitError
try: client.servers.view(uuid)except NotFoundError as error: print(error.status, error.code, error.request_id)except RateLimitError as error: print(error.retry_after)Retries and idempotency
Section titled “Retries and idempotency”Every POST, PUT and DELETE carries an Idempotency-Key: yours, or one made for the call and reused on each retry, so a retried write is never done twice, and a replayed answer
(Idempotent-Replayed: true) is a success, not an error.
Raw responses
Section titled “Raw responses”.with_raw_response on the client or on a resource gives the same methods, each answering an APIResponse: .parse() is what the plain method returns, and the response itself holds status_code, headers, request_id,
operation, whether the answer was a replayed one, and the rate_limit (limit, remaining, reset_at).
raw = client.servers.with_raw_response.view(uuid)raw.parse().name, raw.rate_limitWaiting for a scan, and newer operations
Section titled “Waiting for a scan, and newer operations”client.scans.wait_until_finished(scan_uuid, timeout=120.0, poll_interval=5.0) polls until the scan is neither queued nor running, else raises a WaiterTimeoutError carrying the scan; on
AsyncClient it is awaited. client.request(method, path, params=None, request_options=None) calls an operation newer than the installed SDK with the same auth, retries and errors: path is relative to
/v1, {name} placeholders are filled from params, the rest goes in the query (GET, DELETE) or the JSON body; a 204 answers {"data": None}. client.me() is GET /v1/me.
A Deprecation or Sunset header on an operation is logged once per operation per process at WARNING on the watchtower15 logger, with the dates as record attributes.