Skip to main content
Version: LOC v0.7 (legacy)

HTTP Agent

import { HttpAgent, Http } from "@fstnetwork/loc-logic-sdk";

For sending HTTP requests to specific hosts.

Availability

  • ✓ Generic logic
  • ✗ Aggregator logic
info

This agent requires agent configuration. See tutorial or CLI Handbook for details.

Acquire HTTP Client

async HttpAgent.acquire(configurationName: string): Promise<HttpAgentClient>

Returns a HttpAgentClient object based on provided agent configuration name, which includes a host name and may include authentication information for the Authorization header.

The configuration name is the reference field set in Studio or name field set in CLI config files.

Throws an error if the configuration cannot be found.

Example

const httpClient = await HttpAgent.acquire("my-http-configuration");

HTTP Request

Using the HTTP client:

async httpClient.get(path, headers, contentType, body, config): Promise<Http.Response>

Send a GET request. Returns a Http.Response object.

ParameterTypeDescription
pathstringRequest path (no / prefix)
headersRecord<string, string>Request headers (example: { "content-type": "application/json" })
contentTypeHttp.ContentTypeContent types (see below)
bodyUint8Array | nullRequest body (default null for GET)
configHttp.Config | nullAccept invalid certificates. Default: null. If not null, it should be new Http.Config(true).
info

If the agent configuration includes authentication information, the HTTP agent will override user's Authorization header.

warning

If you enable the HTTP agent to accept invalid certificates like this:

httpClient?.post(
path,
{},
Http.ContentType.Json,
data,
new Http.Config(true),
);

The agent will then accept any certificate (including expired ones) from the HTTP endpoint. This introduces significant security risks and should only be used as a last resort.

Content Types

Type: Http.ContentType

Content TypeType
NoneHttp.ContentType.None or "None"
PlainTextHttp.ContentType.PlainText or "PlainText"
JSONHttp.ContentType.Json or "Json"
FormHttp.ContentType.Form or "Form"
tip

To use a custom content type in headers, set contentType to Http.ContentType.None.

HTTP Response

Type: Http.Response

FieldTypeDescription
statusnumberHTTP response status
headersRecord<string, string>Response headers
bodyUint8ArrayResponse body

Example: POST with JSON payload and JSON response

const path = "path/my-api";

const data = {
name: "Arthur Dent",
age: 42,
};

const httpClient = await HttpAgent.acquire("my-http-configuration");

const response = await httpClient?.post(
path, // path
{}, // no extra headers
Http.ContentType.Json, // content type = JSON
new TextEncoder().encode(JSON.stringify(data)), // body (converted to Uint8Array)
);

if (response?.status === 200) {
// if HTTP status = ok
// decode response body (assuming it's JSON)
const data = JSON.parse(new TextDecoder().decode(response?.body));
// read JSON field
const name = data?.name;
// ...
}

Example: GET with path query string

const path = "path/my-api";

const query = {
name: "Arthur-Dent",
age: 42,
};

const httpClient = await HttpAgent.acquire("my-http-configuration");

// convert object to query string, for example:
// ?name=Arthur-Dent&age=42
const queryString = new URLSearchParams(query).toString();

const response = await httpClient?.get(
`${path}?${queryString}`, // path + query string
{},
Http.ContentType.None,
null, // no body
);

// read response if needed

Example: POST a file with multipart

const path = "path/my-api";

const fileName = "test"; // file name or label
const fileFullName = "test.txt"; // full file name
const fileType = "text/plain"; // file content type

// a mock-up text file content
const filedata = `Ford!
there's an infinite number of monkeys outside
who want to talk to us about this script for
Hamlet they've worked out.`;

const httpClient = await HttpAgent.acquire("my-http-configuration");

// ========== start of template ==========

// multipart headers (use task ID as boundary)
const boundaryValue = ctx.task.taskId.id;
const headers = {
"Content-Type": `multipart/form-data; boundary=${boundaryValue}`,
};

// multipart body template
const body =
`--${boundaryValue}` +
"\r\n" +
`Content-Disposition: form-data; name=${fileName}; filename=${fileFullName}` +
"\r\n" +
`Content-Type: ${fileType}` +
"\r\n\r\n" +
`${filedata}` +
"\r\n" +
`--${boundaryValue}--` +
"\r\n";

// ========== end of template ==========

const response = await httpClient?.post(
path,
headers,
Http.ContentType.PlainText,
new TextEncoder().encode(body),
);

// read response if needed

Change the file content type to the one that match your file.

Example: Emit a CloudEvent

Send a HTTP request using the CloudEvents format:

const path = "path/my-api";

const data = {
name: "Arthur Dent",
age: 42,
};

const payload = JSON.stringify(data);

const headers = {
"ce-specversion": "1.0",
"ce-type": "com.example.someevent", // CloudEvent type or label
"ce-time": new Date().toISOString(),
"ce-id": ctx.task.taskId.id, // id = task id
"ce-source": ctx.task.currentLogic.permanentIdentity, // source = logic PID
"Content-Type": "application/json; charset=utf-8",
"Content-Length": String(payload.length),
};

const httpClient = await HttpAgent.acquire("my-http-configuration");

const response = await httpClient?.post(
path,
headers,
Http.ContentType.Json,
new TextEncoder().encode(payload),
);

// read response if needed