# APIs

> Build HTTP APIs with controllers, route attributes, streaming responses, and MCP Tools.

URL: https://www.trakhound.com/docs/trakhound-framework/apis

An API Package provides HTTP endpoints. It is mounted at the route set in its configuration (or the `.defaultRoute` in its manifest), and its controller methods handle requests under that route.

Diagram: The request GET /api/example/M001?units=mm is matched to the API whose configuration route is /api/example, then to the endpoint marked ApiGet with the route {key}. The route value M001 fills the key parameter and the query value mm fills the units parameter. The method returns a TrakHoundApiResponse, which becomes the HTTP response.

## Create an API

```
dotnet new trakhound.api
```

The template creates a controller that inherits from `TrakHoundApiController`:

```
using TrakHound;
using TrakHound.Api;

public class Controller : TrakHoundApiController
{
    [ApiGet]
    public async Task<TrakHoundApiResponse> Get([FromQuery] string name)
    {
        return Ok($"Hello {name}");
    }

    [ApiGet("{key}")]
    public async Task<TrakHoundApiResponse> GetValue([FromRoute] string key)
    {
        var value = await Variables.ReadString(key);
        return Ok(value);
    }

    [ApiPut("{key}")]
    public async Task<TrakHoundApiResponse> PutValue([FromRoute] string key, [FromQuery] string value)
    {
        await Variables.Set(key, value);
        return Ok();
    }
}
```

If this API is configured with the route `/api/example`, the endpoints are:

```
GET  /api/example?name=World
GET  /api/example/{key}
PUT  /api/example/{key}?value=...
```

## Route Attributes

Add an attribute to each method to set its HTTP method and route. The route is relative to the API's route and can contain parameters in braces.

| Attribute | HTTP Method |
| --- | --- |
| `[ApiGet]` | GET |
| `[ApiPost]` | POST |
| `[ApiPut]` | PUT |
| `[ApiDelete]` | DELETE |
| `[ApiPatch]`, `[ApiHead]`, `[ApiOptions]`, `[ApiConnect]`, `[ApiTrace]` | PATCH, HEAD, OPTIONS, CONNECT, TRACE |
| `[ApiStream]` | A streaming endpoint (see below) |

## Parameters

| Attribute | Reads the value from |
| --- | --- |
| `[FromQuery]` | The query string (ex. `?name=World`) |
| `[FromRoute]` | A route parameter (ex. `{key}`) |
| `[FromHeader]` | A request header (ex. `[FromHeader("X-Line")]`, or the parameter name when none is set). Names are case-insensitive, and a missing header leaves the parameter's default |
| `[FromBody]` | The request body. An optional content type can be set (ex. `[FromBody(ContentType = "application/json")]`) |

Headers that carry the caller's credentials (`Cookie`, `Authorization`, `Proxy-Authorization`, `X-API-Key`, `X-TrakHound-Module-Token`, and `token`) are never passed to an API, so it can't act as its caller. Header parameters are listed in the OpenAPI document as `in: header` and left out of MCP Tool inputs. Apps send headers with `Client.Api.Send` and the `Get`, `Post`, `Put`, `Delete`, and `Stream` overloads that take `headers`.

Describe each parameter with `Description`. Descriptions appear in the admin UI, the OpenAPI document, the [API Catalog](https://www.trakhound.com/docs/trakhound-framework/api-catalog), and [MCP Tool](https://www.trakhound.com/docs/trakhound-framework/mcp-server) inputs:

```
[ApiGet("production")]
public async Task<TrakHoundApiResponse> GetProduction(
    [FromQuery(Description = "The first day to include")] DateTime start,
    [FromQuery(Description = "The last day to include")] DateTime end)
```

## Responses

Methods return a `TrakHoundApiResponse`. The controller provides helpers for common status codes. Each accepts nothing, a string (`text/plain`), an object (serialized as JSON), or bytes with a content type.

| Helper | Status Code |
| --- | --- |
| `Ok()` | 200 |
| `Created()` | 201 |
| `Accepted()` | 202 |
| `Redirect(location, statusCode = 303)` | 303 (or the given status code) |
| `BadRequest()` | 400 |
| `NotAuthorized()` | 401 |
| `NotFound()` | 404 |
| `InternalError()` | 500 |
| `File(content, contentType, filename)` | 200 with a file download (bytes or stream) |

## Streaming

A method marked with `[ApiStream]` returns an `ITrakHoundStream<TrakHoundApiResponse>`. Push responses into the stream as data becomes available, and clean up when the client disconnects:

```
[ApiStream]
public async Task<ITrakHoundStream<TrakHoundApiResponse>> Stream()
{
    var timer = new System.Timers.Timer(1000);
    var stream = new TrakHoundStream<TrakHoundApiResponse>();

    timer.Elapsed += (s, args) => stream.Push(Ok(DateTime.Now.ToString("o")));
    timer.Start();

    // Called when the client disconnects
    stream.OnDisposed = () => timer.Dispose();

    return stream;
}
```

Clients connect to a stream endpoint with a WebSocket, or with **Server-Sent Events**: a GET request with `Accept: text/event-stream` (ex. a browser `EventSource`) receives each value as a `data` event. Server-Sent Events only go from the server to the client, so input from the client needs a WebSocket.

```
curl -N -H "Accept: text/event-stream" http://localhost:8472/api/example/stream
```

## MCP Tools

Mark an endpoint with `[ApiMcpTool]` to offer it to AI assistants as a Tool of the Instance's [MCP Server](https://www.trakhound.com/docs/trakhound-framework/mcp-server). Write the `Description` for an AI agent, and only mark endpoints that are safe for an agent to call:

```
[ApiGet("status")]
[ApiMcpTool(Description = "Returns the current status")]
public async Task<TrakHoundApiResponse> GetStatus()
{
    return Ok("OK");
}
```

GET and stream endpoints are read only. Set `ReadOnly = true` on another method that only reads (ex. a POST search), or `Destructive = true` on one that deletes data or affects equipment. See [API Endpoints as Tools](https://www.trakhound.com/docs/trakhound-framework/mcp-server#api-tools).

## Permissions

Add `[TrakHoundPermission("read")]` (one or more) to an endpoint so administrators can control who calls it with security profiles. Each endpoint is a resource named `api:{apiId}:{controllerId}:{endpointId}`. See [Security](https://www.trakhound.com/docs/trakhound-framework/security).

## Controller Properties

| Property | Description |
| --- | --- |
| `Client` | Client used to call other APIs, run Functions, and read and write [Services](https://www.trakhound.com/docs/trakhound-framework/services). |
| `Volume`, `Variables` | The module's [Volume and Variables](https://www.trakhound.com/docs/trakhound-framework/volumes-and-variables). |
| `Configuration` | The API's configuration. Read parameters with `Configuration.GetParameter(name)`. |
| `GetConfigurationVariable(name)` | Reads a [Configuration Variable](https://www.trakhound.com/docs/trakhound-framework/configuration#variables) shared by every configuration in the profile. |
| `Package` | Information about the Package. |
| `InstanceId`, `BaseUrl`, `BasePath` | The Instance ID and the API's base URL and path. |
| `Logger` | Logger for the API. Also available through `Log(level, message)`. |

Override `OnInitialize()` or `OnInitializeAsync()` to run setup code when the controller is created.

## Grouping and Documentation

Use `[TrakHoundApiController(route, name, description)]` on a controller class to set its route, name, and description, and `[TrakHoundApiResponse(statusCode, returnType)]` on a method to describe its responses. This information is shown in the Instance's admin UI Explorer, where endpoints can also be run.

Each API also gets an OpenAPI document at `_api/openapi/{apiId}`, linked from its page in the admin UI. Developers without admin access can find the APIs and endpoints they are allowed to call in the [API Catalog](https://www.trakhound.com/docs/trakhound-framework/api-catalog).

## Configuration

Besides its `route`, an API configuration can set `httpEnabled: false` to serve the API only to other modules inside the Instance, and `mcpTools` to choose which endpoints are MCP Tools. Routes used by the Instance itself (such as `/_admin`) are reserved and can't be used by APIs. See [Configuration](https://www.trakhound.com/docs/trakhound-framework/configuration).
