Code Examples¶
Complete, production-ready integration examples. Each example executes an engine, polls for results with exponential backoff, and handles errors.
Python¶
import time
import requests
API_BASE = "https://api.xlsxapi.eu"
API_KEY = "acme-insurance_550e8400-e29b-41d4-a716-446655440000"
HEADERS = {"X-API-Key": API_KEY, "Content-Type": "application/json"}
TENANT = "acme-insurance"
ENGINE = "property-calculator"
def execute_engine(inputs: dict, webhook_url: str | None = None) -> dict:
"""Execute an engine and wait for results."""
# Submit job
payload: dict = {"inputs": inputs}
if webhook_url:
payload["webhook_url"] = webhook_url
resp = requests.post(
f"{API_BASE}/jobs/execute/{TENANT}/{ENGINE}",
json=payload,
headers=HEADERS,
)
resp.raise_for_status()
job = resp.json()
job_id = job["job_id"]
# Poll for results (exponential backoff, cap at 15s)
delay = 1.0
while True:
time.sleep(delay)
resp = requests.get(f"{API_BASE}/jobs/{job_id}", headers=HEADERS)
resp.raise_for_status()
result = resp.json()
if result["status"] == "completed":
return result["outputs"]
if result["status"] == "failed":
raise RuntimeError(f"Job failed: {result.get('error_message')}")
delay = min(delay * 2, 15)
def download_file(job_id: str, output_path: str) -> None:
"""Download the filled Excel file for a completed job."""
resp = requests.get(f"{API_BASE}/jobs/{job_id}/download", headers=HEADERS)
resp.raise_for_status()
info = resp.json()
file_resp = requests.get(info["download_url"])
file_resp.raise_for_status()
with open(output_path, "wb") as f:
f.write(file_resp.content)
# Usage
if __name__ == "__main__":
outputs = execute_engine({
"customerAge": 35,
"propertyValue": 500000,
})
print(f"Premium: {outputs['premium']}")
print(f"Deductible: {outputs['deductible']}")
JavaScript / TypeScript¶
const API_BASE = "https://api.xlsxapi.eu";
const API_KEY = "acme-insurance_550e8400-e29b-41d4-a716-446655440000";
const TENANT = "acme-insurance";
const ENGINE = "property-calculator";
interface JobResult {
job_id: string;
status: "pending" | "processing" | "completed" | "failed";
outputs?: Record<string, unknown>;
error_message?: string;
}
async function executeEngine(
inputs: Record<string, unknown>,
webhookUrl?: string
): Promise<Record<string, unknown>> {
// Submit job
const body: Record<string, unknown> = { inputs };
if (webhookUrl) body.webhook_url = webhookUrl;
const execResp = await fetch(
`${API_BASE}/jobs/execute/${TENANT}/${ENGINE}`,
{
method: "POST",
headers: { "X-API-Key": API_KEY, "Content-Type": "application/json" },
body: JSON.stringify(body),
}
);
if (!execResp.ok) {
const err = await execResp.json();
throw new Error(`Execute failed (${execResp.status}): ${err.detail}`);
}
const { job_id } = await execResp.json();
// Poll for results (exponential backoff, cap at 15s)
let delay = 1000;
while (true) {
await new Promise((r) => setTimeout(r, delay));
const statusResp = await fetch(`${API_BASE}/jobs/${job_id}`, {
headers: { "X-API-Key": API_KEY },
});
if (!statusResp.ok) {
throw new Error(`Poll failed (${statusResp.status})`);
}
const result: JobResult = await statusResp.json();
if (result.status === "completed") return result.outputs!;
if (result.status === "failed") {
throw new Error(`Job failed: ${result.error_message}`);
}
delay = Math.min(delay * 2, 15000);
}
}
// Usage
const outputs = await executeEngine({
customerAge: 35,
propertyValue: 500000,
});
console.log(`Premium: ${outputs.premium}`);
C# / .NET¶
using System.Net.Http.Json;
using System.Text.Json;
public class XlsxApiClient
{
private readonly HttpClient _client;
private readonly string _tenant;
private readonly string _engine;
public XlsxApiClient(string apiKey, string tenant, string engine)
{
_client = new HttpClient
{
BaseAddress = new Uri("https://api.xlsxapi.eu")
};
_client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
_tenant = tenant;
_engine = engine;
}
public async Task<JsonElement> ExecuteAsync(
Dictionary<string, object> inputs,
string? webhookUrl = null)
{
// Submit job
var payload = new Dictionary<string, object> { ["inputs"] = inputs };
if (webhookUrl != null) payload["webhook_url"] = webhookUrl;
var resp = await _client.PostAsJsonAsync(
$"/jobs/execute/{_tenant}/{_engine}", payload);
resp.EnsureSuccessStatusCode();
var job = await resp.Content.ReadFromJsonAsync<JsonElement>();
var jobId = job.GetProperty("job_id").GetString()!;
// Poll for results
var delay = 1000;
while (true)
{
await Task.Delay(delay);
var result = await _client
.GetFromJsonAsync<JsonElement>($"/jobs/{jobId}");
var status = result.GetProperty("status").GetString();
if (status == "completed")
return result.GetProperty("outputs");
if (status == "failed")
{
var error = result.GetProperty("error_message").GetString();
throw new Exception($"Job failed: {error}");
}
delay = Math.Min(delay * 2, 15000);
}
}
}
// Usage
var client = new XlsxApiClient(
apiKey: "acme-insurance_550e8400-...",
tenant: "acme-insurance",
engine: "property-calculator"
);
var outputs = await client.ExecuteAsync(new Dictionary<string, object>
{
["customerAge"] = 35,
["propertyValue"] = 500000
});
Console.WriteLine($"Premium: {outputs.GetProperty("premium")}");
curl (Bash)¶
A complete script that executes an engine and waits for results:
#!/usr/bin/env bash
set -euo pipefail
API_BASE="https://api.xlsxapi.eu"
API_KEY="acme-insurance_550e8400-e29b-41d4-a716-446655440000"
TENANT="acme-insurance"
ENGINE="property-calculator"
# Execute
JOB=$(curl -s -X POST "$API_BASE/jobs/execute/$TENANT/$ENGINE" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{"inputs": {"customerAge": 35, "propertyValue": 500000}}')
JOB_ID=$(echo "$JOB" | python3 -c "import sys,json; print(json.load(sys.stdin)['job_id'])")
echo "Job submitted: $JOB_ID"
# Poll with backoff
DELAY=1
while true; do
sleep "$DELAY"
RESULT=$(curl -s -H "X-API-Key: $API_KEY" "$API_BASE/jobs/$JOB_ID")
STATUS=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['status'])")
case "$STATUS" in
completed)
echo "Results:"
echo "$RESULT" | python3 -m json.tool
exit 0
;;
failed)
echo "Job failed!"
echo "$RESULT" | python3 -m json.tool
exit 1
;;
*)
echo "Status: $STATUS (waiting ${DELAY}s...)"
DELAY=$((DELAY * 2 > 15 ? 15 : DELAY * 2))
;;
esac
done