Trino client REST API#

The REST API allows clients to submit SQL queries to Trino and receive the results. Clients include the CLI, the JDBC driver, and others provided by the community. The preferred method to interact with Trino is to use these existing clients. This document provides details about the API for reference. It can also be used to implement your own client, if necessary.

Find more information about client drivers, client applications, and the client protocol configuration in the client documentation.

HTTP methods#

  • A POST to /v1/statement runs the query string in the POST body, and returns a JSON document containing the query results. If there are more results, the JSON document contains a nextUri URL attribute.

  • A GET to the nextUri attribute returns the next batch of query results.

  • A DELETE to nextUri terminates a running query.

Overview of query processing#

A Trino client request is initiated by an HTTP POST to the endpoint /v1/statement, with a POST body consisting of the SQL query string. The caller may set various Client request headers. The headers are only required in the initial POST request, and not when following the nextUri links.

If the client request returns an HTTP 502, 503, or 504, that means there was an intermittent problem processing request and the client should try again in 50-100 ms. Trino does not generate those codes by itself, but those can be generated by load balancers in front of Trino.

Additionally, if the request returns a 429 status code, the client should retry the request using the Retry-After header value provided.

Any HTTP status other than 200, 429, 502, 503 or 504 means that query processing has failed.

The /v1/statement POST request returns a JSON document of type QueryResults, as well as a collection of response headers. The QueryResults document contains an error field of type QueryError if the query has failed, and if that object is not present, the query succeeded. Important aspects of QueryResults are documented in the following sections.

If the data field of the JSON document is set, it contains a list of the rows of data. The columns field is set to a list of the names and types of the columns returned by the query. Most of the response headers are treated like browser cookies by the client, and echoed back as request headers in subsequent client requests, as documented below.

If the JSON document returned by the POST to /v1/statement does not contain a nextUri link, the query has completed, either successfully or unsuccessfully, and no additional requests need to be made. If the nextUri link is present in the document, there are more query results to be fetched. The client should loop executing a GET request to the nextUri returned in the QueryResults response object until nextUri is absent from the response.

The status field of the JSON document is for human consumption only, and provides a hint about the query state. It cannot be used to tell if the query is finished.

Spooling protocol#

By default a client receives results with the direct protocol: the data field of each QueryResults document holds the rows inline. A client can instead opt in to the spooling protocol, in which larger results are staged to object storage and the client fetches them out of band. The spooling protocol must be enabled and configured on the server; the client requests it per query. For how to enable the spooling protocol in a specific client driver or application, see the client documentation.

Requesting the spooling protocol#

A client opts in by sending the X-Trino-Query-Data-Encoding request header on the initial POST to /v1/statement, with a comma-separated list of the encodings it supports, in order of preference, for example:

X-Trino-Query-Data-Encoding: json+zstd,json+lz4,json

If the server has spooling enabled and supports one of the listed encodings, it responds with the spooling protocol and echoes the selected encoding in the X-Trino-Query-Data-Encoding response header. If the header is absent or no encoding matches, the server falls back to the direct protocol. A client must therefore be prepared to handle both protocols in the response.

Segments in the response#

With the spooling protocol, the data field of QueryResults is an object rather than a list of rows:

"data": {
  "encoding": "json+zstd",
  "segments": [
    {
      "type": "inline",
      "data": "<base64-encoded encoded rows>",
      "metadata": { "rowOffset": 0, "rowsCount": 10, "segmentSize": 1024 }
    },
    {
      "type": "spooled",
      "uri": "https://coordinator.example/v1/spooled/download/<id>",
      "ackUri": "https://coordinator.example/v1/spooled/ack/<id>",
      "metadata": { "rowOffset": 10, "rowsCount": 5000, "segmentSize": 4194304 },
      "headers": {
        "<header-name>": ["<header-value>"]
      }
    }
  ]
}

A segment is one of two types, distinguished by the type field:

  • inline — the rows are embedded directly in the data field of the segment, base64-encoded in the negotiated encoding. No further request is needed.

  • spooled — the rows are staged on object storage. The segment carries a uri to retrieve the data, an ackUri to acknowledge it, and optional headers that must be sent with the retrieval and acknowledgement requests. Both uri and ackUri are opaque absolute URIs that may point at different hosts, so a client must use each as given rather than parsing it or assuming a common host.

Both types carry a metadata object describing the segment. A client decodes segments in order, using the negotiated encoding, to reconstruct the result rows.

Segment metadata attributes#

Attribute

Type

Description

rowOffset

number

Absolute offset of the segment’s first row within the result set.

rowsCount

number

Number of rows in the segment.

segmentSize

number

Size of the segment in bytes, as stored or transferred.

uncompressedSize

number

Size of the segment in bytes after decompression. Present only for compressed encodings.

expiresAt

string

Time after which a spooled segment may no longer be retrievable from storage.

Early pages of a large result are often returned as inline segments even when spooling is requested, because small results do not benefit from spooling. The server controls this with protocol.spooling.inlining.enabled, which defaults to true.

Retrieving a spooled segment#

How a client fetches the data for a spooled segment depends on the server’s protocol.spooling.retrieval-mode. STORAGE is the default, and the other modes change where the data is read from:

Segment retrieval modes#

Mode

Description

Required client network access

STORAGE

The segment uri is a pre-signed object storage URI. The client reads the data directly from storage.

Object storage

COORDINATOR_STORAGE_REDIRECT

The uri points at the coordinator, which responds with a redirect to a pre-signed object storage URI.

Coordinator and object storage

COORDINATOR_PROXY

The uri points at the coordinator, which reads from storage and streams the data back itself.

Coordinator only

WORKER_PROXY

The uri points at the coordinator, which redirects to a worker that streams the data back.

Coordinator and workers

In STORAGE and COORDINATOR_STORAGE_REDIRECT, the client reads from object storage directly, so it must have network access to the configured storage location. In COORDINATOR_PROXY and WORKER_PROXY, the cluster reads from storage on the client’s behalf, so the client does not need storage access.

A spooled segment may include a headers map. These headers are opaque to the client. It must send them unchanged on the retrieval request, and on the acknowledgement request, without interpreting or transforming them.

Acknowledging a segment#

After reading a spooled segment, a client must acknowledge processing with a GET to the segment’s ackUri, sending the same headers that came with the segment. This lets the server release the segment from object storage rather than waiting for TTL-based cleanup.

The ackUri, like the segment uri, is opaque. A client issues the GET to it exactly as provided. An intermediary between the client and Trino, such as a load balancer, router, or Trino Gateway, must forward requests to these URIs so that segment retrieval and acknowledgement reach their destination.

A correct client acknowledges every segment it reads. Whether the server acts on the acknowledgement immediately or falls back to TTL-based cleanup is a server-side decision.

Important QueryResults attributes#

The most important attributes of the QueryResults JSON document returned by the REST API endpoints are listed in this table. For more details, refer to the class io.trino.client.QueryResults in module trino-client in the client directory of the Trino source code.

QueryResults attributes#

Attribute

Description

id

The ID of the query.

nextUri

If present, the URL to use for subsequent GET or DELETE requests. If not present, the query is complete or ended in error.

columns

A list of the names and types of the columns returned by the query.

data

The data attribute contains a list of the rows returned by the query request. Each row is itself a list that holds values of the columns in the row, in the order specified by the columns attribute.

updateType

A human-readable string representing the operation. For a CREATE TABLE request, the updateType is “CREATE TABLE”; for SET SESSION it is “SET SESSION”; etc.

error

If query failed, the error attribute contains a QueryError object. That object contains a message, an errorCode and other information about the error. See the io.trino.client.QueryError class in module trino-client in the client directory for more details.

QueryResults diagnostic attributes#

These QueryResults data members may be useful in tracking down problems:

QueryResults diagnostic attributes#

Attribute

Type

Description

queryError

QueryError

Non-null only if the query resulted in an error.

failureInfo

FailureInfo

failureInfo has detail on the reason for the failure, including a stack trace, and FailureInfo.errorLocation, providing the query line number and column number where the failure was detected.

warnings

List<TrinoWarning>

A usually empty list of warnings.

statementStats

StatementStats

A class containing statistics about the query execution. Of particular interest is StatementStats.rootStage, of type StageStats, providing statistics on the execution of each of the stages of query processing.

Client request headers#

This table lists all supported client request headers. Many of the headers can be updated in the client as response headers, and supplied in subsequent requests, just like browser cookies.

Client request headers#

Header name

Description

X-Trino-User

Specifies the session user. If not supplied, the session user is automatically determined via User mapping.

X-Trino-Original-User

Specifies the session’s original user.

X-Trino-Source

For reporting purposes, this supplies the name of the software that submitted the query.

X-Trino-Catalog

The catalog context for query processing. Set by response header X-Trino-Set-Catalog.

X-Trino-Schema

The schema context for query processing. Set by response header X-Trino-Set-Schema.

X-Trino-Time-Zone

The timezone for query processing. Defaults to the timezone of the Trino cluster, and not the timezone of the client.

X-Trino-Language

The language to use when processing the query and formatting results, formatted as a Java Locale string, for example en-US for US English. The language of the session can be set on a per-query basis using the X-Trino-Language HTTP header.

X-Trino-Trace-Token

Supplies a trace token to the Trino engine to help identify log lines that originate with this query request.

X-Trino-Session

Supplies a comma-separated list of name=value pairs as session properties. When the Trino client runs a SET SESSION name=value query, the name=value pair is returned in the X-Trino-Set-Session response header, and added to the client’s list of session properties. If the response header X-Trino-Clear-Session is returned, its value is the name of a session property that is removed from the client’s accumulated list.

X-Trino-Role

Sets the “role” for query processing. A “role” represents a collection of permissions. Set by response header X-Trino-Set-Role. See CREATE ROLE to understand roles.

X-Trino-Prepared-Statement

A comma-separated list of the name=value pairs, where the names are names of previously prepared SQL statements, and the values are keys that identify the executable form of the named prepared statements.

X-Trino-Transaction-Id

The transaction ID to use for query processing. Set by response header X-Trino-Started-Transaction-Id and cleared by X-Trino-Clear-Transaction-Id.

X-Trino-Client-Info

Contains arbitrary information about the client program submitting the query.

X-Trino-Client-Tags

A comma-separated list of “tag” strings, used to identify Trino resource groups.

X-Trino-Client-Capabilities

A comma-separated list of optional protocol features supported by the client. Supported values include PATH, PARAMETRIC_DATETIME, PARAMETRIC_INTERVAL, NUMBER, VARIANT, VARIANT_BINARY, and SESSION_AUTHORIZATION. PARAMETRIC_INTERVAL enables interval qualifier and precision parameters in type metadata and full-precision day-time values. Without it, interval types use the legacy bare family names and day-time values are rounded to milliseconds. This applies recursively to nested values and type metadata.

X-Trino-Resource-Estimate

A comma-separated list of resource=value type assignments. The possible choices of resource are EXECUTION_TIME, CPU_TIME, PEAK_MEMORY and PEAK_TASK_MEMORY. EXECUTION_TIME and CPU_TIME have values specified as airlift Duration strings The format is a double precision number followed by a TimeUnit string, for example s for seconds, m for minutes, h for hours, etc. “PEAK_MEMORY” and “PEAK_TASK_MEMORY” are specified as airlift DataSize strings, whose format is an integer followed by B for bytes; kB for kilobytes; mB for megabytes, gB for gigabytes, etc.

X-Trino-Extra-Credential

Provides extra credentials to the connector. The header is a name=value string that is saved in the session Identity object. The name and value are only meaningful to the connector.

X-Trino-Query-Data-Encoding

A comma-separated list of the spooling protocol encodings the client supports, in order of preference. If set and supported by the server, results are returned with the spooling protocol; otherwise the server falls back to the direct protocol.

Client response headers#

This table lists the supported client response headers. After receiving a response, a client must update the request headers used in subsequent requests to be consistent with the response headers received.

Client response headers#

Header name

Description

X-Trino-Set-Catalog

Instructs the client to set the catalog in the X-Trino-Catalog request header in subsequent client requests.

X-Trino-Set-Schema

Instructs the client to set the schema in the X-Trino-Schema request header in subsequent client requests.

X-Trino-Set-Authorization-User

Instructs the client to set the session authorization user in the X-Trino-User request header in subsequent client requests. X-Trino-Original-User should also be set.

X-Trino-Reset-Authorization-User

Instructs the client to reset X-Trino-User request header to its original value in subsequent client requests and remove X-Trino-Original-User to reset the authorization user back to the original user.

X-Trino-Set-Original-Roles

Instructs the client to set the roles of the original user in the X-Trino-Original-Roles request header in subsequent client requests.

X-Trino-Set-Session

The value of the X-Trino-Set-Session response header is a string of the form property = value. It instructs the client include session property property with value value in the X-Trino-Session header of subsequent client requests.

X-Trino-Clear-Session

Instructs the client to remove the session property whose name is the value of the X-Trino-Clear-Session header from the list of session properties in the X-Trino-Session header in subsequent client requests.

X-Trino-Set-Role

Instructs the client to set X-Trino-Role request header to the catalog role supplied by the X-Trino-Set-Role header in subsequent client requests.

X-Trino-Added-Prepare

Instructs the client to add the name=value pair to the set of prepared statements in the X-Trino-Prepared-Statement request header in subsequent client requests.

X-Trino-Deallocated-Prepare

Instructs the client to remove the prepared statement whose name is the value of the X-Trino-Deallocated-Prepare header from the client’s list of prepared statements sent in the X-Trino-Prepared-Statement request header in subsequent client requests.

X-Trino-Started-Transaction-Id

Provides the transaction ID that the client should pass back in the X-Trino-Transaction-Id request header in subsequent requests.

X-Trino-Clear-Transaction-Id

Instructs the client to clear the X-Trino-Transaction-Id request header in subsequent requests.

X-Trino-Query-Data-Encoding

The spooling protocol encoding selected by the server, present when the query uses the spooling protocol.

ProtocolHeaders#

Class io.trino.client.ProtocolHeaders in module trino-client in the client directory of Trino source enumerates all the HTTP request and response headers allowed by the Trino client REST API.