Examples
Worked examples of calling a Gaur consumer from curl, JavaScript, and Python.
Worked, copy-pasteable examples of calling a Gaur consumer. Each one assumes you have a base URL, a consumer slug, and an API key.
Set these once:
GAUR_BASE_URL="https://<base-url>"
GAUR_CONSUMER="<consumer_slug>"
GAUR_API_KEY="<api_key>"Query a contract
Run a structured query against a contract and read the rows.
curl -s -X POST "$GAUR_BASE_URL/v1/api/$GAUR_CONSUMER/query" \
-H "Authorization: Bearer $GAUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contract_name": "product_performance",
"query": {
"dimensions": [{ "name": "ordered_at", "time_grain": "month" }],
"measures": ["revenue_usd"],
"sorts": [{ "field": "ordered_at", "direction": "asc" }],
"limit": 12
}
}'const res = await fetch(
`${process.env.GAUR_BASE_URL}/v1/api/${process.env.GAUR_CONSUMER}/query`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.GAUR_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
contract_name: "product_performance",
query: {
dimensions: [{ name: "ordered_at", time_grain: "month" }],
measures: ["revenue_usd"],
sorts: [{ field: "ordered_at", direction: "asc" }],
limit: 12,
},
}),
},
);
if (!res.ok) {
const err = await res.json();
throw new Error(`${err.code}: ${err.message}`);
}
const { data } = await res.json();
for (const row of data.pagination.items) {
console.log(row);
}import os
import requests
res = requests.post(
f"{os.environ['GAUR_BASE_URL']}/v1/api/{os.environ['GAUR_CONSUMER']}/query",
headers={
"Authorization": f"Bearer {os.environ['GAUR_API_KEY']}",
"Content-Type": "application/json",
},
json={
"contract_name": "product_performance",
"query": {
"dimensions": [{"name": "ordered_at", "time_grain": "month"}],
"measures": ["revenue_usd"],
"sorts": [{"field": "ordered_at", "direction": "asc"}],
"limit": 12,
},
},
)
if not res.ok:
err = res.json()
raise RuntimeError(f"{err['code']}: {err['message']}")
for row in res.json()["data"]["pagination"]["items"]:
print(row)Query with row-level security context
When a contract uses
row-level security,
pass the values it needs in context. Derive these on your trusted backend,
never from the end user.
curl -s -X POST "$GAUR_BASE_URL/v1/api/$GAUR_CONSUMER/query" \
-H "Authorization: Bearer $GAUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contract_name": "product_performance",
"query": { "measures": ["revenue_usd"] },
"context": { "store_id": "STR-008" }
}'const body = {
contract_name: "product_performance",
query: { measures: ["revenue_usd"] },
// store_id comes from the authenticated session, server-side.
context: { store_id: storeIdForCurrentUser },
};
// ...same fetch call as above, with this bodybody = {
"contract_name": "product_performance",
"query": {"measures": ["revenue_usd"]},
# store_id comes from the authenticated session, server-side.
"context": {"store_id": store_id_for_current_user},
}
# ...same requests.post call as above, with json=bodyPage through a large result
Loop while has_next_page is true. See
Pagination.
async function fetchAll(contractName, query) {
const rows = [];
const limit = 100;
let offset = 0;
while (true) {
const res = await fetch(
`${process.env.GAUR_BASE_URL}/v1/api/${process.env.GAUR_CONSUMER}/query`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.GAUR_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
contract_name: contractName,
query: { ...query, limit, offset },
}),
},
);
if (!res.ok) {
const err = await res.json();
throw new Error(`${err.code}: ${err.message}`);
}
const { pagination } = (await res.json()).data;
rows.push(...pagination.items);
if (!pagination.has_next_page) break;
offset += limit;
}
return rows;
}def fetch_all(contract_name, query):
rows = []
limit, offset = 100, 0
while True:
res = requests.post(
f"{os.environ['GAUR_BASE_URL']}/v1/api/{os.environ['GAUR_CONSUMER']}/query",
headers={
"Authorization": f"Bearer {os.environ['GAUR_API_KEY']}",
"Content-Type": "application/json",
},
json={
"contract_name": contract_name,
"query": {**query, "limit": limit, "offset": offset},
},
)
if not res.ok:
err = res.json()
raise RuntimeError(f"{err['code']}: {err['message']}")
pagination = res.json()["data"]["pagination"]
rows.extend(pagination["items"])
if not pagination["has_next_page"]:
break
offset += limit
return rowsStream a chat answer
The chat endpoint returns a server-sent events stream.
Read each data: line as JSON. Pull narrative text from delta.content, and
pull results and chart suggestions from delta.gaur_event. A strict OpenAI
SDK drops gaur_event, so parse the stream yourself.
curl -N -X POST "$GAUR_BASE_URL/v1/api/$GAUR_CONSUMER/chat/completions" \
-H "Authorization: Bearer $GAUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gaur-nlq-v1",
"messages": [{ "role": "user", "content": "Show me weekly revenue trends." }]
}'The -N flag disables buffering, so events print as they arrive.
const res = await fetch(
`${process.env.GAUR_BASE_URL}/v1/api/${process.env.GAUR_CONSUMER}/chat/completions`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.GAUR_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gaur-nlq-v1",
messages: [{ role: "user", content: "Show me weekly revenue trends." }],
}),
},
);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const payload = line.slice(6);
if (payload === "[DONE]") continue;
const delta = JSON.parse(payload).choices?.[0]?.delta ?? {};
if (delta.content) appendNarrative(delta.content);
if (delta.gaur_event) handleGaurEvent(delta.gaur_event);
}
}import json
with requests.post(
f"{os.environ['GAUR_BASE_URL']}/v1/api/{os.environ['GAUR_CONSUMER']}/chat/completions",
headers={
"Authorization": f"Bearer {os.environ['GAUR_API_KEY']}",
"Content-Type": "application/json",
},
json={
"model": "gaur-nlq-v1",
"messages": [{"role": "user", "content": "Show me weekly revenue trends."}],
},
stream=True,
) as res:
for raw in res.iter_lines():
if not raw or not raw.startswith(b"data: "):
continue
payload = raw[6:].decode()
if payload == "[DONE]":
continue
delta = json.loads(payload)["choices"][0].get("delta", {})
if delta.get("content"):
append_narrative(delta["content"])
if delta.get("gaur_event"):
handle_gaur_event(delta["gaur_event"])