# Other Languages

> Call APIs, read and write data, and receive live data from Python, JavaScript, C#, Rust, C++, or any HTTP client.

URL: https://www.trakhound.com/docs/trakhound-framework/clients

Everything on a TrakHound Instance is reached over HTTP, so any language that can send a request can use it: call your APIs, read and write data through Services, and receive live data as it changes. This guide shows each step in several languages. Pick one, and every example on the page switches to it.

## Ways to Reach an Instance

Diagram: People use Apps in a browser and administrators use the admin UI. Applications and scripts call your APIs and the System API. AI assistants connect to the MCP Server. Developers and AI coding tools discover APIs in the API Catalog and llms.txt. Other Instances use the System API through the HTTP Service.

## Before You Start

- A running Instance with the `Greeter` API from the [Quick Start](https://www.trakhound.com/docs/trakhound-framework/getting-started).
- An API key. In the admin UI, open **Security > API Keys**, click **Create Key**, and copy the key (it's only shown once).
- A Service to store data in. The examples use a Router named `quickstart` that sends everything to a `TrakHound.Memory.Service`, so they can't touch your real data. To set it up, add the Memory Service under **Config > Services**, then add a Router named `quickstart` with one Route (`*`) that targets it under **Config > Routers**. To use your own Services instead, leave `routerId` out and the Instance's default Router is used.

Every example reads the Instance's address and your key from two environment variables:

```
TRAKHOUND_URL=http://localhost:8472
TRAKHOUND_API_KEY=thk_...
```

## 1. Set Up a Project

**Python:**

Python 3.9 or later, with the `requests` library:

```
pip install requests
```

**JavaScript:**

Node.js 22 or later. `fetch` is built in, so no packages are needed. Save the examples as `.mjs` files so they can use `await` at the top level.

**C#:**

The .NET 8 SDK or later. `HttpClient` is built in:

```
dotnet new console -n TrakHoundClient
```

**Rust:**

Rust with the `reqwest` crate:

```
cargo new trakhound_client
cd trakhound_client
cargo add reqwest --features blocking,json,query
```

**C++:**

A C++17 compiler, CMake, and [vcpkg](https://vcpkg.io) (included with Visual Studio's **Desktop development with C++** workload). The examples use [cpr](https://github.com/libcpr/cpr), a wrapper around libcurl.

```
// vcpkg.json
{
  "dependencies": [ "cpr" ]
}
```

```
# CMakeLists.txt
cmake_minimum_required(VERSION 3.21)
project(trakhound_client CXX)
set(CMAKE_CXX_STANDARD 17)

find_package(cpr CONFIG REQUIRED)
add_executable(trakhound_client main.cpp)
target_link_libraries(trakhound_client PRIVATE cpr::cpr)
```

From a **Developer Command Prompt for Visual Studio** (which sets `VCPKG_ROOT`), add a vcpkg baseline once, then build. The first build compiles cpr and libcurl, which takes a few minutes:

```
vcpkg x-update-baseline --add-initial-baseline
cmake -B build -S . -DCMAKE_TOOLCHAIN_FILE=%VCPKG_ROOT%/scripts/buildsystems/vcpkg.cmake
cmake --build build --config Release
build\Release\trakhound_client.exe
```

**cURL:**

cURL is included with Windows 10 and later, macOS, and most Linux distributions. The examples use Bash syntax for the environment variables.

## 2. Call an API

Send your key in the `X-API-Key` header (or as `Authorization: Bearer <key>`) and call the API at its route:

**Python:**

```
import os
import requests

BASE_URL = os.environ.get("TRAKHOUND_URL", "http://localhost:8472")

session = requests.Session()
session.headers["X-API-Key"] = os.environ["TRAKHOUND_API_KEY"]

response = session.get(f"{BASE_URL}/greeter", params={"name": "world"})
response.raise_for_status()
print(response.text)
```

**JavaScript:**

```
const BASE_URL = process.env.TRAKHOUND_URL ?? "http://localhost:8472";
const headers = { "X-API-Key": process.env.TRAKHOUND_API_KEY };

async function call(path, params, init = {}) {
  const url = new URL(path, BASE_URL);
  url.search = new URLSearchParams(params);
  const response = await fetch(url, { headers, ...init });
  if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
  return response;
}

const greeting = await call("/greeter", { name: "world" });
console.log(await greeting.text());
```

**C#:**

```
var baseUrl = Environment.GetEnvironmentVariable("TRAKHOUND_URL") ?? "http://localhost:8472";

using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
http.DefaultRequestHeaders.Add("X-API-Key", Environment.GetEnvironmentVariable("TRAKHOUND_API_KEY"));

Console.WriteLine(await http.GetStringAsync("/greeter?name=world"));
```

**Rust:**

```
use reqwest::blocking::Client;
use std::env;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let base_url = env::var("TRAKHOUND_URL").unwrap_or("http://localhost:8472".into());
    let api_key = env::var("TRAKHOUND_API_KEY")?;
    let client = Client::new();

    let greeting = client
        .get(format!("{base_url}/greeter"))
        .query(&[("name", "world")])
        .header("X-API-Key", &api_key)
        .send()?
        .error_for_status()?
        .text()?;
    println!("{greeting}");

    Ok(())
}
```

**C++:**

```
#include <cpr/cpr.h>
#include <cstdlib>
#include <iostream>
#include <string>

int main()
{
    const char* url = std::getenv("TRAKHOUND_URL");
    const std::string baseUrl = url ? url : "http://localhost:8472";
    const cpr::Header headers{{"X-API-Key", std::getenv("TRAKHOUND_API_KEY")}};

    auto greeting = cpr::Get(cpr::Url{baseUrl + "/greeter"}, cpr::Parameters{{"name", "world"}}, headers);
    if (greeting.status_code != 200) { std::cerr << greeting.status_code << " " << greeting.text << "\n"; return 1; }
    std::cout << greeting.text << "\n";
    return 0;
}
```

**cURL:**

```
curl -H "X-API-Key: $TRAKHOUND_API_KEY" "$TRAKHOUND_URL/greeter?name=world"
```

```
Hello, world!
```

## 3. Read and Write Key-Values

The System API's `/_services` routes read and write data through the Instance's Services, the same way modules do with `Client.Services`. Publish a value, read it back, and list the keys in its collection:

**Python:**

```
kv = f"{BASE_URL}/_services/key-values"

session.post(f"{kv}/publish", params={
    "collection": "machines", "key": "M001", "value": "Running", "routerId": "quickstart"
}).raise_for_status()

response = session.get(kv, params={"collection": "machines", "key": "M001", "routerId": "quickstart"})
print("M001 =", response.text)

response = session.get(f"{kv}/list/keys", params={"collection": "machines", "pattern": "*", "routerId": "quickstart"})
print("Keys:", response.json())
```

**JavaScript:**

```
await call("/_services/key-values/publish",
  { collection: "machines", key: "M001", value: "Running", routerId: "quickstart" },
  { method: "POST" });

const value = await call("/_services/key-values", { collection: "machines", key: "M001", routerId: "quickstart" });
console.log("M001 =", await value.text());

const keys = await call("/_services/key-values/list/keys", { collection: "machines", pattern: "*", routerId: "quickstart" });
console.log("Keys:", await keys.json());
```

**C#:**

```
using System.Net.Http.Json;

(await http.PostAsync("/_services/key-values/publish?collection=machines&key=M001&value=Running&routerId=quickstart", null)).EnsureSuccessStatusCode();

Console.WriteLine("M001 = " + await http.GetStringAsync("/_services/key-values?collection=machines&key=M001&routerId=quickstart"));

var keys = await http.GetFromJsonAsync<string[]>("/_services/key-values/list/keys?collection=machines&pattern=*&routerId=quickstart");
Console.WriteLine("Keys: " + string.Join(", ", keys!));
```

**Rust:**

```
let kv = format!("{base_url}/_services/key-values");

client
    .post(format!("{kv}/publish"))
    .query(&[("collection", "machines"), ("key", "M001"), ("value", "Running"), ("routerId", "quickstart")])
    .header("X-API-Key", &api_key)
    .send()?
    .error_for_status()?;

let value = client
    .get(&kv)
    .query(&[("collection", "machines"), ("key", "M001"), ("routerId", "quickstart")])
    .header("X-API-Key", &api_key)
    .send()?
    .error_for_status()?
    .text()?;
println!("M001 = {value}");

let keys: Vec<String> = client
    .get(format!("{kv}/list/keys"))
    .query(&[("collection", "machines"), ("pattern", "*"), ("routerId", "quickstart")])
    .header("X-API-Key", &api_key)
    .send()?
    .error_for_status()?
    .json()?;
println!("Keys: {keys:?}");
```

**C++:**

```
const std::string kv = baseUrl + "/_services/key-values";

auto publish = cpr::Post(cpr::Url{kv + "/publish"},
    cpr::Parameters{{"collection", "machines"}, {"key", "M001"}, {"value", "Running"}, {"routerId", "quickstart"}}, headers);

auto value = cpr::Get(cpr::Url{kv}, cpr::Parameters{{"collection", "machines"}, {"key", "M001"}, {"routerId", "quickstart"}}, headers);
std::cout << "M001 = " << value.text << "\n";

auto keys = cpr::Get(cpr::Url{kv + "/list/keys"},
    cpr::Parameters{{"collection", "machines"}, {"pattern", "*"}, {"routerId", "quickstart"}}, headers);
std::cout << "Keys: " << keys.text << "\n"; // A JSON array, ex. ["M001"]
```

**cURL:**

```
curl -X POST -H "X-API-Key: $TRAKHOUND_API_KEY" \
  "$TRAKHOUND_URL/_services/key-values/publish?collection=machines&key=M001&value=Running&routerId=quickstart"

curl -H "X-API-Key: $TRAKHOUND_API_KEY" \
  "$TRAKHOUND_URL/_services/key-values?collection=machines&key=M001&routerId=quickstart"

curl -H "X-API-Key: $TRAKHOUND_API_KEY" \
  "$TRAKHOUND_URL/_services/key-values/list/keys?collection=machines&pattern=*&routerId=quickstart"
```

```
M001 = Running
Keys: ["M001"]
```

Tables, Blobs, Messages, and Message Queues have routes of their own under `/_services`. They're listed, with their parameters, in the System API's OpenAPI documents (see [step 5](https://www.trakhound.com/docs/trakhound-framework/clients#openapi)).

## 4. Receive Live Data

Subscribe routes stream data as it changes. Request one with `Accept: text/event-stream` to receive **Server-Sent Events**, which any HTTP client can read. This subscribes to the status of every machine:

**Python:**

```
response = requests.get(
    f"{BASE_URL}/_services/messages/subscribe",
    params={"topic": "machines/+/status", "routerId": "quickstart"},
    headers={"X-API-Key": os.environ["TRAKHOUND_API_KEY"], "Accept": "text/event-stream"},
    stream=True,
)
response.raise_for_status()

lines = []
for line in response.iter_lines(decode_unicode=True):
    if line.startswith("data:"):
        lines.append(line[5:].removeprefix(" "))
    elif line == "" and lines:
        # Each event is a Message: Topic, Retain, QoS, Timestamp, a blank line, then the Content
        topic, content = lines[0], "\n".join(lines[5:])
        print(f"{topic} = {content}")
        lines = []
```

**JavaScript:**

```
const url = new URL("/_services/messages/subscribe", BASE_URL);
url.search = new URLSearchParams({ topic: "machines/+/status", routerId: "quickstart" });

const response = await fetch(url, {
  headers: { "X-API-Key": process.env.TRAKHOUND_API_KEY, "Accept": "text/event-stream" },
});

let buffer = "";
for await (const chunk of response.body.pipeThrough(new TextDecoderStream())) {
  buffer += chunk;
  let end;
  while ((end = buffer.indexOf("\n\n")) >= 0) {
    const event = buffer.slice(0, end);
    buffer = buffer.slice(end + 2);
    const data = event.split("\n").filter(l => l.startsWith("data:")).map(l => l.slice(5).replace(/^ /, ""));
    if (data.length === 0) continue; // a comment, ex. ": connected"
    // Each event is a Message: Topic, Retain, QoS, Timestamp, a blank line, then the Content
    console.log(`${data[0]} = ${data.slice(5).join("\n")}`);
  }
}
```

**C#:**

```
var request = new HttpRequestMessage(HttpMethod.Get, "/_services/messages/subscribe?topic=machines/%2B/status&routerId=quickstart");
request.Headers.Add("Accept", "text/event-stream");

using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();

using var reader = new StreamReader(await response.Content.ReadAsStreamAsync());
var data = new List<string>();
while (await reader.ReadLineAsync() is string line)
{
    if (line.StartsWith("data:")) data.Add(line[5..].TrimStart(' '));
    else if (line == "" && data.Count > 0)
    {
        // Each event is a Message: Topic, Retain, QoS, Timestamp, a blank line, then the Content
        Console.WriteLine($"{data[0]} = {string.Join("\n", data.Skip(5))}");
        data.Clear();
    }
}
```

**Rust:**

Read the response body line by line, as in the Python and C# examples: collect the `data:` lines until a blank line, and each group is one Message. With `reqwest`'s blocking client, wrap the response in a `std::io::BufReader` and use `lines()`.

**C++:**

Use `cpr::Get` with a `cpr::WriteCallback` to receive the body as it arrives, then split it into events on blank lines, as in the Python and C# examples.

**cURL:**

```
curl -N -H "X-API-Key: $TRAKHOUND_API_KEY" -H "Accept: text/event-stream" \
  "$TRAKHOUND_URL/_services/messages/subscribe?topic=machines/%2B/status&routerId=quickstart"
```

While it's running, publish a Message from another terminal:

```
curl -X POST -H "X-API-Key: $TRAKHOUND_API_KEY" -H "Content-Type: text/plain" --data "Running" \
  "$TRAKHOUND_URL/_services/messages/publish?topic=machines/M001/status&routerId=quickstart"
```

```
machines/M001/status = Running
```

Each event's `data:` lines are a Message: its Topic, Retain, QoS, and Timestamp (Unix nanoseconds), a blank line, then the Content. A `: connected` comment is sent first. Server-Sent Events only go from the Instance to the client; for routes that also take input from the client, connect with a WebSocket instead. API endpoints marked `[ApiStream]` work the same way (see [APIs](https://www.trakhound.com/docs/trakhound-framework/apis)).

## 5. Generate a Client

To call larger APIs with typed methods, generate a client from their OpenAPI documents:

| Route | Returns |
| --- | --- |
| `/_developer/catalog` | The APIs, with each API's `id`, route, and the endpoints the caller can use |
| `/_developer/openapi/{id}` | An API's OpenAPI 3.1 document, with its server URL and the API key and Bearer security schemes |
| `/_instances/openapi/services` | The System API's `/_services` routes (other areas are listed at `/_instances/openapi/areas`) |
| `/llms.txt` | The same information as a Markdown index for AI coding tools |

Find the API's `id` in the Catalog, download its document, and generate a client with a tool such as [OpenAPI Generator](https://openapi-generator.tech):

```
curl -H "X-API-Key: $TRAKHOUND_API_KEY" "$TRAKHOUND_URL/_developer/catalog"
curl -H "X-API-Key: $TRAKHOUND_API_KEY" -o greeter.json "$TRAKHOUND_URL/_developer/openapi/<id>"

openapi-generator-cli generate -i greeter.json -g python -o greeter-client
```

Use `-g typescript-fetch`, `-g csharp`, `-g rust`, `-g cpp-restsdk`, `-g go`, or `-g java` for other languages. The [API Explorer](https://www.trakhound.com/docs/trakhound-framework/api-catalog) App also shows code samples for each endpoint.

## Errors

| Status | Meaning |
| --- | --- |
| 400 | A parameter is missing or invalid. |
| 401 | The resource is protected and the request has no valid key or session. |
| 403 | The key's roles don't allow it. In newer Instances, also a System resource or Service that no profile protects, called from another machine. |
| 404 | The route doesn't exist, or the Service doesn't have what was asked for. |
| 405 | The Router has no Service for that kind of data (ex. no Key-Value Service on the default Router). |
| 413, 429 | The request is too large, or a [Rate Limit](https://www.trakhound.com/docs/trakhound-framework/security#rate-limits) was reached. Wait for `Retry-After`. |
| 503 | The Service's backend can't be reached, or the Instance is still starting (with `Retry-After`). |

> An API key only matters once a [security profile](https://www.trakhound.com/docs/trakhound-framework/security) protects something. Until then, requests succeed with or without one, even with a wrong key, so add a profile before relying on keys.
