Skip to Content
Docs

Call Platform Services

Call any granted platform service's HTTP API from a managed Worker with services.request, including endpoints the typed capabilities don't cover.

services.request is the escape hatch to the platform's own HTTP APIs. It sends one JSON or text request to any service the Worker is granted. That includes services with no typed capability, such as Logs, Observability, Agents, and the Native Object Registry. It also includes services the typed capabilities already use, such as Native Objects, Files, the AI Gateway, and AI Search, when you need an endpoint or option their helpers don't offer. The host authenticates the request, so your code never handles a platform credential. A new endpoint on a granted service needs no adapter or template release.

services.request needs managed template 0.10.0 or later and an adapter from the same release. See Release Versions. On an earlier template, the call fails with contract (unsupported-method).

Prefer a typed capability when it does what you need. The typed capabilities page through results, stream large files, recover transfers, and check Native Object restrictions for you. services.request is limited to JSON or text bodies of 1 MiB, and on Native Objects to routes that name a type. See Limits and Retries and Native Object Rules.

Grant the Services

A Worker can call only the services in its PLATFORM_SERVICES option. The option is a comma-separated list of service names. With no value, every request is refused. Every managed template already gives the host the service catalog, through its platform-services feature, so this option is the only thing to set. It decides which catalog services your code may call with services.request. The typed capabilities and your declared connections don't need it: the host reaches Native Objects, Files, the AI Gateway, AI Search, and the Connections API for them whatever the option says. Grant only the services the app uses:

Terminal
ctxl workers create order-sync \
  --size small \
  --managed managed-event-worker:0.10.0 \
  --build .worker-image \
  --option PLATFORM_SERVICES=logsApi,observabilityApi \
  --config-id my-config \
  --pretty

To change the grant later, run ctxl workers update <worker-id> --option PLATFORM_SERVICES=<names>. In the admin console, set the option in the Managed worker fields.

These services are in the catalog:

Service API
nativeObjectApi Native Objects. Use it for routes the record and attachment capabilities don't cover.
nativeObjectRegistryApi Native Object Registry: object types and their definitions
agentsApi Agents
logsApi Tenant logs
observabilityApi Observability metrics
notificationsApi Notifications (JSON requests only, no event stream)
filesApi Files. Use the attachment capabilities for transfers.
aiGatewayApi AI Gateway, for endpoints beyond the AI capability
aiSearchApi AI Search, for endpoints beyond aiSearch.query

Only the listed services are supported. agentsApi and nativeObjectRegistryApi are available only in environments whose catalog includes them. connectionsApi cannot be granted: a Worker calls a third-party API only through a declared connection alias. See Connections.

Send a Request

Pass the service name, the HTTP method, and the path. The path starts with / and includes the API version and any URL-encoded query string. Optional parameters are body (a JSON value), headers, responseType (json or text), and retryUnauthorized.

const response = await context.services!.request("logsApi", "POST", "/api/v1/$page/logs", {
  body: { pageSize: 10 },
})
if (response.status !== 200) throw new Error(`Logs returned ${response.status}`)
const page = response.body as { items?: unknown[] }

The reply is { status, headers, body }:

  • status is the backend's HTTP status. A 4xx or 5xx from the backend is a reply, not a failure. Check it.
  • headers has only content-type, etag, retry-after, and x-request-id.
  • body is parsed JSON by default, or null for an empty body. With responseType: "text" it is the text. A backend error or redirect that isn't JSON is returned as text with its status.

A redirect is returned as its 3xx status. The host does not follow it.

Set the Options

The optional parameters are spelled for each language:

Language Options
TypeScript An object: { body, headers, responseType, retryUnauthorized }
Rust ServicesRequestOptions { body, headers, response_type, retry_unauthorized, ..Default::default() }. Each field is an Option; body and headers are serde_json::Value.
Go &worker.ServicesRequestOptions{Body, Headers, ResponseType, RetryUnauthorized}, or nil. The reply is decoded into the pointer you pass last.
Python Keyword arguments: body=, headers=, response_type=, retry_unauthorized=

Update a Native Object Record with a Hash Guard

Prefer records.patch for this. When you need a Native Object route that has no typed capability, send the hash you read in x-if-hash-match. Native Object ignores the standard if-match header. A stale hash returns 412, which is a reply, not a failure:

const response = await context.services!.request("nativeObjectApi", "PATCH", `/api/v1/orders/${orderId}`, {
  headers: { "x-if-hash-match": recordHash },
  body: [{ op: "set", path: "/status", value: "processed" }],
})
if (response.status === 412) {
  // Someone changed the record. Read it again before you retry.
}

Raw Platform Call

services.request is also a raw platform call, with the same parameters as one object. See Raw Platform Calls:

TypeScript
const reply = await context.platform!.call("services.request", {
  service: "logsApi", method: "POST", path: "/api/v1/$page/logs", body: { pageSize: 10 },
})

Headers

Your code can add only these headers: accept, accept-language, content-type, if-match, x-if-hash-match, if-none-match, if-modified-since, if-unmodified-since, prefer, idempotency-key, and x-request-id. content-type must be a JSON type, such as application/json or application/merge-patch+json. The host sets the authorization, tenant, and correlation headers. Any other header is refused with validation (header-not-allowed).

Limits and Retries

  • A request body can be at most 1 MiB of JSON. A response can be at most 1 MiB.
  • A request can have at most 32 added headers, in at most 8 KiB.
  • Each request must finish within 20 seconds, and within the invocation's own deadline.
  • The host retries once after a 401 with a renewed token, for GET, HEAD, and OPTIONS only. For other methods, pass retryUnauthorized: true, and only when sending the request twice is safe.
  • The host does not retry a dropped connection, a 429, or a 5xx.
  • A failed or timed-out write can have taken effect. The failure has effectMayHaveOccurred. Check the result before you retry.

Binary and multipart bodies, server-sent events, WebSockets, and streaming are not supported. Use the attachment, cloud storage, and AI capabilities for large data.

Worker Identity

The host chooses the credentials from the service, never from your request:

Service Credentials
nativeObjectApi and aiSearchApi The tenant's managed Native Object connection
Every other service The Worker's own OAuth client

Worker identity uses the tenant-wide platform OAuth client. The host manages its tokens, and each backend applies its authentication and authorization checks to that identity. PLATFORM_SERVICES allows calls through services.request; it does not change the identity's backend permissions. The host never falls back to other credentials.

If a request returns 401 or 403, inspect the backend's error and confirm the target tenant, service, and resource. If the failure remains unresolved and appears to involve the Worker's managed credentials or permissions, contact Contextual support to investigate.

The same split applies to the typed capabilities. Records, attachments, and AI Search use the managed Native Object connection. AI generation, AI uploads, tool sessions, and loading your bound connections use the Worker's own client.

Native Object Rules

A request to nativeObjectApi must use a route that names a concrete object type, such as /api/v1/orders, /api/v1/$page/orders, or /api/v1/$versions/orders/<record-id>. The host refuses:

  • Routes across all types, such as $versions, $audit-trail, and $attachments without a type, even when the body names a type
  • Connection records (api-configuration), in any case or encoding, in the path or query
  • Revealing secret fields ($secrets)
  • Unknown route prefixes, encoded / or \ separators, and double-encoded paths

When the Worker's Native Object access is limited to specific types or is read-only, every services.request is refused. Use the typed capabilities, which check those restrictions.

Refusals

The host checks each request before it sends anything. A refused request is a PlatformError:

Code and Reason Cause What to Do
authorization, service-not-granted The service is not in PLATFORM_SERVICES. Add it to the option.
authorization, service-not-configured The service is not in this environment's catalog. Contact Contextual support to check whether the service is available.
authorization, service-not-allowed The request goes to the Connections API. Use a declared connection alias.
authorization, native-object-restricted Native Object restrictions are configured for the Worker. Use the typed record capabilities.
authorization, native-object-type-required The Native Object route does not name a concrete type, or is not a known route. Use a route with a type, and query each type separately.
authorization, connection-records The path or query names Connection records. Use a declared connection alias.
validation, header-not-allowed The request adds a header that is not allowed. Remove the header.
validation, content-type-not-json content-type is not a JSON type. Send JSON.
validation, header-limit or payload-too-large Too many headers, or a body over 1 MiB. Reduce the request.

A refusal has retryable false. Catch it and handle it, or let it fail the invocation.

Find a Service's Address

services.resolve returns a service's URL. It needs no grant and gives no access. A service that isn't in the catalog fails with authorization (service-not-configured), so you can check whether an optional service is available:

const { url } = await context.services!.resolve("observabilityApi")