Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

HTTP Client

The Http tool provides methods for making HTTP requests.

Usage

Declare the tool with use Http in your agent:

agent ApiClient {
    use Http

    on start {
        let response = try Http.get("https://api.example.com/data");
        print("Status: " ++ str(response.status));
        print("Body: " ++ response.body);
        yield(response.status);
    }

    on error(e) {
        print("Request failed");
        yield(-1);
    }
}

run ApiClient;

Methods

Http.get(url: String) -> HttpResponse

Performs an HTTP GET request.

let response = try Http.get("https://httpbin.org/get");

Http.post(url: String, body: String) -> HttpResponse

Performs an HTTP POST request with a JSON body.

let response = try Http.post(
    "https://httpbin.org/post",
    "{\"key\": \"value\"}"
);

HttpResponse

Both methods return an HttpResponse with the following fields:

FieldTypeDescription
statusIntHTTP status code (e.g., 200, 404, 500)
bodyStringResponse body as text
headersMap<String, String>Response headers

Examples

Fetching JSON Data

agent JsonFetcher {
    use Http
    url: String

    on start {
        let response = try Http.get(self.url);
        if response.status == 200 {
            yield(response.body);
        } else {
            yield("Error: " ++ str(response.status));
        }
    }

    on error(e) {
        yield("Request failed");
    }
}

run JsonFetcher { url: "https://httpbin.org/json" };

Posting Data

agent DataPoster {
    use Http

    on start {
        let payload = "{\"message\": \"Hello from Sage!\"}";
        let response = try Http.post("https://httpbin.org/post", payload);
        yield(response.status);
    }

    on error(e) {
        yield(-1);
    }
}

run DataPoster;

Error Recovery

agent ResilientFetcher {
    use Http
    urls: List<String>

    on start {
        for url in self.urls {
            let response = catch Http.get(url) {
                HttpResponse { status: 0, body: "", headers: {} }
            };
            if response.status == 200 {
                yield(response.body);
                return;
            }
        }
        yield("All URLs failed");
    }
}

run ResilientFetcher {
    urls: ["https://primary.example.com", "https://backup.example.com"]
};

Configuration

VariableDescriptionDefault
SAGE_HTTP_TIMEOUTRequest timeout in seconds30

The HTTP client automatically sets a User-Agent header of sage-agent/{version}.