HTTP Request and Response Parameter Mapping (Rust)
Overview
When an agent is exposed over HTTP, Golem maps parts of each HTTP request to constructor and method parameters. This skill covers how path segments, query parameters, headers, and request bodies are mapped, which types are supported for each, and how return types map to HTTP responses.
Path Variables
Path variables {var_name} in mount or endpoint paths map to parameters by name:
// Mount path variables → constructor parameters
#[agent_definition(mount = "/api/tasks/{task_name}")]
pub trait TaskAgent {
fn new(task_name: String) -> Self;
// Endpoint path variables → method parameters
#[endpoint(get = "/items/{item_id}")]
fn get_item(&self, item_id: String) -> Item;
}Remaining (catch-all) path variables capture everything after a prefix:
#[endpoint(get = "/files/{*path}")]
fn get_file(&self, path: String) -> FileContent;
// GET .../files/docs/readme.md → path = "docs/readme.md"Catch-all variables can only appear as the last path segment and are not allowed in mount paths.
Query Parameters
Specified in the endpoint path using ?key={var} syntax:
#[endpoint(get = "/search?q={query}&limit={max_results}")]
fn search(&self, query: String, max_results: u64) -> Vec<SearchResult>;
// GET .../search?q=hello&limit=10Header Variables
Map HTTP headers to parameters using the headers(...) block on #[endpoint]:
#[endpoint(
get = "/data",
headers("X-Request-Id" = "request_id", "Authorization" = "token")
)]
fn get_data(&self, request_id: String, token: String) -> Data;Supported Types for Path, Query, and Header Variables
Only these types can be used for parameters bound to path/query/header variables (the value is parsed from the URL/header string):
| Rust Type | Parsed From |
|---|---|
String | Used as-is |
char | Single character |
bool | Parsed from "true" / "false" |
u8, u16, u32, u64 | Parsed as unsigned integer |
i8, i16, i32, i64 | Parsed as signed integer |
f32, f64 | Parsed as floating-point number |
| Enum (unit variants only) | Matched against known case names |
For query parameters and headers only (not path variables), two additional wrapper types are supported:
| Rust Type | Behavior |
|---|---|
Option<T> (where T is a supported type above) | Optional — absent query param or header produces None |
Vec<T> (where T is a supported type above) | Repeated query params or comma-separated header values |
All other types (structs, tuples, enums with data, HashMap, etc.) can only be used as body parameters.
POST Request Body Mapping
User-supplied method parameters not bound to path variables, query parameters, or headers are body parameters. Ordinary structured parameters are populated from the JSON request body:
#[endpoint(post = "/items/{id}")]
fn update_item(&mut self, id: String, name: String, count: u64) -> Item;
// POST .../items/123
// Body: { "name": "Widget", "count": 5 }
// → id from path, name and count from bodyEach ordinary structured body parameter becomes a top-level field in the expected JSON body object. All custom types must derive Schema.
⚠️ Important: Ordinary structured bodies use a JSON object with body parameter names only as keys, even for one parameter.
fn decide(&mut self, decision: String)expects{"decision": "approved"}, not a bare string. A single object parameter namedpayloadalso needs wrapping:{"payload": {"name": "Widget", "count": 5}}, not{"name": "Widget", "count": 5}. Do not include path/query/header parameters. Unstructured text and binary parameters instead consume the raw body; see below.
CLI positional invocation is different: pass one argument per user-supplied method parameter in signature order, including parameters bound to path/query/header values over HTTP. Skip host-injected Principal fields without a principal value or placeholder. Use Rust native literals for each value, not one JSON object wrapping the full input. A single object parameter is one native struct literal without the HTTP payload wrapper. Exclude self and config parameters. Load golem-invoke-agent-rust for CLI examples and caller-only input rules.
Binary Request and Response Bodies
Use UnstructuredBinary from the SDK for raw binary payloads:
use golem_rust::agentic::UnstructuredBinary;
use golem_rust::AllowedMimeTypes;
// Accepting any binary content type
#[endpoint(post = "/upload/{bucket}")]
fn upload(&self, bucket: String, payload: UnstructuredBinary<String>) -> i64;
// Restricting to specific MIME types
#[derive(AllowedMimeTypes, Clone, Debug)]
pub enum ImageTypes {
#[mime_type("image/gif")]
ImageGif,
#[mime_type("image/png")]
ImagePng,
}
#[endpoint(post = "/upload-image/{bucket}")]
fn upload_image(&self, bucket: String, payload: UnstructuredBinary<ImageTypes>) -> i64;
// Returning binary data
#[endpoint(get = "/download")]
fn download(&self) -> UnstructuredBinary<String>;In the implementation:
fn upload(&self, _bucket: String, payload: UnstructuredBinary<String>) -> i64 {
match payload {
UnstructuredBinary::Url(_) => -1,
UnstructuredBinary::Inline { data, .. } => data.len() as i64,
}
}
fn download(&self) -> UnstructuredBinary<String> {
UnstructuredBinary::Inline {
data: vec![1, 2, 3, 4],
mime_type: "application/octet-stream".to_string(),
}
}Plain Text Request and Response Bodies
Use UnstructuredText from the SDK for raw text/plain payloads. Like
UnstructuredBinary, a method using UnstructuredText may have only one body
parameter and that parameter cannot be bound to a path/query/header/mount
variable. The body is decoded as UTF-8.
use golem_rust::agentic::{AnyLanguage, UnstructuredText};
use golem_rust::AllowedLanguages;
// Accepting any text/plain content (`UnstructuredText` = `UnstructuredText<AnyLanguage>`)
#[endpoint(post = "/notes/{id}")]
fn add_note(&self, id: String, body: UnstructuredText) -> u64;
// Restricting to specific language codes
#[derive(AllowedLanguages, Clone, Debug)]
pub enum Languages {
#[code("en")]
En,
#[code("de")]
De,
}
#[endpoint(post = "/translate/{id}")]
fn translate(&self, id: String, body: UnstructuredText<Languages>) -> String;
// Returning text/plain
#[endpoint(get = "/notes/{id}")]
fn get_note(&self, id: String) -> UnstructuredText;HTTP-level rules:
- The request must have either no
Content-Type,text/plain, ortext/plain; charset=utf-8(case-insensitive). Any other content type is rejected with415 Unsupported Media Type. Content-Languageis always optional, even whenAllowedLanguagesis restricted. If present, it must be a single value (multi-valued or comma-separated headers are rejected with400 Bad Request).- When restricted, the supplied
Content-Languageis matched case-insensitively against the allowed list; otherwise415 Unsupported Media Type. - A non-UTF-8 request body is rejected with
400 Bad Request. Content-Languagecannot also be bound as an endpoint header parameter when the body isUnstructuredText— that header is reserved for declaring the body language.
In the implementation:
fn add_note(&self, _id: String, body: UnstructuredText) -> u64 {
match body {
UnstructuredText::Url(_) => 0,
UnstructuredText::Text { text, .. } => text.len() as u64,
}
}
fn get_note(&self, _id: String) -> UnstructuredText {
UnstructuredText::from_inline("hello", AnyLanguage::new("en"))
}The response is sent as Content-Type: text/plain; charset=utf-8. If the
returned UnstructuredText::Text has a language_code, it is forwarded as
the Content-Language response header.
Return Type to HTTP Response Mapping
| 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 | Raw binary with Content-Type (default application/octet-stream) |
UnstructuredText<L> | 200 OK | text/plain; charset=utf-8 (+ optional Content-Language) |
UnstructuredBinary::Url / UnstructuredText::Url | 307 Temporary Redirect | Location = the URL |
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 (or a redirect), not as JSON:
// 200 raw bytes / 404 when missing / 500 with JSON `E`
#[endpoint(get = "/files/{id}")]
fn download(&self, id: String) -> Result<Option<UnstructuredBinary<String>>, ErrorResponse>;Data Type to JSON Mapping
| Rust Type | JSON Representation |
|---|---|
String | JSON string |
u8–u64, i8–i64 | JSON number (integer) |
f32, f64 | JSON number (float) |
bool | JSON boolean |
Vec<T> | JSON array |
Struct (with Schema) | JSON object (camelCase field names) |
Option<T> | value or null |
Result<T, E> | value (see response mapping above) |
| Enum (unit variants) | JSON string |
| Enum (with data) | JSON object with tag |
HashMap<K, V> | JSON array of [key, value] tuples |
Related Guides
- Load
golem-add-http-endpoint-rustfor the high-level workflow of defining and mounting HTTP endpoints on an agent