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):
booleanfloatintegerstringbytes
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.
Tags
Functions grouped by their application.
array
input
json
number
string
Functions
base64
base64(value: bytes, decode?: boolean): bytes
Encode or decode content to/from base64
Parameters
value: bytes(required): Value to encode or decodedecode: boolean(default =false): Decode the input from base64 to its original value instead of encoding it to base64
Return
bytes
The encoded value (if decode=false) or decoded value (if decode=true)
Errors
- If
decode=trueandvalueis not a valid base64 string
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(required): Value to convert
Return
boolean
Boolean representation of the input
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. Supports streaming of stdout.
Parameters
command: string[](required): Command to run, in the form [program, arg1, arg2, …]cwd: string(default =.): Directory to execute the subprocess in. The given path will be resolved relative to the directory containing the collection file.stdin: bytes(default =b''): Data to pipe to the subprocess’s stdin
Return
bytes
Stdout output as bytes. May be returned as a stream (LazyValue).
Errors
- If the command fails to initialize (e.g. program unknown)
- If the subprocess exits with a non-zero status code
Examples
command(["echo", "hello"]) => hello
command(["grep","1"], stdin="line 1\nline2") => line 1
concat
concat(elements: string[]): string
Concatenate any number of strings together
Parameters
elements: string[](required): Strings to concatenate together. Any non-string values will be stringified
Return
string
Concatenated string
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() => TedSteveSarah
debug
debug(value: value): value
Print a value to stdout, returning the same value. Useful for debugging templates.
Parameters
value: value(required): The value to print and return
Return
value
The same value that was passed in
Examples
# Prints "hello"
debug("hello") => 'hello'
# Contents of data.json will be printed
file("data.json") | debug() | jsonpath("$.data") => 123
env
env(variable: string, default?: string): string
Get the value of an environment variable, or "" if not set
Parameters
variable: string(required): Name of the environment variable to readdefault: string(default = ``): Value to return when the environment variable is not present
Return
string
Value of the environment variable or the provided default
Examples
env("HOME") => /home/username
env("NONEXISTENT") =>
env("NONEXISTENT", default="default") => default
file
file(path: string): bytes
Load contents of a file. Output is bytes but can be used as a string in most cases. Supports streaming for large/binary files.
Parameters
path: string(required): Path to the file to read, relative to the collection file (slumber.yml). A leading~will be expanded to $HOME.
Return
bytes
File contents as bytes (may be a stream)
Errors
- If an I/O error occurs while opening 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(required): Value to convert
Return
float
Floating point representation (f64)
Errors
- If
valueis a string or byte string that doesn’t parse to a float - If
valueis an inconvertible type such as an array or object
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
index
index(index: integer, sequence: string | bytes | value[]): value
Get one element from a string, bytes, or array For strings, the index is in terms of characters, not bytes.
Parameters
index: integer(required): Index of the element to return, starting at 0. Negative values count backwards from the end.sequence: string | bytes | value[](required): String, bytes, or array to index into
Return
value
Value at index. If index >= length, return null
Examples
[0, 1, 2] | index(1) => 1
'abc' | index(1) => 'b'
# Negative indexes count back from the end
'abc' | index(-1) => 'c'
'abc' | index(3) => null
# String indexes are in terms of characters. Multi-byte UTF-8 characters count as a single element
'nägemist' | index(1) => 'ä'
# Bytes indexes are in terms of bytes, not UTF-8 characters
b'nägemist' | index(1) => b'Ã'
integer
integer(value: value): integer
Convert a value to an int
Parameters
value: value(required): Value to convert
Return
integer
Integer representation (i64)
Errors
- If
valueis a string or byte string that doesn’t parse to an integer - If
valueis an inconvertible type such as an array or object
Examples
integer('3') => 3
integer(b'3') => 3
integer(3.5) => 3
integer(null) => 0
integer(false) => 0
integer(true) => 1
join
join(separator: string, values: string[]): string
Join a list of strings with a separator
join is the inverse of split. join(sep, split(sep, value)) always yields value.
Parameters
separator: string(required): String to join withvalues: string[](required): Array to join
Return
string
Joined string
Examples
['a', 'b', 'c'] | join(',') => 'a,b,c'
# Non-string values are coerced to strings
[1, 2, 3] | join(',') => '1,2,3'
jq
jq(
query: string,
value: value,
mode?: "auto" | "single" | "array",
): value
Transform a JSON value using a jq query. Uses the jaq Rust implementation.
Parameters
query: string(required):jqquery stringvalue: value(required): JSON value to query. Strings/bytes will be parsed as JSON first.mode: "auto" | "single" | "array"(default =auto): How to handle multiple results (auto/single/array)
Return
value
Resulting template Value
Errors
- If
valueis 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') | jq(".first_name") => Alice
json_parse
json_parse(value: string): value
Parse a JSON string to a template value
Parameters
value: string(required): JSON string
Return
value
Parsed JSON as serde_json::Value
Errors
- If
valueis not valid JSON
Examples
json_parse('{"name": "Alice"}') => {"name": "Alice"}
file('body.json') | json_parse() => {"name": "Alice"}
jsonpath
jsonpath(
query: string,
value: value,
mode?: "auto" | "single" | "array",
): value
Transform a JSON value using a JSONPath query
Parameters
value: value(required): JSON value to query. Strings/bytes will be parsed as JSON before querying.query: string(required): JSONPath query stringmode: "auto" | "single" | "array"(default =auto): How to handle multiple results (auto/single/array)
Return
value
Resulting template Value
Errors
- If
valueis 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
lower
lower(value: string): string
Convert a string to lowercase
Parameters
value: string(required): String to convert
Return
string
Lowercased string
Examples
lower("HELLO") => hello
# UTF-8 characters are converted as well
lower("NÄGEMIST") => nägemist
prompt
prompt(message?: string, default?: string, sensitive?: boolean): string
Prompt the user to enter a text value
Parameters
message: string(default =''): Optional prompt message to display to the userdefault: string(default =''): Optional default value to pre-fill the inputsensitive: boolean(default =false): Mask the input while typing. Also masks output in previews.
Return
string
Entered string
Errors
- If the user doesn’t give a response
Examples
prompt() => What do I put here? Help!!
prompt(message="Enter your name") => Barry Barracuda
prompt(message="Password", sensitive=true) => hunter2
replace
replace(
from: string,
to: string,
value: string,
regex?: boolean,
n?: integer,
): string
Replace all occurrences of from in value with to
Parameters
from: string(required): Pattern to be replacedto: string(required): String to replace each occurrence offromwithvalue: string(required): String to splitregex: boolean(default =false): Iftrue,fromwill be parsed as a regular expression instead of a plain string.n: integer(default =null): Maximum number of replacements to make, starting from the start of the string. Ifnull, make all possible replacements
Return
string
Array of separated string segments
Errors
- If
regex=truebutfromis not a valid regex
Examples
'banana' | replace('na', 'ma') => 'bamama'
# Replace a or b with x
'banana' | replace('[ab]', 'x', regex=true) => 'xxnxnx'
'banana' | replace('na', 'ma', n=1) => 'bamana'
# Overlapping instances of `to` are NOT all replaced
'bananan' | replace('nan', 'mam') => 'bamaman'
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
Parameters
recipe_id: string(required): ID (not name) of the recipe to load the response fromtrigger: "never" | "no_history" | "always" | Duration(default =never): When to execute the upstream request (never/no_history/always/Duration)
Return
bytes
Most recent response body as bytes
Errors
- If
recipeisn’t in the collection - If there is no request in history and
trigger='never' - If a request is triggered and failed
Examples
response("login") => {"token": "abc123"}
response("login", trigger="1h") => {"token": "abc123"}
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
Parameters
recipe_id: string(required): ID (not name) of the recipe to load the response fromheader: string(required): Name of the header to extract (case-insensitive)trigger: "never" | "no_history" | "always" | Duration(default =never): When to execute the upstream request vs using cached response
Return
bytes
Header value as bytes
Errors
- If
recipeisn’t in the collection - If there is no request in history and
trigger='never' - If a request is triggered and failed
- If the header is missing
Examples
response_header("get_rate_limit", "X-Rate-Limit", trigger="5m") => 100
select
select(
options: (string | { "label": string, "value": value })[],
message?: string,
): value
Ask the user to select a value from a list
Parameters
options: (string | { "label": string, "value": value })[](required): List of options to choose from. Each option can be either a string or an object with “label” and “value”.message: string(default = ``): Descriptive message to display to the user
Return
value
The selected value
Errors
- If
optionsis empty - If the user doesn’t give a response
Examples
select(["dev", "staging", "prod"]) => dev
select(["GET", "POST","PUT"], message="HTTP method") => POST
select([{"label":"Sam","value":1},{"label":"Mike","value":2}]) => 2
sensitive
sensitive(value: string): string
Mark a value as sensitive, masking it in template previews. No impact on requests sent.
Parameters
value: string(required): String to mask
Return
string
Masked string in preview, input string when building requests
Examples
sensitive("hunter2") => •••••••
slice
slice(
start: integer,
stop: integer,
sequence: string | bytes | value[],
): string | bytes | value[]
Extract a portion of a string, bytes, or array Indexes are zero-based and [inclusive, exclusive)
Parameters
start: integer(required): Index of the first element to include, starting at 0. Negative values count backward from the end.stop: integer(required): Index after the last element to include, starting at 0.nullwill slice to the end. Negative values count backwards from the end.sequence: string | bytes | value[](required): String, bytes, or array to slice
Return
string | bytes | value[]
Subslice of the input string/array. If stop < start, return an empty slice. If either index outside the range [0, length], it will be clamped to that range.
Examples
[0, 1, 2] | slice(1, 2) => [1]
[0, 1, 2] | slice(1, 3) => [1, 2]
'abc' | slice(0, 2) => 'ab'
'abc' | slice(0, 0) => ''
# Use `null` for `stop` to slice to the end
'abc' | slice(1, null) => 'bc'
# Negative indexes count back from the end
'abc' | slice(1, -1) => 'b'
# Combine the two to get the last n elements
'abc' | slice(-2, null) => 'bc'
# Indexes are in terms of characters. Multi-byte UTF-8 characters count as a single element
'nägemist' | slice(1, 3) => 'äg'
# Bytes indexes are in terms of bytes, not UTF-8 characters
b'nägemist' | slice(1, 3) => b'ä'
split
split(separator: string, value: string, n?: integer): string[]
Split a string on a separator
Parameters
separator: string(required): String to split onvalue: string(required): String to splitn: integer(default =null): Maximum number of times to split. Ifnull, split as many times as possible
Return
string[]
Array of separated string segments
Examples
'a,b,c' | split(',') => ['a', 'b', 'c']
'a,b,c' | split(',', n=1) => ['a', 'b,c']
'a,b,c' | split('') => ['', 'a', ',', 'b', ',', 'c', '']
'' | split(',') => ['']
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(required): Value to stringify
Return
string
String representation
Errors
- If
valueis 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(required): String to trim (typically piped in)mode: "start" | "end" | "both"(default =both): Section of the string to trim (start/end/both)
Return
string
Trimmed string
Examples
trim(" hello ") => hello
trim(" hello ", mode="start") => hello
command(["echo", "hello"]) | trim() => hello
upper
upper(value: string): string
Convert a string to uppercase
Parameters
value: string(required): String to convert
Return
string
Uppercased string
Examples
upper("hello") => HELLO
# UTF-8 characters are converted as well
lower("nägemist") => NÄGEMIST