> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://apidocs.polytomic.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://apidocs.polytomic.com/_mcp/server.

# Execute Harbor Saved Query

POST https://app.polytomic.com/api/harbors/{harbor_id}/saved-queries/{saved_query_id}/execute
Content-Type: application/json

Submits the current published Harbor saved query for asynchronous reader-only execution.

Use a Harbor-bound scoped credential with query access to the Harbor's backing
Connection. Administrator credentials cannot submit executions here. Saved
queries require a Polytomic-managed Harbor.

Polytomic selects the current published revision while processing your request.
The response identifies that exact immutable revision. Selection happens before
Polytomic accepts the execution. Drafts, unpublished queries, and archived
queries are unavailable for selection. You cannot select a historical revision
or supply SQL through this endpoint.

> ⚠️ Concurrent publication changes
>
> Publishing, unpublishing, or archiving a saved query after selection does not
> change the selected revision. An in-flight request may still be accepted and
> execute that revision. Unpublishing or archiving does not cancel in-flight
> requests or queued executions. Query access is checked again before execution
> and result retrieval.

Parameter values are bound separately from SQL. Omitted parameters use the
published `default_value`, never draft validation values. An omitted optional
parameter without a default binds SQL `NULL`. Required parameters allow omission
when a default exists, but reject explicit `null` even with a default. Missing
required values without defaults, explicit `null` for required parameters,
unknown parameter names, and invalid scalar types return
`422 Unprocessable Entity` without accepting an execution. Execution requires
reader credentials and never falls back to writer credentials.

For report windows, define parameters with `required: true` and a
`default_value`, such as `7` for a `days` parameter. This allows omission while
preventing explicit `null` from turning a time filter into a SQL `NULL`
comparison.

To archive a saved query through REST, use
[`DELETE /api/harbors/{harbor_id}/saved-queries/{saved_query_id}`](../../../../../../api-reference/harbors/delete-saved-query).
Unpublish is available only through the GraphQL `unpublishHarborSavedQuery`
mutation, not a REST endpoint.

## Results

The response returns a task ID with status `created`, not result rows. Poll
[`GET /api/queries/{id}`](../../../../../../api-reference/query-runner/get-query) using a credential
from the same Harbor profile. Query access is checked again before execution and
result retrieval. Stop polling at `done`, `failed`, or `unknown`; `unknown` means
execution started but no durable terminal result is available.

Results and detailed failure information expire after 24 hours. Use the
`expires` field and follow `links.next` to retrieve additional result pages.

## Harbor Activity

Send a new nonzero UUID in `X-Polytomic-Activity-Request-ID`. Missing or invalid
IDs return `400 Bad Request`. Reusing a consumed ID returns `409 Conflict` and
does not create another execution.

You may omit `X-Polytomic-Harbor-Session` for direct REST requests. If supplied,
the session must be active and bound to your credential and Harbor.

Polytomic records `query.submitted` atomically with acceptance. The event
identifies the saved query, immutable revision, published version, and bounded
name snapshot. SQL, parameter values and defaults, column names, and result rows
remain outside Activity metadata. If Activity persistence is unavailable, the
request returns `503 Service Unavailable` without accepting an execution.

`query.started` records provider invocation. `query.succeeded` means results are
available for authorized retrieval, not that you have consumed them.

Reference: https://apidocs.polytomic.com/api-reference/harbors/execute-saved-query

## Authentication

- `Authorization` header (bearer token, required) — Bearer user API key
- `Authorization` header (basic auth, required) — Basic organization-scoped API key

## Request

### Path parameters

- `harbor_id` (string, required) — Unique identifier of the Harbor.
- `saved_query_id` (string, required) — Unique stable identifier of the saved query.

### Headers

- `X-Polytomic-Harbor-Session` (string, optional)
- `X-Polytomic-Activity-Request-ID` (string, optional)

### Body (application/json)

This endpoint expects an ExecuteHarborSavedQueryRequest.

- `parameters` (map from string to any, optional) — Named JSON scalar overrides for declared parameters. Omission uses published default_value, or SQL NULL for optional parameters without a default. Required parameters reject explicit null even with a default; without a default they also reject omission. Unknown names and invalid types are rejected.

## Response

### 200

OK

- `data` (ExecuteHarborSavedQueryEnvelopeData, optional)

## Errors

### 400 Bad Request Error

Bad Request

- `key` (string, optional)
- `message` (string, optional)
- `metadata` (map from string to any, optional)
- `status` (integer, optional)

### 403 Forbidden Error

Forbidden

- `key` (string, optional)
- `message` (string, optional)
- `metadata` (map from string to any, optional)
- `status` (integer, optional)

### 404 Not Found Error

Not Found

- `key` (string, optional)
- `message` (string, optional)
- `metadata` (map from string to any, optional)
- `status` (integer, optional)

### 409 Conflict Error

Conflict

- `key` (string, optional)
- `message` (string, optional)
- `metadata` (map from string to any, optional)
- `status` (integer, optional)

### 422 Unprocessable Entity Error

Unprocessable Entity

- `key` (string, optional)
- `message` (string, optional)
- `metadata` (map from string to any, optional)
- `status` (integer, optional)

### 500 Internal Server Error

Internal Server Error

- `key` (string, optional)
- `message` (string, optional)
- `metadata` (map from string to any, optional)
- `status` (integer, optional)

### 503 Service Unavailable Error

Service Unavailable

- `key` (string, optional)
- `message` (string, optional)
- `metadata` (map from string to any, optional)
- `status` (integer, optional)

## Types

### ExecuteHarborSavedQueryEnvelopeData

- `count` (long, optional) — The number of rows returned by the query. This will not be returned until the query completes.
- `error` (string, optional) — Error message if the query failed.
- `expires` (string, optional) — The time at which the query will expire and be deleted. This will not be returned until the query completes.
- `fields` (list of string, optional) — The names of the fields returned by the query. This will not be returned until the query completes.
- `id` (string, optional) — The ID of the query task. Poll GET /api/queries/\{id} until the task reaches the terminal status done, failed, or unknown.
- `results` (list of map from string to any, optional) — The query results, returned as an array of objects.
- `revision_id` (string, optional) — Immutable published revision selected while processing this request, before execution acceptance.
- `saved_query_id` (string, optional) — Stable identifier of the executed saved query.
- `status` (enum, optional)
  - Allowed values: `created`, `running`, `unknown`, `done`, `failed`
- `version` (integer, optional) — Published version of the selected immutable revision.

## Examples

**Request**

```json
{}
```

**Response**

```json
{
  "data": {
    "count": 10,
    "error": "string",
    "expires": "2021-01-01T00:00:00Z",
    "fields": [
      "name",
      "age"
    ],
    "id": "43d893ef-322b-47da-badb-3cf10d13a556",
    "results": [
      {}
    ],
    "revision_id": "248df4b7-aa70-47b8-a036-33ac447e668d",
    "saved_query_id": "248df4b7-aa70-47b8-a036-33ac447e668d",
    "status": "created",
    "version": 1
  }
}
```

**SDK Code**

```python
import requests

url = "https://app.polytomic.com/api/harbors/248df4b7-aa70-47b8-a036-33ac447e668d/saved-queries/248df4b7-aa70-47b8-a036-33ac447e668d/execute"

payload = {}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://app.polytomic.com/api/harbors/248df4b7-aa70-47b8-a036-33ac447e668d/saved-queries/248df4b7-aa70-47b8-a036-33ac447e668d/execute';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://app.polytomic.com/api/harbors/248df4b7-aa70-47b8-a036-33ac447e668d/saved-queries/248df4b7-aa70-47b8-a036-33ac447e668d/execute"

	payload := strings.NewReader("{}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://app.polytomic.com/api/harbors/248df4b7-aa70-47b8-a036-33ac447e668d/saved-queries/248df4b7-aa70-47b8-a036-33ac447e668d/execute")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://app.polytomic.com/api/harbors/248df4b7-aa70-47b8-a036-33ac447e668d/saved-queries/248df4b7-aa70-47b8-a036-33ac447e668d/execute")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://app.polytomic.com/api/harbors/248df4b7-aa70-47b8-a036-33ac447e668d/saved-queries/248df4b7-aa70-47b8-a036-33ac447e668d/execute', [
  'body' => '{}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://app.polytomic.com/api/harbors/248df4b7-aa70-47b8-a036-33ac447e668d/saved-queries/248df4b7-aa70-47b8-a036-33ac447e668d/execute");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://app.polytomic.com/api/harbors/248df4b7-aa70-47b8-a036-33ac447e668d/saved-queries/248df4b7-aa70-47b8-a036-33ac447e668d/execute")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```