Template Functions
Reading Function Signatures
The function signatures below borrow from TypeScript to describe the arguments a function accepts and the value it returns:
f(arg1: boolean, arg2: string[], arg3?: string): bytes
The function f
accepts two required positional arguments (arg1
and arg2
) and one optional keyword argument (arg3
), and returns a bytes
.
Types
value
is the top-level type. It represents any template value.
The following types are scalar (i.e. not collections):
boolean
float
integer
string
bytes
Array types accept an array of a single type: string[]
accepts ["a", "b", "c"]
but not ["a", 1, false]
.
Type unions allow values that match any of the members: "a" | "b"
accepts the string "a"
or the string "b"
.
Some functions define custom types such as JsonPath
, which are generally a narrowing of the string
type. These will be described on a case-by-case basis in the function descriptions.
Arguments
Arguments with a ?
are optional keyword arguments. Those without ?
are required positional arguments. See Arguments for more.
Functions
base64
base64(value: bytes, decode?: boolean): bytes
Encode or decode content to/from base64.
Parameters
decode
: Decode the input from base64 to its original value instead of encoding it to base64
Errors
- If
decode=true
and the string is not valid base64
Examples
{{ base64("test") }} => "dGVzdA=="
{{ base64("dGVzdA==", decode=true) }} => "test"
boolean
boolean(value: value): boolean
Convert a value to a boolean. Empty values such as 0
, ""
or []
convert to false
. Anything else converts to true
.
Parameters
value
: Value to convert
Examples
{{ boolean(null) }} => false
{{ boolean(0) }} => false
{{ boolean(1) }} => true
{{ boolean('') }} => false
{{ boolean('0') }} => true
{{ boolean([]) }} => false
{{ boolean([0]) }} => true
command
command(command: string[], cwd?: string, stdin?: bytes): bytes
Run a command in a subprocess and return its stdout output. While the output
type is bytes
, in most cases you can use it interchangeably as a
string.
Parameters
command
: Command to run, in the form[program, arg1, arg2, ...]
cwd
: Directory to execute the subprocess in. Defaults to the directory containing the collection file. For example, if the collection is/data/slumber.yml
, the subprocess will execute in/data
regardless of where Slumber is invoked from. The given path will be resolved relative to that default.stdin
: Data to pipe to the subprocess's stdin
Errors
- If the command fails to initialize (e.g. the program is unknown)
- If the subprocess exits with a non-zero status code
Examples
{{ command(["echo", "hello"]) }} => "hello\n"
{{ command(["grep", "1"], stdin="line 1\nline2") }} => "line 1\n"
command
is commonly paired withtrim
to remove trailing newlines from command output:{{ command(["echo", "hello"]) | trim() }}
concat
concat(elements: string[]): string
Concatenate any number of strings together
Parameters
elements
: Strings to concatenate together. Any non-string values will be stringified
Examples
{{ concat(['My name is ', name, ' and I am ', age]) }} => "My name is Ted and I am 37"
{{ file("data.json") | jsonpath("$.users[*].name") | concat() }} => Concatenate all names in the JSON together
debug
debug(value: value): value
Print a value to stdout, returning the same value. This isn't very useful in the TUI because stdout gets clobbered, but it can be helpful for debugging templates with the CLI.
Parameters
value
: The value to print and return
Examples
{{ debug("hello") }} => "hello" (also prints "hello" to stdout)
{{ file("data.json") | debug() | jsonpath("$.data") }} => Extract data field and print intermediate result
env
env(variable: string): string
Get the value of an environment variable, or ""
if not set.
Parameters
variable
: Name of the environment variable to read
Examples
{{ env("HOME") }} => "/home/username"
{{ env("NONEXISTENT") }} => null
file
file(path: string): bytes
Load contents of a file. While the output type is bytes
,
in most cases you can use it interchangeably as a
string. bytes
support means you can also use this to load binary files such as images,
which can be useful for request bodies.
Parameters
path
: Path to the file to read, relative to the collection file (slumber.yml
) in use. A leading~
will be expanded to your home directory ($HOME
).
Errors
- If an I/O error occurs while reading the file (e.g. file missing)
Examples
{{ file("config.json") }} => Contents of config.json file
float
float(value: value): float
Convert a value to a float
Parameters
value
: Value to convert
Errors
- If
value
is a string or byte string that doesn't parse to a float, or an inconvertible type such as an array
Examples
{{ float('3.5') }} => 3.5
{{ float(b'3.5') }} => 3.5
{{ float(3) }} => 3.0
{{ float(null) }} => 0.0
{{ float(false) }} => 0.0
{{ float(true) }} => 1.0
integer
integer(value: value): integer
Convert a value to an int
Parameters
value
: Value to convert
Errors
- If
value
is a string or byte string that doesn't parse to an integer, or an inconvertible type such as an array
Examples
{{ integer('3') }} => 3
{{ integer(b'3') }} => 3
{{ integer(3.5) }} => 3
{{ integer(null) }} => 0
{{ integer(false) }} => 0
{{ integer(true) }} => 1
json_parse
json_parse(value: string): value
Parse a JSON string to a template value.
Parameters
value
: JSON string
Errors
- If
value
is not valid JSON
Examples
{{ json_parse('{"name": "Alice"}') }} => {"name": "Alice"}
# Commonly combined with file() or response() because they spit out raw JSON
{{ file('body.json') | json_parse() }} => {"name": "Alice"}"
{{ response('get_user') | json_parse() }} => {"name": "Alice"}"
This can be used in json
request bodies to create dynamic non-string
values.
body:
type: json
data: {
"data": "{{ response('get_user') | json_parse() }}"
}
This will render a request body like:
{"data": {"name": "Alice"}}
jsonpath
jsonpath(query: JsonPath, value: value, mode?: "auto" | "single" | "array"): value
Transform a JSON value using a JSONPath query. See JSONPath specification or jsonpath.com for query syntax.
This function is most useful when used after a data-providing function such
as file
or response
.
Parameters
value
: JSON value to query. If this is a string or bytes, it will be parsed as JSON before being queried. If it's already a structured value (bool, array, etc.), it will be mapped directly to JSON. This value is typically piped in from the output ofresponse()
orfile()
.query
: JSONPath query stringmode
(default:"auto"
): How to handle multiple results (see table below)
An explanation of mode
using this object as an example:
[{ "name": "Apple" }, { "name": "Kiwi" }, { "name": "Mango" }]
Mode | Description | $.id | $[0].name | $[*].name |
---|---|---|---|---|
auto | If query returns a single value, use it. If it returns multiple, use a JSON array | Error | Apple | ["Apple", "Kiwi", "Mango"] |
single | If a query returns a single value, use it. Otherwise, error. | Error | Apple | Error |
array | Return results as an array, regardless of count. | [] | ["Apple"] | ["Apple", "Kiwi", "Mango"] |
Errors
- If
value
is a string with invalid JSON - If the query returns no results and
mode='auto'
ormode='single'
- If the query returns 2+ results and
mode='single'
Examples
{{ response('get_user') | jsonpath("$.first_name") }} => "Alice"
prompt
prompt(message?: string, default?: string, sensitive?: boolean): string
Prompt the user to enter a text value.
Parameters
message
: Optional prompt message to display to the userdefault
: Optional default value to pre-fill the inputsensitive
: Mask the input while typing. Unlike thesensitive
function, which masks output values, this flag enables masking on the input and output. This means it's redundant to combinesensitive
withprompt
.
Errors
- If the user doesn't give a response
Examples
# Prompt with no message. User may be confused!
{{ prompt() }} => "What do I put here? Help!!"
# Prompts with custom message
{{ prompt(message="Enter your name") }} => "Barry Barracuda"
# Mask input while the user types
{{ prompt(message="Password", sensitive=true) }} => "hunter2"
response
response(recipe_id: string, trigger?: "never" | "no_history" | "always" | Duration): bytes
Load the most recent response body for the given recipe and current profile.
While the output type is bytes
, in most cases you can use it
interchangeably as a
string.
Parameters
recipe_id
: ID (not name) of the recipe to load the response fromtrigger
: When to execute the upstream request
An explanation of trigger
:
Value | Description |
---|---|
"never" | Never trigger. The most recent response in history for the upstream recipe will always be used; error if there is none |
"no_history" | Trigger only if there is no response in history for the upstream recipe |
"always" | Always execute the upstream request |
Duration | Trigger if the most recent response for the upstream recipe is older than some duration, or there is none |
Duration
is a string
in the format <quantity><unit>...
, e.g. "3h"
.
Supported units are:
s
(seconds)m
(minutes)h
(hours)d
(days)
Multiple units can be combined:
"10h5m"
: 10 hours and 5 minutes"3d2s"
: 3 days and 2 seconds
Errors
- If
recipe
isn't in the collection - If there is no request in history and
trigger='never'
- If a request is triggered and failed
Examples
# Use the most recent response body. Error if there are no responses in history
{{ response("login") }} => {"token": "abc123"}
# Re-execute if older than 1 hour
{{ response("login", trigger="1h") }} => {"token": "abc123"}
# Combine with jsonpath for data extraction
{{ response("login") | jsonpath("$.token") }} => "abc123"
response
is commonly combined withjsonpath
to extract data from JSON responses
response_header
response_header(recipe_id: string, header: string, trigger?: "never" | "no_history" | "always" | Duration): bytes
Load a header value from the most recent response for a recipe and the
current profile. While the output type is bytes
,
in most cases you can use it interchangeably as a
string.
Parameters
recipe_id
: ID (not name) of the recipe to load the response fromheader
: Name of the header to extract (case-insensitive)trigger
: When to execute the upstream request vs using the cached response; seeresponse
Errors
- If
recipe
isn't in the collection - If there is no request in history and
trigger='never'
- If a request is triggered and failed
Examples
# Fetch current rate limit, refreshed if older than 5 minutes
{{ response_header("get_rate_limit", "X-Rate-Limit", trigger="5m") }} => Value of X-Rate-Limit response header
select
select(options: string[], message?: string): string
Ask the user to select a value from a list.
Parameters
options
: List of options to choose frommessage
: Descriptive message to display to the user
Errors
- If
options
is empty - If the user doesn't give a response
Examples
{{ select(["dev", "staging", "prod"]) }} => "dev"
# Custom prompt message
{{ select(["GET", "POST", "PUT"], message="HTTP method") }} => "POST"
sensitive
sensitive(value: string): string
Mark a value as sensitive, masking it in template previews. This has no impact on how requests are actually sent, it only prevents sensitive values such as passwords from being displayed in the recipe preview.
Parameters
value
: String to mask
Examples
{{ sensitive("hunter2") }} => "•••••••" (in preview)
string
string(value: value): string
Stringify a value. Any value can be converted to a string except for non-UTF-8 bytes
Parameters
value
: Value to stringify
Errors
- If
value
is a byte string that isn't valid UTF-8
Examples
{{ string('hello') }} => "hello"
{{ string(b'hello') }} => "hello"
{{ string([1, 2, 3]) }} => "[1, 2, 3]"
trim
trim(value: string, mode?: "start" | "end" | "both"): string
Trim whitespace from the beginning and/or end of a string.
Parameters
value
: String to trim (typically piped in from a previous function with|
)mode
(default:"both"
): Section of the string to trim
Examples
{{ trim(" hello ") }} => "hello"
{{ trim(" hello ", mode="start") }} => "hello "
# Remove trailing newline from command output
{{ command(["echo", "hello"]) | trim() }} => "hello"