Use Optional Variables¶
Mark variables as optional to handle cases where data may be missing or unset, allowing your flow to continue gracefully instead of failing.
QType YAML¶
Explanation¶
?suffix: Shorthand syntax to mark a variable as optional- Optional variables: Can be
Noneor set to a value - FieldExtractor: Returns
Nonefor optional output variables when JSONPath finds no matches, instead of raising an error. If you make the variable non-optional, it will raise an error.
Complete Example¶
id: optional_variables_demo
description: Demonstrates optional variables that can handle missing data gracefully
flows:
- id: extract_optional_field
variables:
- id: user_profile
type: text
- id: email
type: text?
inputs:
- user_profile
outputs:
- email
steps:
# Try to extract email - may not exist, will return None if missing
- type: FieldExtractor
id: extract_email
inputs:
- user_profile
outputs:
- email
json_path: $.email
- type: Echo
id: show_result
inputs:
- email
outputs:
- email
Run it:
# When email field exists
qtype run examples/language_features/optional_variables.qtype.yaml -i '{"user_profile": {"email":"hello@domain.com"}}'
# Results:
# email: hello@domain.com
# When email field is missing
qtype run examples/language_features/optional_variables.qtype.yaml -i '{"user_profile": "just text"}'
# Results:
# email: None