Skip to Content
How-To GuidesMoonBitHTTP Request and Response Parameter Mapping (MoonBit)

HTTP Request and Response Parameter Mapping (MoonBit)

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:

///| /// A task management agent #derive.agent #derive.mount("/api/tasks/{task_name}") pub(all) struct TaskAgent { task_name : String } ///| fn TaskAgent::new(task_name : String) -> TaskAgent { { task_name } } ///| /// Get an item by ID #derive.endpoint(get="/items/{item_id}") pub fn TaskAgent::get_item(self : Self, item_id : String) -> Item { // task_name from mount path, item_id from endpoint path ... }

Remaining (catch-all) path variables capture everything after a prefix:

#derive.endpoint(get="/files/{*path}") pub fn TaskAgent::get_file(self : 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:

#derive.endpoint(get="/search?q={query}&limit={max_results}") pub fn TaskAgent::search(self : Self, query : String, max_results : UInt64) -> Array[SearchResult] { // GET .../search?q=hello&limit=10 ... }

Header Variables

Map HTTP headers to parameters using #derive.endpoint_header:

#derive.endpoint(get="/data") #derive.endpoint_header("X-Request-Id", "request_id") #derive.endpoint_header("Authorization", "token") pub fn TaskAgent::get_data(self : Self, request_id : String, token : String) -> Data { ... }

Each #derive.endpoint_header maps one header to one method parameter. Duplicate header names (case-insensitive) are not allowed.

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):

MoonBit TypeParsed From
StringUsed as-is
CharSingle character
BoolParsed from "true" / "false"
UInt, UInt64Parsed as unsigned integer
Int, Int64Parsed as signed integer
DoubleParsed 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:

MoonBit TypeBehavior
T? (Option[T], where T is a supported type above)Optional — absent query param or header produces None
Array[T] (where T is a supported type above)Repeated query params or comma-separated header values

All other types (structs, tuples, enums with data, 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:

#derive.endpoint(post="/items/{id}") pub fn TaskAgent::update_item(self : Self, id : String, name : String, count : UInt64) -> Item { // POST .../items/123 // Body: { "name": "Widget", "count": 5 } // → id from path, name and count from body ... }

Each ordinary structured body parameter becomes a top-level field in the expected JSON body object. All custom types must have #derive.golem_schema.

⚠️ Important: Ordinary structured bodies use a JSON object with body parameter names only as keys, even for one parameter. decide(self : Self, decision : String) expects {"decision": "approved"}, not a bare string. A single object parameter named payload also 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 MoonBit 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-moonbit for CLI examples and caller-only input rules.

Raw Text and Binary Bodies

Use @schema.UnstructuredText[L] for raw text/plain and @schema.UnstructuredBinary[M] for raw binary request and response bodies. Each is inline content or a URL reference:

pub(all) enum UnstructuredText[L] { Inline(text~ : String, language~ : String?) Url(String) } pub(all) enum UnstructuredBinary[M] { Inline(bytes~ : Bytes, mime_type~ : String?) Url(String) }

Restrictions are type-level: the type argument implements @schema.AllowedLanguages (languages()) or @schema.AllowedMimeTypes (mime_types()). Use @schema.AnyLanguage / @schema.AnyMimeType for no restriction. There are no #derive.text_languages / #derive.mime_types annotations.

///| pub(all) struct ImageTypes {} ///| impl @schema.AllowedMimeTypes for ImageTypes with fn mime_types() { ["image/png", "image/gif"] } ///| #derive.endpoint(post="/upload/{bucket}") pub fn UploadAgent::upload( self : Self, bucket : String, payload : @schema.UnstructuredBinary[ImageTypes], ) -> Int { match payload { Inline(bytes~, ..) => bytes.length() Url(_) => -1 } } ///| #derive.endpoint(get="/notes/{id}") pub fn UploadAgent::get_note( self : Self, id : String, ) -> @schema.UnstructuredText[@schema.AnyLanguage] { @schema.UnstructuredText::inline("hello", language="en") }
  • Construct values with UnstructuredText::inline(text, language?) / UnstructuredBinary::inline(bytes, mime_type?) or ::url(url).
  • A method with an unstructured body parameter may have only one body parameter, and it cannot be bound to a path/query/header variable.
  • Text request bodies must have no Content-Type, text/plain, or text/plain; charset=utf-8 (otherwise 415); an optional single Content-Language is checked against the allow-list.
  • Responses: text is sent as text/plain; charset=utf-8 with the language as Content-Language; binary uses its MIME type (default application/octet-stream); a Url value is a 307 redirect.

Return Type to HTTP Response Mapping

Return TypeHTTP StatusResponse Body
Unit (no return)204 No Contentempty
T (any type)200 OKJSON-serialized T
T? (Option[T])200 OK if Some, 404 Not Found if NoneJSON T or empty
Result[T, E]200 OK if Ok, 500 Internal Server Error if ErrJSON T or JSON E
Result[Unit, E]204 No Content if Ok, 500 if Errempty or JSON E
Result[T?, E]200 OK if Ok(Some), 404 Not Found if Ok(None), 500 if ErrJSON T, empty, or JSON E
@schema.UnstructuredBinary[M]200 OK (Url → 307 redirect)Raw binary with Content-Type
@schema.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 unstructured value nested in T?, Result[T, E], or Result[T?, E] is sent as the raw body, not as JSON. For example, Result[@schema.UnstructuredBinary[M]?, String] gives raw bytes (200), 404 for Ok(None), and a JSON error (500) for Err.

Data Type to JSON Mapping

MoonBit TypeJSON Representation
StringJSON string
Int, Int64, UInt, UInt64JSON number (integer)
DoubleJSON number (float)
BoolJSON boolean
Array[T]JSON array
Struct (with #derive.golem_schema)JSON object
T? (Option[T])value or null
Result[T, E]value (see response mapping above)
Enum (unit variants)JSON string
Enum (with data, #derive.golem_schema)JSON object with tag
(A, B, ...) (tuple)JSON array

Custom Types

All custom structs and enums used as parameters or return types must be annotated with #derive.golem_schema:

#derive.golem_schema pub(all) enum Priority { Low Medium High } derive(Eq) #derive.golem_schema pub(all) struct TaskInfo { title : String priority : Priority description : String? }

Complete Example

///| /// A REST API agent exposing weather data via HTTP endpoints #derive.agent #derive.mount("/api/{city}/weather") pub(all) struct WeatherAgent { city : String mut last_temperature : Double } ///| fn WeatherAgent::new(city : String) -> WeatherAgent { { city, last_temperature: 0.0 } } ///| /// Get current temperature #derive.endpoint(get="/current?unit={unit}") pub fn WeatherAgent::get_temperature(self : Self, unit : String) -> Double { if unit == "fahrenheit" { self.last_temperature * 9.0 / 5.0 + 32.0 } else { self.last_temperature } } ///| /// Set the temperature #derive.endpoint(post="/set") #derive.endpoint_header("X-Source", "source") pub fn WeatherAgent::set_temperature( self : Self, temperature : Double, source : String, ) -> String { self.last_temperature = temperature "Temperature set to " + temperature.to_string() + " from " + source }