Adding HTTP Endpoints to a Rust Golem Agent
Overview
Golem agents can be exposed over HTTP using code-first route definitions. This involves:
- Adding a
mountparameter to#[agent_definition] - Annotating trait methods with
#[endpoint(...)] - Adding an
httpApideployment section togolem.yaml(load thegolem-configure-api-domainskill)
Related Skills
| Skill | When to Load |
|---|---|
| golem-http-params-rust | Path/query/header variable mapping, body mapping, supported types, response mapping |
| golem-make-http-request-rust | Making outgoing HTTP requests from agent code, especially when calling other Golem agent endpoints (required for correct JSON body formatting) |
| golem-add-http-auth-rust | Enabling authentication |
| golem-add-cors-rust | Configuring CORS allowed origins |
| golem-configure-api-domain | Setting up httpApi in golem.yaml, security schemes, domain deployments, and subdomain versus domain choices |
Steps
- Add
mount = "/path/{param}"to#[agent_definition(...)] - Add
#[endpoint(get = "/...")](orpost,put,delete) to trait methods - Add
httpApideployment togolem.yaml(seegolem-configure-api-domainskill) - Build and deploy
Mount Path
The mount parameter on #[agent_definition] defines the base HTTP path. Path variables in {braces} map to constructor parameters:
use golem_rust::{agent_definition, agent_implementation, endpoint};
#[agent_definition(mount = "/api/tasks/{task_name}")]
pub trait TaskAgent {
fn new(task_name: String) -> Self;
// methods...
}
Rules:
- Path must start with
/ - On a key mount, every user-supplied constructor parameter must appear as a
{variable}in the mount path (using the parameter name) - On a key mount, every ordinary
{variable}must match a constructor parameter name - Catch-all
{*rest}variables are not allowed in mount paths
Required Agent ID Mounts and Creation
Use an ID mount to address an existing durable, non-router agent without constructor inputs in the URL:
#[agent_definition(
mount = "/tasks/{instance}",
agent_id(path = "instance"),
create_route = "/tasks/create"
)]
For query addressing, use mount = "/tasks" and agent_id(query = "instance"). The ID is required; there is no optional binding or keyed fallback. ID mounts cannot bind constructor fields or combine with phantom_agent or ephemeral mode. The query ID name is reserved from explicit and implicit method query bindings and protocol controls. Keep fresh-per-request phantom_agent and ephemeral lifecycle policies on key mounts.
create_route declares a full exact POST path, not a mount suffix, and requires an ID mount. Only literals and system variables are allowed in this path. Send a JSON object with one field per user-supplied constructor parameter, as an endpoint body has one field per method parameter, for example {"name": "first"}; an optional parameter may be left out. Other fields, such as env, config or keyed, are rejected with 400. The new agent has no key. Route authentication does not grant configuration authority. Use authorized operator REST creation or SDK creation for overrides. Creation inherits mount authentication/CORS, waits for the constructor, and returns 201 Created with agentId/agentFingerprint JSON and an ID-mounted Location. Current HTTP callers have no caller scope, even with authentication, so Idempotency-Key is ignored; retries create new unkeyed agents.
ID selection never creates an agent. File serving supports both key and ID mounts but is lookup-only: missing keys and unknown, deleted, wrong-type or wrong-environment IDs return terminal 404, without creation or handler fallback. Missing files on an existing target retain normal mapping fallback.
Endpoint Annotation
The #[endpoint(...)] attribute marks a trait method as an HTTP endpoint. Specify one HTTP method with its path:
#[endpoint(get = "/items")]
fn list_items(&self) -> Vec<Item>;
#[endpoint(post = "/items")]
fn create_item(&mut self, name: String, count: u64) -> Item;
#[endpoint(put = "/items/{id}")]
fn update_item(&mut self, id: String, name: String) -> Item;
#[endpoint(delete = "/items/{id}")]
fn delete_item(&mut self, id: String);
Endpoint paths are relative to the mount path. A method can have multiple #[endpoint(...)] attributes to expose it under different routes.
For details on how path variables, query parameters, headers, and request bodies map to method parameters, load the golem-http-params-rust skill.
Durable Stream Route Customization
For a method with stream inputs or outputs, add durable_streams(...) inside #[endpoint(...)] to customize its Durable Streams HTTP surface:
#[endpoint(
post = "/events",
durable_streams(
input("input", name = "uploads"),
output(
"$result",
name = "events",
content_type = "application/vnd.example.events"
),
max_concurrent_readers_per_stream = 8,
max_append_requests_per_second_per_stream = 25,
)
)]
fn events(&mut self, input: AgentStream<u8>) -> AgentStream<u8>;
inputandoutputselect canonical top-level stream slots.$resultis the only implicit result selector.namechanges the public URL and OpenAPI name; the canonical name is no longer accepted in the public URL.content_typeis allowed only for a directAgentStream<u8>slot and must be a concrete non-text, non-JSON MIME type without parameters or wildcards. JSON-shaped streams stayapplication/json; do not usetext/plainforAgentStream<String>. SSE still usestext/event-streamand base64 data.- Reader and append limits must be positive and no greater than the installation maximums. Omitted values use the registry installation defaults.
- Limits are maintained per route and worker-service node, not as a cluster-wide quota.
A New Agent per Request
Set phantom_agent = true to create a new agent without a key, with a new agent ID, for each HTTP request, enabling fully parallel processing:
#[agent_definition(mount = "/gateway/{name}", phantom_agent = true)]
pub trait GatewayAgent {
fn new(name: String) -> Self;
// Each HTTP request gets its own agent instance
}
Custom Types
All types used in endpoint parameters and return values must derive Schema:
use golem_rust::Schema;
#[derive(Clone, Schema)]
pub struct Task {
pub id: String,
pub title: String,
pub done: bool,
}
Return Type to HTTP Response Mapping
Golem maps method return types to HTTP status codes and response bodies according to the table below. This mapping is currently not configurable.
| Return Type | HTTP Status | Response Body |
|---|---|---|
| () (unit / no return) | 204 No Content | empty |
| T (any type) | 200 OK | JSON-serialized T |
| Option<T> | 200 OK if Some, 404 Not Found if None | JSON T or empty |
| Result<T, E> | 200 OK if Ok, 500 Internal Server Error if Err | JSON T or JSON E |
| Result<(), E> | 204 No Content if Ok, 500 if Err | empty or JSON E |
| Result<T, ()> | 200 OK if Ok, 500 if Err | JSON T or empty |
| Result<Option<T>, E> | 200 OK if Ok(Some), 404 Not Found if Ok(None), 500 if Err | JSON T, empty, or JSON E |
| UnstructuredBinary<M> | 200 OK (Url → 307 redirect) | Raw binary with Content-Type |
| UnstructuredText<L> | 200 OK (Url → 307 redirect) | text/plain; charset=utf-8 (+ optional Content-Language) |
The value inside Some / Ok follows the same rules as a top-level value: an UnstructuredBinary or UnstructuredText nested in Option<_>, Result<_, E>, or Result<Option<_>, E> is sent as the raw body, not as JSON. A guarded raw download (raw bytes / 404 / JSON error 500):
#[endpoint(get = "/files/{id}")]
fn download(&self, id: String) -> Result<Option<UnstructuredBinary<String>>, ErrorResponse>;
// Implementation
fn download(&self, id: String) -> Result<Option<UnstructuredBinary<String>>, ErrorResponse> {
match id.as_str() {
"missing" => Ok(None), // 404
"pending" => Err(ErrorResponse { error: "pending".to_string() }), // 500, JSON body
_ => Ok(Some(UnstructuredBinary::Inline { // 200, raw bytes
data: vec![1, 2, 3],
mime_type: "image/png".to_string(),
})),
}
}
Complete Example
use golem_rust::{agent_definition, agent_implementation, endpoint, Schema};
#[derive(Clone, Schema)]
pub struct Task {
pub id: String,
pub title: String,
pub done: bool,
}
#[derive(Schema)]
pub struct ErrorResponse {
pub error: String,
}
#[agent_definition(mount = "/task-agents/{name}")]
pub trait TaskAgent {
fn new(name: String) -> Self;
#[endpoint(get = "/tasks")]
fn get_tasks(&self) -> Vec<Task>;
#[endpoint(post = "/tasks")]
fn create_task(&mut self, title: String) -> Task;
#[endpoint(get = "/tasks/{id}")]
fn get_task(&self, id: String) -> Option<Task>;
#[endpoint(post = "/tasks/{id}/complete")]
fn complete_task(&mut self, id: String) -> Result<Task, ErrorResponse>;
}
struct TaskAgentImpl {
name: String,
tasks: Vec<Task>,
}
#[agent_implementation]
impl TaskAgent for TaskAgentImpl {
fn new(name: String) -> Self {
Self { name, tasks: vec![] }
}
fn get_tasks(&self) -> Vec<Task> {
self.tasks.clone()
}
fn create_task(&mut self, title: String) -> Task {
let task = Task {
id: format!("{}", self.tasks.len() + 1),
title,
done: false,
};
self.tasks.push(task.clone());
task
}
fn get_task(&self, id: String) -> Option<Task> {
self.tasks.iter().find(|t| t.id == id).cloned()
}
fn complete_task(&mut self, id: String) -> Result<Task, ErrorResponse> {
match self.tasks.iter_mut().find(|t| t.id == id) {
Some(task) => {
task.done = true;
Ok(task.clone())
}
None => Err(ErrorResponse { error: "not found".to_string() }),
}
}
}
# golem.yaml (add to existing file)
httpApi:
deployments:
local:
- subdomain: my-app # resolves to my-app.localhost:9006 by default
agents:
TaskAgent: {}
Key Constraints
- A
mountpath is required on#[agent_definition]before any#[endpoint]attributes can be used - Key mounts bind user-supplied constructor parameters via mount path variables; ID mounts bind only the agent ID
- Path/query/header variable names must exactly match method parameter names
- Catch-all path variables
{*name}can only appear as the last path segment - The endpoint path must start with
/ - Exactly one HTTP method must be specified per
#[endpoint]attribute - All custom types used in parameters or return values must derive
Schema