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

HTTP Agent

For sending HTTP requests.

Availability

  • ✓ Generic logic
  • ✗ Aggregator logic

HTTP Request

async http?.get(url, headers, contentType, body, config): Promise<Http.Response>

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

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

JavaScript users can access type Http via global variable Saffron:

const Http = Saffron.Http;

TypeScript users can import it from @fstnetwork/loc-logic-sdk:

import { ..., Http } from @fstnetwork/loc-logic-sdk;
warning

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

await ctx.agents.http?.post(
path,
{},
Http.ContentType.Json,
data,
new Http.Config(true),
);

The agent will 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

Content TypeType
NoneHttp.ContentType.None or "None"
PlainTextHttp.ContentType.PlantText or "PlantText"
JSONHttp.ContentType.Json or "Json"
FormHttp.ContentType.Form or "Form"
warning

PlantText is a typo of PlainText and will be fixed in the next release.

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 url = "https://myservice/api";

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

const response = await ctx.agents.http?.post(
url, // URL
{}, // 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 URL query string

const url = "https://myservice/api";

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

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

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

// read response if needed

Example: header authorization

const url = "https://myservice/api";
const user = "****";
const password = "********";
const scheme = "Basic"; // authorization scheme

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

// use Web API to encode "user:password" to Base64 string
const authToken = btoa(`${user}:${password}`);

// authorization header
const headers = {
Authorization: `${scheme} ${authToken}`,
};

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

const response = await ctx.agents.http?.get(
url,
headers,
Http.ContentType.None,
null,
);

if (response.status === 200) {
// take actions
}

For available HTTP authorization schemes, please refer to here.

Example: POST a file with multipart

const url = "https://myservice/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.`;

// ========== 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 ctx.agents.http?.post(
url,
headers,
Http.ContentType.PlantText,
new TextEncoder().encode(body),
);

// read response if needed

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