The Form-Builder API

HTTP

Use the form.fetch method to make arbitrary HTTP requests at runtime. This is similar to the browser Fetch API, but isn't 1:1 compatible.

Here's a simple example that loads in a list of countries from this JSON file:

let url = "https://prod.static.formulate.dev/docs/flags/flags.json";
let response = await form.fetch(url);
let choices = JSON.parse(response.text).map(c => ({value: c.Code, label: c.Name}));
await form.select("What country are you from?", choices, {single: true});

Which generates a form that looks like:

Restrictions

Your Formulate script runs in a secure browser sandbox, and as such some restrictions and caveats apply to the use of fetch:

  • You're only able to retrieve the entire response body as a string using the text key, as demonstrated above. Streaming responses and binary response bodies are not supported at the moment.
  • Your request will fail if a CORS preflight check doesn't succeed.
  • Non-2XX responses do not throw an exception. Your code has to check the ok or status field in the Response object in order to be resilient to HTTP errors.

Request Options

In addition to a URL, you can pass an options object to fetch like so:

await form.fetch('https://example.com/', {method: 'POST'});

Here's a full list of supported options:

Option Type
method string The HTTP method to use. One of GET, POST, PUT, DELETE, OPTIONS
headers object HTTP request headers
body string HTTP request body
redirect string Control redirect behavior on a 3xx response. One of follow, error, manual
referrer string HTTP Referer
integrity string Set the subresource integrity value

Return Value

A call to form.fetch() returns a Response, which contains:

Option Type
text string The response body, serialized to a string
headers object HTTP response headers
url string The URL of the response
ok boolean Indicates whether the response was successful (status in the range 200 – 299) or not
redirected boolean Indicates whether or not the response is the result of a redirect
status number The status code of the response
statusText string The status message corresponding to the status code. (e.g., OK for 200).
type sting The type of the response (e.g., basic, cors).