Utility Functions
Last updated
Was this helpful?
Last updated
Was this helpful?
Halts execution and returns the defined result immediately. Return is useful when used in combination with where you want to change the return based on the result of the condition.
Try/catch enables you to catch any errors that may occur in a specific stack of functions and execute additional logic based on that result. This function essentially enables fully custom error handling in Xano.
Try - Try these functions first
Catch - Execute these functions if the Try statements return an error
Finally - Execute these functions regardless of the result
In the below example, we are starting with a Delete File function, and trying to delete a file that does not exist.
Deleting a file that does not exist returns ERROR_CODE_NOT_FOUND and halts execution.
Normally, when an error occurs in the function stack, execution is halted entirely. If we wanted to deploy some customized error handling to change this behavior, we can do so by placing this function inside of a Try/Catch statement.
In the below iteration, we've moved Delete File into the Try portion of a Try/Catch statement. Now, when we run the endpoint again, the function itself is still failing, but the API itself still returns a success response.
We can then use the Catch portion to read the error, using three variables only available via Try/Catch.
code is the error code
message is the error message
result will be any accompanying data. Most functions will not output a result, and only return data in code and message
When we run this again and output those variables as part of our response, you'll see that the API still returns a 'Success' result, but we can view the error message returned by our function in our Try statement.
You can then use the Finally section to determine the behavior based on the result of your Try/Catch. In the below example, we're using a conditional statement to check if the try/catch code variable is empty. If it is empty, we return a success message. If it is not empty (which means there was an error in our Try statements), we return an error message.
Practical Example of using Try/Catch
Throw Error allows you to halt execution with a custom error message. This is different from a Precondition step because it does not restrict you to specific error codes. It can be used in combination with Try/Catch or on its own.
Post process allows you to execute additional logic after your API has provided a response. This can be useful if you want to see a response on your front-end without waiting for any additional processing to occur, but a background task does not meet your needs.
Example
In this function stack, we are setting var_1 with a value of "Hello" and calling an external API to send the contents of this variable.
Afterwards, we have added Post Process to update var_1 and send a new request to the same external API.
The function stack is set to respond with the contents of var_1.
This means that the following will happen in sequence:
Set var_1 to "Hello!"
Send var_1 to external API
The Xano API responds with "Hello!"
Set var_1 to "Goodbye!"
Send var_1 to external API
Below is a video of this example in action. Note how the external API recieves both 'Hello' and 'Goodbye', but the Xano API just responds with 'Hello'. Note: the video does not contain any audio.
Post Process will use the state of variables where it is defined. This means that while Post Process executes at the end of the function stack, the placement is still important to ensure that any variables it uses retain the appropriate content.
Post Process also enables the use of some special variables: body, headers, and status_code. These are only available during post process, and can be used to transmit any of the corresponding data back to a database table, or to an external API, to record the results of post process.
Debug Log allows you to output specific information in a new debug logging section of the Debugger. This is similar to how a console log statement in Javascript would behave. These steps will not run outside of Run & Debug.
This can be especially helpful for debugging data errors with loops or otherwise just giving you a quick view of a variable's contents during execution. You can insert whatever data you'd like into Debug Logs; they will accept any data type, and can also have filters applied.
In the below example, we're looping through results from a Query All Records statement, and outputting a specific value from each item to the new Debug Log.
And the result is available in the new Debug Log section of the debugger
A precondition is a statement that says "this condition must evaluate as true, or we halt execution and return an error message."
Halts execution and returns a value. Useful to ensure that specific pieces of your function stack are running as expected while building.
Groups functions together. This is an organizational tool for you as you build your function stacks and does not impact any part of the actual execution.
Waits for a defined number of seconds before proceeding to the next step.
CSV Stream is a powerful function allowing you to 'stream' chunks of a CSV file in sequence to your function stack, allowing for processing of large CSV files.
A successful CSV stream function stack includes three essential parts.
a file resource to ingest the CSV file This can come from either a File Resource input, or a file delivered by an external API, with a Create File Resource step applied
a For Each loop to run through the individual CSV rows The loop is responsible for performing any functions you'd like on your CSV, such as adding each row to one of your database tables.
In the below example, we've added these three key components, and can now process the incoming CSV data.
CSV Stream is a much simpler alternative to the previously established method of array functions and object manipulation to process incoming CSV data.
Set a custom HTTP header. This function is useful if you need your responses to deliver specific, custom headers. You can also use this to specify custom API response codes outside of the ones our Precondition function offers.
The duplicates parameter lets you decide to either replace headers that already exist with your new header, or allow for duplicate headers to exist.
Returns all of the variables present up to that point in the function stack.
Returns all of the inputs sent to the API in a single object.
Returns all data sent to the API, even if they are not defined inputs. You'd use this function when building a Webhook, or you otherwise aren't sure what data will be sent to this endpoint.
Calculate the distance between two longitude/Latitude points
This function allows you to specify which data source that database operations following it target. Remember that the order of operations in a function stack matters, so any database operations that come before your Set Data Source statement will use whatever is used normally.
a CSV stream function to stream the CSV data This function initiates the streaming of CSV data, and provides an output variable. This output variable is meant for use with a loop
Returns all of your in a single object.
Takes in an IP address and returns geographical information based on that IP. This product includes GeoLite2 data created by MaxMind, available from .
You can check out some examples of the Template Engine in real-world scenarios here: .
Each conditional has four different components.
Conditional Type
The conditional type determines how this condition is weighted in the final return. You can choose between AND and OR. AND conditionals require the present conditional and any others before it to be satisfied, such as "where the date is before today AND the user is an admin". OR conditionals do not require any other conditionals to be satisfied, such as "if the user is an admin OR if the user is a manager".
Left Value
This is the first value you're using in the conditional. In a database query, this is usually going to be a column that you want to check against.
Operators
Equals (==) - an exact match
Not Equals (!=) - does not equal
Equals with type matching (===) - an exact value match and an exact type match
Ex. Variable var_1 has a value of 123, with a type of text. You set up a conditional statement to check if var_1 === 123, but your value in the conditional statement is of type integer. This would return false, because the types do not match.
Not equals with type matching (!==) - does not equal value or type, similar to ===
Greater than (>) - the value on the left is greater than the value on the right
Greater than or equals (≥) - the value on the left is greater than or equals to the value on the right.
Less than (<) - the value on the left is less than the value on the right.
Less than or equals (≤) - the value on the left is less than or equals to the value on the right.
LIKE - Used for comparing text. Like is case-insensitive and compares if a text string is like another text string. It can be thought of as equals for text but upper case and lower case does not matter.
NOT LIKE - Used for comparing text. Not Like is case-insensitive and compares if a text string is not like another. It is like not equals for text but upper case and lower case does not matter.
INCLUDES - Used for comparing text. Includes is a flexible operator and is case-insensitive. It is able to determine if there is a partial match in a text string.
DOES NOT INCLUDE - Used for comparing text. Does not include determines if a text string is not included in another text string.
IN - If a single value is found in an array (list). Start with the single value on the left side and the right side should contain the array.
NOT IN - If a single value is not found in an array (list). The single value should be on the left side and the array on the right side.
OVERLAPS - Used for comparing two arrays. Overlaps determines if any values in one array are present in the second array.
DOES NOT OVERLAP - Used for comparing two arrays. Does not overlaps determines if no values in the first array are present in the second array.
CONTAINS - Contains is an advanced filter used for JSON and arrays. It looks for an exact schema match.
DOES NOT CONTAIN - Does not contain is the opposite of contains. It determines if there is not an exact schema match.
The right value is whatever you are checking against the left value. This could be a hardcoded value, a variable, or even a database field from the same record.
The Template Engine, powered by Twig, is used to manipulate and dynamically generate large blocks of text or code with your own data, such as records from your Xano database, or from inputs sent to your APIs.
It's great for helping generate things like AI prompts, HTML, and other more large-format data without messing around with a bulk of separate functions to do so.
At its core, think of the Template Engine as text replacement and manipulation of the future. It is designed to give you a simple syntax to quickly manipulate large text strings with dynamic data, such as...
AI Prompts
HTML
JSON
SQL queries
Replacing a name inside of a string like "Hello, [first_name] [last_name]"
Dynamically providing a price for a single product
The Template Engine, however, is useful for content templates where:
The template will be edited by non-developers
The data structure is complex with nested objects
You need to include conditional sections
Data formatting (like dates) needs to be consistent
Templates might be reused with different data sources
If you're doing dynamic replacement over a longer block of text, such as the example below, Template Engine will make this much easier for you.
Variables are wrapped in {{ curly braces }}, like this, and begin with a $ character. In the below example, we're getting the name
from an object stored in the user1
variable.
Reference items in an array by using the item index.
Conditionals are helpful if you want to dynamically determine what the end result of your template looks like outside of the actual data. For example, maybe you want VIP users to have a different greeting than regular users.
Conditionals are wrapped in {% and %} and have support for else
and else if
In the above example, for this user:
...the result would be:
In the above example, for this score:
...the result would be:
You can use loops to populate lists of data without having to write out separate lines for each item, or knowing how many items you'll need to populate.
2x Blue T-shirt at $19.99 each
1x Denim Jeans at $59.99 each
3x Cotton Socks at $4.99 each
You can also use an Else statement at the end of your For loop to determine what action to take if no items are found. In the next example, if $list
contains no items, the template will return No items found.
You can use Twig's built in filters, similar to our own, to transform or manipulate data as part of the template.
upper
Converts string to uppercase
{{ $user.name|upper }}
When $user.name is "John Smith"
"JOHN SMITH"
lower
Converts string to lowercase
{{ $user.name|lower }}
When $user.name is "John Smith"
"john smith"
trim
Removes whitespace from the beginning and end of a string
{{ $user.input|trim }}
When $user.input is " hello "
"hello"
join
Joins array elements into a string with a delimiter
{{ $user.tags|join(', ') }}
When $user.tags is ["php", "twig", "web"]
"php, twig, web"
default
Provides a fallback value if the variable is null, empty, or undefined
{{ $user.middleName|default('No middle name') }}
When $user.middleName is null
"No middle name"
number_format
Formats numbers with grouped thousands and decimal points
{{ $product.price|number_format(2, '.', ',') }}
When $product.price is 1234.56
"1,234.56"
shuffle
Randomly shuffles an array
{{ $user.items|shuffle }}
When $user.items is ["a", "b", "c"]
Random order like: ["c", "a", "b"]
date
Formats dates using PHP's date syntax
{{ $user.createdAt|date("F j, Y") }}
When $user.createdAt is "2023-12-25"
"December 25, 2023"
The escape filter is used to format text using specifications designated by the destination, such as a URL that only allows certain characters to remain valid.
When you use e
by itself without specifying a format, it typically defaults to HTML escaping. This means it will convert characters like <
, >
, &
, "
, and '
to their HTML-safe equivalents.
When you specify a format (like e('html')
, e('js')
, e('url')
, etc.), you're explicitly telling the Template Engine how to escape the content for a specific context, which can provide more precise protection. We'd recommend always specifying the format, just to be safe.
You can insert comments into your templates by wrapping them in {# and #}. They won't appear in your final template.
REGEX MATCHES - used for finding patterns in text.
REGEX DOES NOT MATCH - used for finding a pattern that does not match in text.
The template engine is powered by Twig, which you can learn more about .
You should stick with filters like or if you're manipulating short strings of text, such as:
The below list is some of the most essential filters used in Twig, but it is not all of them. You can review the entire list .