> 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.

# Create Harbor Saved Query Draft

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

Creates a stable Harbor saved query with its initial mutable draft.

Saved queries are supported only for Polytomic-managed Harbors whose backing
Connection type is `polytomic_harbor`. Customer-managed Harbor backings return
an unsupported-backing error.

The saved query receives a stable ID, but it remains absent from published
saved-query reads until an administrator publishes its initial draft.

Use `{{parameter_name}}` references in `sql_template`. Each reference must have
one scalar declaration. Validation values and defaults must match the declared
`string`, `number`, `boolean`, `date`, `timestamp`, or `uuid` type.

Unknown JSON fields, including fields inside parameter declarations, return
`400 Bad Request` before the draft is saved. Use `default_value`, not `default`,
for parameter defaults.

When you omit a parameter during execution, Polytomic uses its published
`default_value`, never its draft validation value. An omitted optional parameter
without a default binds SQL `NULL`. A required parameter allows omission when a
default exists, but rejects explicit `null` even with a default.

For a report window, use a required parameter with a default so omission selects
a useful window and explicit `null` is rejected:

```json
{"name": "days", "type": "number", "required": true, "default_value": 7}
```

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

## 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.

### Body (application/json)

This endpoint expects a CreateHarborSavedQueryDraftRequest.

- `name` (string, required) — Human-readable saved-query name. Maximum 200 characters.
- `sql_template` (string, required) — DuckDB SQL template using \{\{name}} references for bound parameters.
- `change_note` (string, optional, nullable) — Optional note copied to the immutable published version.
- `description` (string, optional) — Business definition and usage notes. Maximum 2,000 characters.
- `owner` (string, optional) — Human-readable owner label. Maximum 200 characters.
- `parameters` (list of HarborSavedQueryParameter, optional, nullable) — Typed scalar parameter declarations.
- `validation_values` (map from string to any, optional, nullable) — Author-supplied JSON scalar values used only to validate this draft.

## Response

### 200

OK

- `data` (HarborSavedQueryDraftResponse, 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)

### 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)

## Types

### HarborSavedQueryParameter

- `name` (string, required) — Template parameter name referenced as \{\{start\_date}}.
- `type` (enum, required) — Scalar parameter type.
  - Allowed values: `string`, `number`, `boolean`, `date`, `timestamp`, `uuid`
- `default_value` (any, optional) — JSON scalar used when the parameter is omitted, matching the declared type. Use default_value, not default. Optional parameters without a default bind SQL NULL.
- `required` (boolean, optional) — When true, rejects explicit null during validation and execution and allows omission only when default_value is present.

### HarborSavedQueryDraftResponse

- `change_note` (string, optional, nullable) — Optional draft change note.
- `created_at` (datetime, optional) — When the draft was created.
- `created_by` (string, optional, nullable) — Actor that created the draft. Null for the system actor.
- `created_by_type` (string, optional) — Type of actor that created the draft.
- `description` (string, optional) — Draft business definition.
- `id` (string, optional) — Unique identifier of this mutable draft candidate.
- `name` (string, optional) — Draft name.
- `owner` (string, optional) — Draft owner label.
- `parameters` (list of HarborSavedQueryParameter, optional, nullable) — Draft typed parameter declarations.
- `saved_query_id` (string, optional) — Stable saved-query identifier.
- `sql_template` (string, optional) — Draft SQL template.
- `updated_at` (datetime, optional) — When the draft was last replaced.
- `updated_by` (string, optional, nullable) — Actor that last replaced the draft. Null for the system actor.
- `updated_by_type` (string, optional) — Type of actor that last replaced the draft.
- `validation_values` (map from string to any, optional, nullable) — Author-supplied validation inputs.

## Examples

**Request**

```json
{
  "name": "Monthly revenue",
  "sql_template": "SELECT account_id, sum(amount) AS revenue FROM orders WHERE created_at >= {{start_date}} GROUP BY account_id"
}
```

**Response**

```json
{
  "data": {
    "change_note": "string",
    "created_at": "2024-01-15T09:30:00Z",
    "created_by": "248df4b7-aa70-47b8-a036-33ac447e668d",
    "created_by_type": "string",
    "description": "string",
    "id": "248df4b7-aa70-47b8-a036-33ac447e668d",
    "name": "string",
    "owner": "string",
    "parameters": [
      {
        "name": "start_date",
        "type": "string",
        "default_value": null,
        "required": true
      }
    ],
    "saved_query_id": "248df4b7-aa70-47b8-a036-33ac447e668d",
    "sql_template": "string",
    "updated_at": "2024-01-15T09:30:00Z",
    "updated_by": "248df4b7-aa70-47b8-a036-33ac447e668d",
    "updated_by_type": "string",
    "validation_values": {}
  }
}
```

**SDK Code**

```python
import requests

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

payload = {
    "name": "Monthly revenue",
    "sql_template": "SELECT account_id, sum(amount) AS revenue FROM orders WHERE created_at >= {{start_date}} GROUP BY account_id"
}
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';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"name":"Monthly revenue","sql_template":"SELECT account_id, sum(amount) AS revenue FROM orders WHERE created_at >= {{start_date}} GROUP BY account_id"}'
};

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"

	payload := strings.NewReader("{\n  \"name\": \"Monthly revenue\",\n  \"sql_template\": \"SELECT account_id, sum(amount) AS revenue FROM orders WHERE created_at >= {{start_date}} GROUP BY account_id\"\n}")

	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")

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 = "{\n  \"name\": \"Monthly revenue\",\n  \"sql_template\": \"SELECT account_id, sum(amount) AS revenue FROM orders WHERE created_at >= {{start_date}} GROUP BY account_id\"\n}"

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")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"name\": \"Monthly revenue\",\n  \"sql_template\": \"SELECT account_id, sum(amount) AS revenue FROM orders WHERE created_at >= {{start_date}} GROUP BY account_id\"\n}")
  .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', [
  'body' => '{
  "name": "Monthly revenue",
  "sql_template": "SELECT account_id, sum(amount) AS revenue FROM orders WHERE created_at >= {{start_date}} GROUP BY account_id"
}',
  '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");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"name\": \"Monthly revenue\",\n  \"sql_template\": \"SELECT account_id, sum(amount) AS revenue FROM orders WHERE created_at >= {{start_date}} GROUP BY account_id\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "name": "Monthly revenue",
  "sql_template": "SELECT account_id, sum(amount) AS revenue FROM orders WHERE created_at >= {{start_date}} GROUP BY account_id"
] 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")! 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()
```