API Reference

This section documents the public API of the Splunk SOAR SDK.

Jump to a Section:

The App Class

class soar_sdk.app.App[source]

Bases: object

Main application class for SOAR connectors.

This class provides the foundation for building SOAR connectors. It handles action registration, asset management, test connectivity, polling, and webhook functionality.

The App class serves as the central coordinator for all app functionality, providing decorators for action registration and managing the lifecycle of SOAR operations.

Parameters:
  • name (str) – Human-readable name of the app.

  • app_type (str) – Type of the app (e.g., “investigative”, “corrective”).

  • logo (str) – Path to the app’s logo image.

  • logo_dark (str) – Path to the app’s dark theme logo image.

  • product_vendor (str) – Vendor of the product this app integrates with.

  • product_name (str) – Name of the product this app integrates with.

  • publisher (str) – Publisher of the app.

  • appid (str) – Unique UUID identifier for the app.

  • python_version (list[PythonVersion] | str | None) – List of supported Python versions. Defaults to all supported versions.

  • min_phantom_version (str) – Minimum required SOAR version. Defaults to configured minimum.

  • fips_compliant (bool) – Whether the app is FIPS compliant. Defaults to False.

  • asset_cls (type[BaseAsset]) – Asset class to use for configuration. Defaults to BaseAsset.

Raises:

ValueError – If appid is not a valid UUID.

Example

>>> app = App(
...     name="My SOAR App",
...     app_type="investigative",
...     logo="logo.png",
...     logo_dark="logo_dark.png",
...     product_vendor="Acme Corp",
...     product_name="Security Platform",
...     publisher="My Company",
...     appid="12345678-1234-5678-9012-123456789012",
... )
__init__(*, name, app_type, logo, logo_dark, product_vendor, product_name, publisher, appid, python_version=None, min_phantom_version='7.0.0', fips_compliant=False, asset_cls=<class 'soar_sdk.asset.BaseAsset'>)[source]
Parameters:
get_actions()[source]

Returns the list of actions registered in the app.

Return type:

dict[str, Action]

cli()[source]

Create and execute an AppRunner to run an action via command line.

Calling this function in your app’s main module will allow you to run actions or webhook handlers directly from the command line for testing and debugging.

Example:

python app.py --help
usage: app.py [-h] [--soar-url SOAR_URL] [--soar-user SOAR_USER] [--soar-password SOAR_PASSWORD] {action,webhook} ...

positional arguments:
{action,webhook}
    action              Run an action
    webhook             Invoke a webhook handler

options:
-h, --help            show this help message and exit
--soar-url SOAR_URL   SOAR URL to connect to. Can be provided via PHANTOM_BASE_URL environment variable as well.
--soar-user SOAR_USER
                        Username to connect to SOAR instance. Can be provided via PHANTOM_USER environment variable as well
--soar-password SOAR_PASSWORD
                        Password to connect to SOAR instance. Can be provided via PHANTOM_PASSWORD environment variable as well
Return type:

None

handle(raw_input_data, handle=None)[source]

Runs handling of the input data on connector.

NOTE: handle is actually a pointer address to spawn’s internal state. In versions of SOAR >6.4.1, handle will not be passed to the app.

Parameters:
Return type:

str

static create_soar_client_auth_object(input_data)[source]

Creates a SOARClientAuth object based on the input data.

This is used to authenticate the SOAR client before running actions.

Parameters:

input_data (InputSpecification)

Return type:

SOARClientAuth

__call__(raw_input_data, handle=None)

Runs handling of the input data on connector.

NOTE: handle is actually a pointer address to spawn’s internal state. In versions of SOAR >6.4.1, handle will not be passed to the app.

Parameters:
Return type:

str

property asset: BaseAsset

Returns the asset instance for the app.

on_es_poll()[source]

Decorator for the on_es_poll action.

The decorated function must be a generator (using yield) or return an Iterator that yields tuples of (Finding, list[AttachmentInput]). Only one on_es_poll action is allowed per app.

Return type:

OnESPollDecorator

Example

>>> @app.on_es_poll()
... def on_es_poll(
...     params: OnESPollParams, soar: SOARClient, asset: Asset
... ) -> Iterator[tuple[Finding, list[AttachmentInput]]]:
...     yield (
...         Finding(
...             rule_title="Risk threshold exceeded for user",
...             rule_description="Risk Threshold Exceeded for an object over a 24 hour period",
...             security_domain="threat",
...             risk_object="bad_user@splunk.com",
...             risk_object_type="user",
...             risk_score=100.0,
...             status="New",
...         ),
...         [],
...     )
make_request(output_class=None)[source]

Decorator for registering a make request action function.

This decorator marks a function as the make request action for the app. make request is used to call any endpoint of the underlying API service this app implements. Only one make request action is allowed per app. The function you define needs to accept at least one parameter of type MakeRequestParams and can accept any other parameters you need. Other useful parameters to accept are the SOARClient and the asset.

Returns:

A decorator instance that handles make request action registration.

Return type:

MakeRequestActionDecorator

Example

>>> @app.make_request()
... def http_action(
...     self, params: MakeRequestParams, asset: Asset
... ) -> MakeRequestOutput:
...     logger.info(f"testing connectivity against {asset.base_url}")
...     return MakeRequestOutput(
...         status_code=200,
...         response_body=f"Base url is {asset.base_url}",
...     )

Note

The make request action function should return either a MakeRequestOutput object or of an output class derived from it.

Parameters:

output_class (type[ActionOutput] | None)

webhook_meta: WebhookMeta | None = None
webhook_router: Router | None = None
webhook(url_pattern, allowed_methods=None)[source]

Decorator for registering a webhook handler.

Parameters:
Return type:

WebhookDecorator

handle_webhook(method, headers, path_parts, query, body, asset, soar_rest_client)[source]

Handles the incoming webhook request.

Parameters:
Return type:

dict

Key App Methods

App.action(*, name=None, identifier=None, description=None, verbose='', action_type='generic', read_only=True, params_class=None, output_class=None, render_as=None, view_handler=None, versions='EQ(*)', summary_type=None, enable_concurrency_lock=False)[source]

Decorator for registering an action function.

This decorator marks a function as an action handler for the app.

Parameters:
Return type:

ActionDecorator

App.test_connectivity()[source]

Decorator for registering a test connectivity function.

This decorator marks a function as the test connectivity action for the app. Test connectivity is used to verify that the app can successfully connect to its configured external service or API. Only one test connectivity function is allowed per app.

Returns:

A decorator instance that handles test

connectivity registration.

Return type:

ConnectivityTestDecorator

Example

>>> @app.test_connectivity()
... def test_connectivity_handler(self, asset: Asset):
...     logger.info(f"testing connectivity against {asset.base_url}")

Note

The test connectivity function should not return anything or raise an exception if it fails.

App.on_poll()[source]

Decorator for the on_poll action.

The decorated function must be a generator (using yield) or return an Iterator that yields Container and/or Artifact objects. Only one on_poll action is allowed per app.

Usage: If a Container is yielded first, all subsequent Artifacts will be added to that container unless they already have a container_id. If an Artifact is yielded without a container and no container_id is set, it will be skipped.

Return type:

OnPollDecorator

Example

>>> @app.on_poll()
... def on_poll(
...     params: OnPollParams, soar: SOARClient, asset: Asset
... ) -> Iterator[Union[Container, Artifact]]:
...     yield Container(
...         name="Network Alerts",
...         description="Some network-related alerts",
...         severity="medium",
...     )
App.register_action(action, *, name=None, identifier=None, description=None, verbose='', action_type='generic', read_only=True, params_class=None, output_class=None, render_as=None, view_handler=None, view_template=None, versions='EQ(*)', summary_type=None, enable_concurrency_lock=False)[source]

Dynamically register an action function defined in another module.

This method allows an app to dynamically import and register an action function that is defined in a separate module. It provides a programmatic way to register actions without using decorators directly on the action function.

Parameters:
  • action (str | Callable) –

    Either an import string to find the function that implements an action, or the imported function itself.

    Warning

    If you import the function directly, and provide the callable to this function, this sometimes messes with the app’s CLI invocation. For example, if you import your function with a relative import, like:

    from .actions.my_action import my_action_function
    

    then executing your app directly, like:

    python src/app.py action my_action_function
    

    will fail, but running as a module, like:

    python -m src.app action my_action_function
    

    will work. By contrast, if you use an absolute import, like:

    from actions.my_action import my_action_function
    

    then the direct CLI invocation will work, while the module invocation will fail. This is a limitation with Python itself.

    To avoid this confusion, it is recommended to provide the action as an import string, like "actions.my_action:my_action_function". This way, both invocation methods will work consistently.

  • name (str | None) – Human-readable name for the action. If not provided, defaults to the function name with underscores replaced by spaces.

  • identifier (str | None) – Unique identifier for the action. If not provided, defaults to the function name.

  • description (str | None) – Brief description of what the action does. Used in the app manifest and UI.

  • verbose (str) – Detailed description or usage information for the action.

  • action_type (str) – Type of action (e.g., “generic”, “investigate”, “correct”). Defaults to “generic”.

  • read_only (bool) – Whether the action only reads data without making changes. Defaults to True for safety.

  • params_class (type[Params] | None) – Pydantic model class for validating action parameters. If not provided, uses generic parameter validation.

  • output_class (type[ActionOutput] | None) – Pydantic model class for structuring action output. If not provided, uses generic output format.

  • view_handler (str | Callable | None) –

    Optional import string to a view handler function, or the imported function itself, to associate with this action. Will be automatically decorated with the view_handler decorator.

    Warning

    See the warning above about importing action functions as opposed to using import strings. The same issues apply to view handler functions as well.

  • view_template (str | None) – Template name to use with the view handler. Only relevant if view_handler is provided.

  • versions (str) – Version constraint string for when this action is available. Defaults to “EQ(*)” (all versions).

  • summary_type (type[ActionOutput] | None) – Pydantic model class for structuring action summary output.

  • enable_concurrency_lock (bool) – Whether to enable a concurrency lock for this action. Defaults to False.

Return type:

Action

Returns:

The registered Action instance with all metadata and handlers configured.

Raises:

ActionRegistrationError – If view_handler is provided but cannot be found in its original module for replacement.

Example

>>> action = app.register_action(
...     "action.my_action:my_action_function",
...     name="Dynamic Action",
...     description="Action imported from another module",
...     view_handler="my_views_module:my_view_handler",
...     view_template="custom_template.html",
... )
Parameters:

render_as (str | None)

App.enable_webhooks(default_requires_auth=True, default_allowed_headers=None, default_ip_allowlist=None)[source]

Enable webhook functionality for the app.

This method configures the app to handle incoming webhook requests by setting up the security and routing configurations.

Parameters:
  • default_requires_auth (bool) – Whether webhooks require authentication by default.

  • default_allowed_headers (list[str] | None) – List of HTTP headers allowed in webhook requests.

  • default_ip_allowlist (list[str] | None) – List of IP addresses/CIDR blocks allowed to send webhooks. Defaults to [“0.0.0.0/0”, “::/0”] (allow all).

Return type:

App

Returns:

The App instance for method chaining.

Example

>>> app.enable_webhooks(
...     default_requires_auth=True,
...     default_allowed_headers=["X-Custom-Header"],
...     default_ip_allowlist=["192.168.1.0/24"],
... )
App.view_handler(*, template=None)[source]

Decorator for custom view functions with output parsing and template rendering.

The decorated function receives parsed ActionOutput objects and can return either a dict for template rendering, HTML string, or component data model. If a template is provided, dict results will be rendered using the template. Component type is automatically inferred from the return type annotation.

See also

For more information on custom views, see the following custom views documentation:

Example

>>> @app.view_handler(template="my_template.html")
... def my_view(outputs: List[MyActionOutput]) -> dict:
...     return {"data": outputs[0].some_field}
>>> @app.view_handler()
... def my_chart_view(outputs: List[MyActionOutput]) -> PieChartData:
...     return PieChartData(
...         title="Chart",
...         labels=["A", "B"],
...         values=[1, 2],
...         colors=["red", "blue"],
...     )
Parameters:

template (str | None)

Return type:

ViewHandlerDecorator

Asset Configuration

AssetField

soar_sdk.asset.AssetField(description=None, required=True, default=None, value_list=None, sensitive=False, alias=None)[source]

Representation of an asset configuration field.

The field needs extra metadata that is later used for the configuration of the app. This function takes care of the required information for the manifest JSON file and fills in defaults.

Parameters:
  • description (str | None) – A short description of this parameter. The description is shown in the asset form as the input’s title.

  • required (bool) – Whether or not this config key is mandatory for this asset to function. If this configuration is not provided, actions cannot be executed on the app.

  • value_list (list | None) – To allow the user to choose from a pre-defined list of values displayed in a drop-down for this configuration key, specify them as a list for example, [“one”, “two”, “three”].

  • sensitive (bool) – When True, the field is treated as a password and will be encrypted and hidden from logs.

  • default (Any | None)

  • alias (str | None)

Return type:

Any

Returns:

The FieldInfo object as pydantic.Field.

BaseAsset

class soar_sdk.asset.BaseAsset[source]

Bases: BaseModel

Base class for asset models in SOAR SDK.

This class provides the foundation for defining an asset configuration for SOAR apps. It extends Pydantic’s BaseModel to provide validation, serialization, and manifest generation capabilities for asset configurations.

Asset classes define the configuration parameters that users need to provide when setting up an app instance in SOAR. These typically include connection details, authentication credentials, and other app-specific settings.

The class automatically validates field names to prevent conflicts with platform-reserved fields and provides methods to generate JSON schemas compatible with SOAR’s asset configuration system.

Example

>>> class MyAsset(BaseAsset):
...     base_url: str = AssetField(description="API base URL", required=True)
...     api_key: str = AssetField(
...         description="API authentication key", sensitive=True
...     )
...     timeout: int = AssetField(
...         description="Request timeout in seconds", default=30
...     )

Note

Field names cannot start with “_reserved_” or use names reserved by the SOAR platform to avoid conflicts with internal fields.

Parameters:

data (Any)

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod to_json_schema()[source]

Generate a JSON schema representation of the asset configuration.

Converts the Pydantic model fields into a format compatible with SOAR’s asset configuration system. This includes data type mapping, validation rules, and UI hints for the SOAR platform.

Return type:

dict[str, AssetFieldSpecification]

Returns:

A dictionary mapping field names to their schema specifications, including data types, descriptions, requirements, and other metadata.

Raises:

TypeError – If a field type cannot be serialized or if a sensitive field is not of type str.

Example

>>> class MyAsset(BaseAsset):
...     host: str = AssetField(description="Server hostname")
...     port: int = AssetField(description="Server port", default=443)
>>> schema = MyAsset.to_json_schema()
>>> schema["host"]["data_type"]
'string'
>>> schema["host"]["required"]
True

Note

Sensitive fields are automatically converted to “password” type regardless of their Python type annotation, and must be str type.

classmethod fields_requiring_decryption()[source]

Set of fields that require decryption.

Return type:

set[str]

Returns:

A set of field names that are marked as sensitive and need decryption before use.

classmethod timezone_fields()[source]

Set of fields that use the ZoneInfo type.

Return type:

set[str]

Returns:

A set of field names that use the ZoneInfo type.

property auth_state: AssetState

A place to store authentication data, such as session and refresh tokens, between action runs. This data is stored by the SOAR service, and is encrypted at rest.

property cache_state: AssetState

A place to cache miscellaneous data between action runs. This data is stored by the SOAR service, and is encrypted at rest.

property ingest_state: AssetState

A place to store ingestion information, such as checkpoints, between action runs. This data is stored by the SOAR service, and is encrypted at rest.

model_post_init(context, /)

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Action Parameters

Action parameters are defined in Pydantic models, which extend the soar_sdk.params.Params class. At their most basic, parameters can have a simple data type such as str or int.

from soar_sdk.params import Params


class CreateUserParams(Params):
   username: str
   first_name: str
   last_name: str
   email: str
   is_admin: bool
   uid: int

Adding Extra Metadata

You can use the Param() function to add extra information to a parameter type. For example, let’s give the uid field a Common Event Format (CEF) type and make it optional.

from soar_sdk.params import Params, Param


class CreateUserParams(Params):
   username: str
   first_name: str
   last_name: str
   email: str
   is_admin: bool
   uid: int = Param(required=False, cef_types=["user id"])

Defining Parameters

class soar_sdk.params.Params[source]

Params defines the full set of inputs for an action.

It can contain strings, booleans, or numbers – no lists or dictionaries. Params fields can be optional if desired, or optionally have a default value, CEF type, and other metadata defined in soar_sdk.params.Param().

Parameters:

data (Any)

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

soar_sdk.params.Param(description=None, required=True, primary=False, default=None, value_list=None, cef_types=None, allow_list=False, sensitive=False, alias=None, column_name=None)[source]

Representation of a single complex action parameter.

Use this function to define the default value for an action parameter that requires extra metadata for the manifest. This function is a thin wrapper around pydantic.Field.

Parameters:
  • description (str | None) – A short description of this parameter. The description is shown in the user interface when running an action manually.

  • default (Any | None) – To set the default value of a variable in the UI, use this key. The user will be able to modify this value, so the app will need to validate it. This key also works in conjunction with value_list.

  • required (bool) – Whether or not this parameter is mandatory for this action to function. If this parameter is not provided, the action fails.

  • primary (bool) – Specifies if the action acts primarily on this parameter or not. It is used in conjunction with the contains field to display a list of contextual actions where the user clicks on a piece of data in the UI.

  • value_list (list | None) – To allow the user to choose from a pre-defined list of values displayed in a drop-down for this parameter, specify them as a list for example, [“one”, “two”, “three”]. An action can be run from the playbook, in which case the user can pass an arbitrary value for the parameter, so the app needs to validate this parameter on its own.

  • contains – Specifies what kind of content this field contains.

  • data_type – The type of variable. Supported types are string, password, numeric, and boolean.

  • allow_list (bool) – Use this key to specify if the parameter supports specifying multiple values as a comma separated string.

  • kwargs – additional kwargs accepted by pydantic.Field

  • column_name (str | None) – Optional name for the parameter when displayed in an output table.

  • cef_types (list | None)

  • sensitive (bool)

  • alias (str | None)

Return type:

Any

Returns:

returns the FieldInfo object as pydantic.Field

Parameters For on poll

On poll functions require a specific parameter class called OnPollParams. YYou should use this class as-is, instead of overriding it.

class soar_sdk.params.OnPollParams[source]

Canonical parameters for the special ‘on poll’ action.

Parameters:

data (Any)

start_time: int
end_time: int
container_count: int
artifact_count: int
container_id: str
is_manual_poll()[source]

Check if this is a manual poll execution (poll now) vs scheduled polling.

Return type:

bool

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Parameters for the Make Request Action

Make Request action functions require a specific parameter class called MakeRequestParams. You should use this class as-is, instead of overriding it.

class soar_sdk.params.MakeRequestParams[source]

Canonical parameters for the special make request action.

Parameters:

data (Any)

classmethod __init_subclass__(**kwargs)[source]

Validate that subclasses only define allowed fields.

Parameters:

kwargs (Any)

Return type:

None

model_post_init(_MakeRequestParams__context)[source]

Ensure model fields are validated after instance is created.

Parameters:

_MakeRequestParams__context (Any)

Return type:

None

http_method: str
endpoint: str
headers: str
query_parameters: str
body: str
timeout: int
verify_ssl: bool
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Action Outputs

Action outputs are defined in Pydantic models, which extend the ActionOutput class.

Much like parameters, outputs can have simple data types such as str or int, or be annotated with the OutputField() function to add extra metadata.

from soar_sdk.action_results import ActionOutput, OutputField

class CreateUserOutput(ActionOutput):
   uid: int = OutputField(cef_types=["user id"])
   create_date: str

Output models can be nested, allowing you to create complex data structures:

from soar_sdk.action_results import ActionOutput, OutputField

class UserDetails(ActionOutput):
   uid: int = OutputField(cef_types=["user id"])
   username: str
   email: str

class CreateUserOutput(ActionOutput):
   user_details: UserDetails
   create_date: str

class ListUsersOutput(ActionOutput):
   users: list[UserDetails]

You can add summary data and a result message to your action, by calling soar_sdk.abstract.SOARClient.set_message() and soar_sdk.abstract.SOARClient.set_summary(). Summary objects are also subclasses of ActionOutput, and you must register them in your action decorator:

from soar_sdk.action_results import ActionOutput, OutputField
from soar_sdk.abstract import SOARClient

class UserSummary(ActionOutput):
   total_users: int
   active_users: int
   inactive_users: int

@app.action(summary_type=UserSummary)
def list_users(params: ListUsersParams, soar: SOARClient[UserSummary]) -> ListUsersOutput:
    ...
    soar.set_summary(UserSummary(total_users=100, active_users=80, inactive_users=20))
    soar.set_message("Found 100 users")
    return ListUsersOutput(users=users)

Defining Action Outputs

class soar_sdk.action_results.ActionOutput[source]

Base class for defining structured action output schemas.

ActionOutput defines the JSON schema that an action is expected to output. It is translated into datapaths, example values, and CEF fields for integration with the SOAR platform.

Subclasses should define fields using type annotations and OutputField() for metadata. The schema is automatically converted to SOAR-compatible format for manifest generation and data validation.

Example

>>> class MyActionOutput(ActionOutput):
...     hostname: str = OutputField(
...         cef_types=["destinationHostName"],
...         example_values=["server1.example.com"],
...     )
...     port: int = OutputField(example_values=[80, 443, 8080])
...     is_secure: bool  # Automatically gets True/False examples
...
...     under_field: str = OutputField(
...         alias="_under_field"
...     )  # Model fields can't start with an underscore, so we're using an alias to create the proper JSON key

Note

Fields cannot be Union or Optional types. Use specific types only. Nested ActionOutput classes are supported for complex data structures.

Parameters:

data (Any)

model_config: ClassVar[ConfigDict] = {'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

soar_sdk.action_results.OutputField(cef_types=None, example_values=None, alias=None, column_name=None)[source]

Define metadata for an action output field.

This function creates field metadata that is used to describe how action output fields should look like, including CEF mapping and example values for documentation and validation.

Parameters:
  • cef_types (list[str] | None) – Optional list of CEF (Common Event Format) field names that this output field maps to. Used for integration with SIEM systems.

  • example_values (list[str | float | bool] | None) – Optional list of example values for this field, used in documentation and for testing/validation purposes.

  • alias (str | None) – Optional alternative name for the field when serialized.

  • column_name (str | None) – Optional name for the field when displayed in a table.

Note

Column name and order must be set together, if one is set but the other is not, an error will be raised.

Return type:

Any

Returns:

A Pydantic Field object with the specified metadata.

Example

>>> class MyActionOutput(ActionOutput):
...     ip_address: str = OutputField(
...         cef_types=["sourceAddress", "destinationAddress"],
...         example_values=["192.168.1.1", "10.0.0.1"],
...     )
...     count: int = OutputField(example_values=[1, 5, 10])

Make Request Action Output

For make request functions, we have provided a convenience class called MakeRequestOutput. This class extends the ActionOutput class and adds a status_code and response_body field. You can use this class to return the response from the make request action.

class soar_sdk.action_results.MakeRequestOutput[source]

Output class for make request action.

This class extends the ActionOutput class and adds a status_code and response_body field. You can use this class as is or extend it to add more fields.

Example

>>> class CustomMakeRequestOutput(MakeRequestOutput):
...     error: str = OutputField(example_values=["Invalid credentials"])

Note

The status_code field is used to return the HTTP status code of the response. The response_body field is used to return the response body of the response.

Parameters:

data (Any)

status_code: int
response_body: str
model_config: ClassVar[ConfigDict] = {'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

SOARClient

The SOARClient class is an app’s gateway to the Splunk SOAR platform APIs. It provides methods for creating and manipulating platform objects such as containers, artifacts, and vault items.

class soar_sdk.abstract.SOARClient[source]

Bases: Generic[SummaryType]

An API interface for interacting with the Splunk SOAR Platform.

abstract property client: Client

Generic HTTP client. Subclasses must define.

abstract property vault: Vault

Object governing interaction with the SOAR Vault API. Subclasses must define.

abstract property artifact: Artifact

Object governing interaction with the SOAR artifact API. Subclasses must define.

abstract property container: Container

Object governing interaction with the SOAR container API. Subclasses must define.

abstract get_executing_container_id()[source]

Return the current Container ID passed in the Connector Run Action JSON.

Return type:

int

abstract get_asset_id()[source]

Return the current Asset ID passed in the Connector Run Action JSON.

Return type:

str

get(endpoint, *, params=None, headers=None, cookies=None, timeout=None, auth=None, follow_redirects=False, extensions=None)[source]

Perform a GET request to the specific endpoint using the SOAR client.

Parameters:
Return type:

Response

post(endpoint, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=None, timeout=None, follow_redirects=True, extensions=None)[source]

Perform a POST request to the specific endpoint using the SOAR client.

Parameters:
Return type:

Response

put(endpoint, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=None, timeout=None, follow_redirects=True, extensions=None)[source]

Perform a PUT request to the specific endpoint using the SOAR client.

Parameters:
Return type:

Response

delete(endpoint, *, params=None, headers=None, cookies=None, auth=None, timeout=None, follow_redirects=False, extensions=None)[source]

Perform a DELETE request to the specific endpoint using the SOAR client.

Parameters:
Return type:

Response

get_soar_base_url()[source]

Get the base URL for the running SOAR system.

Return type:

str

Example

https://splunk.soar/

abstract update_client(soar_auth, asset_id, container_id=0)[source]

Hook to update the SOAR API client before any actions run with the input data.

An example of what this function might do is authenticate the API client.

Parameters:
  • soar_auth (SOARClientAuth)

  • asset_id (str)

  • container_id (int)

Return type:

None

abstract set_summary(summary)[source]

Set the custom summary object for the action run.

Parameters:

summary (TypeVar(SummaryType, bound= ActionOutput))

Return type:

None

abstract set_message(message)[source]

Set the summary message for the action run.

Parameters:

message (str)

Return type:

None

abstract get_summary()[source]

Get the summary for the action run.

Return type:

Optional[TypeVar(SummaryType, bound= ActionOutput)]

abstract get_message()[source]

Get the summary message for the action run.

Return type:

str

APIs

Artifact API

class soar_sdk.apis.artifact.Artifact[source]

Bases: object

API interface for managing SOAR artifacts.

This class provides methods to create and manage artifacts within SOAR.

soar_client

The SOAR client instance for API communication.

Type:

SOARClient

Parameters:

soar_client (SOARClient)

__init__(soar_client)[source]

Initialize the Artifact API interface.

Sets up the artifact interface with default artifact properties and initializes internal artifact storage for unauthenticated clients.

Parameters:

soar_client (SOARClient) – The SOAR client instance for API communication.

create(artifact)[source]

Create a new artifact in the SOAR platform.

Creates an artifact with the provided data, applying default values for common fields if not specified. For authenticated clients, the artifact is created via the REST API. For unauthenticated clients, the artifact is stored locally for testing purposes.

Parameters:

artifact (dict) – The artifact data to create. Must be JSON-serializable. Common fields include: - container_id: ID of the container to associate with - cef: Common Event Format data - label: Artifact label (defaults to ‘artifact’) - type: Artifact type (defaults to ‘generic’) - description: Human-readable description

Returns:

The ID of the created artifact.

Return type:

int

Raises:
  • ActionFailure – If the artifact data cannot be serialized to JSON.

  • SoarAPIError – If the API request fails or the artifact cannot be created. For unauthenticated clients, raised if no container_id is provided.

Example

>>> artifact_data = {
...     "container_id": 123,
...     "cef": {"sourceAddress": "192.168.1.1"},
...     "label": "ip",
...     "type": "network",
... }
>>> artifact_id = artifact_api.create(artifact_data)
>>> print(f"Created artifact with ID: {artifact_id}")

Container API

class soar_sdk.apis.container.Container[source]

Bases: object

API interface for managing SOAR containers.

This class provides methods to create and manage containers within the SOAR platform. Containers represent security incidents or cases that group related artifacts and serve as the primary organizational unit for security investigations.

soar_client

The SOAR client instance for API communication.

Type:

SOARClient

Parameters:

soar_client (SOARClient)

__init__(soar_client)[source]

Initialize the Container API interface.

Sets up the container interface with default container properties and initializes internal container storage for unauthenticated clients.

Parameters:

soar_client (SOARClient) – The SOAR client instance for API communication.

set_executing_asset(asset_id)[source]

Set the executing asset for containers created by this interface.

The executing asset ID will be automatically added to all containers created through this interface. This identifies which SOAR asset (app instance) is responsible for creating the container.

Parameters:

asset_id (str) – The ID of the asset that will be set as the executing asset.

Return type:

None

create(container, fail_on_duplicate=False)[source]

Create a new container in the SOAR platform.

Creates a container with the provided data, applying default values for common fields if not specified. For authenticated clients, the container is created via the REST API. For unauthenticated clients, the container is stored locally for testing purposes.

Parameters:
  • container (dict) – The container data to create. Must be JSON-serializable. Common fields include: - name: Container name/title - description: Human-readable description - severity: Severity level (low, medium, high, critical) - status: Container status (new, open, closed) - artifacts: List of artifacts to create with the container - asset_id: ID of the executing asset (required)

  • fail_on_duplicate (bool, optional) – If True, raise an exception when a duplicate container is found. If False, return the existing container ID. Defaults to False.

Returns:

The ID of the created or existing container.

Return type:

int

Raises:
  • ActionFailure – If container preparation fails or the container data cannot be serialized to JSON.

  • SoarAPIError – If the API request fails, the container cannot be created, or if fail_on_duplicate=True and a duplicate is found.

  • ValueError – If required fields (like asset_id) are missing.

Example

>>> container_data = {
...     "name": "Suspicious Network Activity",
...     "description": "Detected unusual traffic patterns",
...     "severity": "medium",
...     "artifacts": [
...         {
...             "cef": {"sourceAddress": "192.168.1.100"},
...             "label": "ip",
...             "type": "network",
...         }
...     ],
... }
>>> container_id = container_api.create(container_data)
>>> print(f"Created container with ID: {container_id}")

Vault API

class soar_sdk.apis.vault.Vault[source]

Bases: object

API interface for managing SOAR vault operations.

This class provides methods to interact with the SOAR vault system for file storage and retrieval. The vault is used to store files, attachments, and other binary data associated with containers and investigations.

phantom_vault

The underlying vault implementation for file operations.

Type:

VaultBase

Parameters:

soar_client (SOARClient)

__init__(soar_client)[source]

Initialize the Vault API interface.

Sets up the vault interface using the appropriate vault implementation based on the SOAR client configuration.

Parameters:

soar_client (SOARClient) – The SOAR client instance for API communication.

get_vault_tmp_dir()[source]

Get the vault temporary directory path.

Returns the file system path to the temporary directory used by the vault for storing temporary files during processing operations.

Returns:

The absolute path to the vault temporary directory.

Return type:

str

Example

>>> vault_tmp = vault_api.get_vault_tmp_dir()
>>> print(f"Vault temp directory: {vault_tmp}")
create_attachment(container_id, file_content, file_name, metadata=None)[source]

Create a vault attachment from file content.

Creates a new file in the vault using the provided content and associates it with the specified container. The content can be either string or binary data.

Parameters:
  • container_id (int) – The ID of the container to associate the attachment with.

  • file_content (Union[str, bytes]) – The content of the file to create. Can be text (str) or binary data (bytes).

  • file_name (str) – The name to give the file in the vault.

  • metadata (Optional[dict[str, str]], optional) – Additional metadata to associate with the file. Defaults to None.

Returns:

The vault ID of the created attachment.

Return type:

str

Example

>>> content = "This is a sample text file content"
>>> vault_id = vault_api.create_attachment(
...     container_id=123,
...     file_content=content,
...     file_name="sample.txt",
...     metadata={"source": "user_upload"},
... )
>>> print(f"Created attachment with vault ID: {vault_id}")
add_attachment(container_id, file_location, file_name, metadata=None)[source]

Add an existing file to the vault as an attachment.

Takes an existing file from the file system and adds it to the vault, associating it with the specified container. The original file is typically copied or moved to the vault storage.

Parameters:
  • container_id (int) – The ID of the container to associate the attachment with.

  • file_location (str) – The file system path to the existing file to add.

  • file_name (str) – The name to give the file in the vault.

  • metadata (Optional[dict[str, str]], optional) – Additional metadata to associate with the file. Defaults to None.

Returns:

The vault ID of the added attachment.

Return type:

str

Example

>>> vault_id = vault_api.add_attachment(
...     container_id=123,
...     file_location="/tmp/evidence.pdf",
...     file_name="evidence_report.pdf",
...     metadata={"type": "report", "classification": "internal"},
... )
>>> print(f"Added attachment with vault ID: {vault_id}")
get_attachment(vault_id=None, file_name=None, container_id=None)[source]

Retrieve attachment(s) from the vault.

Retrieves one or more attachments from the vault based on the provided search criteria. Can search by vault ID, file name, or container ID.

Parameters:
  • vault_id (Optional[str], optional) – The specific vault ID to retrieve. If provided, returns only that attachment. Defaults to None.

  • file_name (Optional[str], optional) – Search for attachments with this file name. Defaults to None.

  • container_id (Optional[int], optional) – Search for attachments associated with this container. Defaults to None.

Returns:

List of attachment objects containing

metadata and file content. Each object typically includes keys like ‘vault_id’, ‘name’, ‘size’, ‘metadata’, and ‘path’.

Return type:

list[VaultAttachment]

Example

>>> # Get a specific attachment by vault ID
>>> attachments = vault_api.get_attachment(vault_id="abc123")
>>>
>>> # Get all attachments for a container
>>> attachments = vault_api.get_attachment(container_id=123)
delete_attachment(vault_id=None, file_name=None, container_id=None, remove_all=False)[source]

Delete attachment(s) from the vault.

Removes one or more attachments from the vault based on the provided search criteria. Can delete by vault ID, file name, or all attachments in a container.

Parameters:
  • vault_id (Optional[str], optional) – The specific vault ID to delete. If provided, deletes only that attachment. Defaults to None.

  • file_name (Optional[str], optional) – Delete attachments with this file name. Defaults to None.

  • container_id (Optional[int], optional) – Delete attachments associated with this container. Defaults to None.

  • remove_all (bool, optional) – If True and container_id is provided, removes all attachments from the container. Defaults to False.

Returns:

List of vault IDs of the deleted attachments.

Return type:

list[str]

Example

>>> # Delete a specific attachment
>>> deleted = vault_api.delete_attachment(vault_id="abc123")
>>> print(f"Deleted attachments: {deleted}")
>>>
>>> # Delete all attachments from a container
>>> deleted = vault_api.delete_attachment(container_id=123, remove_all=True)
>>>
>>> # Delete attachments by filename
>>> deleted = vault_api.delete_attachment(file_name="temp_file.txt")

Data Models

class soar_sdk.models.artifact.Artifact[source]

Represents an artifact to be created during on_poll.

This class allows users to create artifacts when yielding from an ‘on poll’ action.

Parameters:

data (Any)

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

name: str | None
label: str | None
description: str | None
type: str | None
severity: str | None
source_data_identifier: str | None
container_id: int | None
data: dict[str, Any] | None
run_automation: bool
owner_id: int | str | None
cef: dict[str, Any] | None
cef_types: dict[str, list[str]] | None
ingest_app_id: int | str | None
tags: list[str] | str | None
start_time: str | None
end_time: str | None
kill_chain: str | None
to_dict()[source]

Convert the artifact to a dictionary (needed for save_artifact).

Return type:

dict[str, Any]

class soar_sdk.models.container.Container[source]

Represents a container to be created during on_poll.

This class allows users to specify container properties when yielding from an on_poll function.

Parameters:

data (Any)

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

name: str
label: str | None
description: str | None
source_data_identifier: str | None
external_id: str | None
severity: str | None
status: str | None
tags: list[str] | str | None
owner_id: int | str | None
sensitivity: str | None
artifacts: list[dict[str, Any]] | None
asset_id: int | None
close_time: str | None
custom_fields: dict[str, Any] | None
data: dict[str, Any] | None
due_time: str | None
end_time: str | None
ingest_app_id: int | None
kill_chain: str | None
role_id: int | str | None
run_automation: bool
start_time: str | None
open_time: str | None
tenant_id: int | str | None
container_type: str | None
template_id: int | None
authorized_users: list[int] | None
artifact_count: int | None
container_id: str | None
to_dict()[source]

Convert the container to a dictionary (needed for save_container).

Return type:

dict[str, Any]

class soar_sdk.models.vault_attachment.VaultAttachment[source]

Model representing a vault attachment.

This model is used to represent the metadata and content of a file stored in the SOAR vault. It includes attributes such as vault ID, file name, size, metadata, and the file path.

Parameters:

data (Any)

id: int
created_via: str | None
container: str
task: str | None
create_time: str
name: str
user: str
vault_document: int
mime_type: str | None
es_attachment_id: str | None
hash: str
vault_id: str
size: int
path: str
metadata: dict
aka: list[str]
container_id: int
contains: list[str]
open(mode='r')[source]

Open the vault attachment file.

Parameters:

mode (str) – The mode in which to open the file. Defaults to ‘r’.

Returns:

A file-like object for reading the attachment content.

Return type:

file

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class soar_sdk.models.view.ViewContext[source]

Model representing the context dictionary passed to view functions.

Parameters:

data (Any)

QS: dict[str, list[str]]
container: int
app: int
no_connection: bool
google_maps_key: bool | str
app_name: str | None
results: list[dict[str, Any]] | None
html_content: str | None
model_config: ClassVar[ConfigDict] = {'extra': 'allow'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class soar_sdk.models.view.ResultSummary[source]

Summary statistics for an app run.

Parameters:

data (Any)

total_objects: int
total_objects_successful: int
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Logging

exception soar_sdk.logging.getLogger[source]

Bases:

Get the recommended logger for SOAR SDK applications.

This is the standard logger you should use in all SOAR applications built with the SDK. It provides all normal Python logging capabilities with additional SOAR-specific features like progress logging and integration with the SOAR platform’s logging system.

The logger supports all standard Python logging levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) plus a custom PROGRESS level for tracking action progress.

Parameters:

name (str, optional) – The name for the logger instance. Defaults to “phantom_logger” for compatibility.

Returns:

A logger instance with SOAR-specific capabilities that

extends the standard Python logger interface.

Return type:

PhantomLogger

Example

>>> from soar_sdk.logging import getLogger
>>> logger = getLogger()
>>> logger.debug("Debug message for troubleshooting")
>>> logger.info("Informational message")
>>> logger.warning("Warning about potential issue")
>>> logger.error("Error occurred during processing")
>>> logger.progress("Action is 50% complete")
>>>
>>> # Logger supports all standard logging methods
>>> logger.setLevel(logging.DEBUG)
>>> logger.addHandler(custom_handler)
>>> logger.log(logging.INFO, "Custom level logging")

Note

This function returns a singleton instance, so multiple calls with the same name will return the same logger object for consistency across your application.

exception soar_sdk.logging.info[source]

Bases:

Log an informational message using the default SOAR logger.

Convenience function for info-level logging without needing to instantiate a logger. Use this for general informational messages about normal program execution and important events.

Parameters:
  • msg (str) – The log message. Supports Python string formatting with positional arguments.

  • *args (Any) – Variable length argument list for string formatting.

  • **kwargs (Any) – Arbitrary keyword arguments passed to the underlying logger.

Return type:

None

Example

>>> from soar_sdk.logging import info
>>> info("Action started successfully")
exception soar_sdk.logging.debug[source]

Bases:

Log a debug message using the default SOAR logger.

Convenience function for debug-level logging without needing to instantiate a logger. This function uses the singleton SOAR logger instance and supports all standard Python logging formatting and options.

Parameters:
  • msg (str) – The log message. Supports Python string formatting with positional arguments.

  • *args (Any) – Variable length argument list for string formatting.

  • **kwargs (Any) – Arbitrary keyword arguments passed to the underlying logger.

Return type:

None

Example

>>> from soar_sdk.logging import debug
>>> debug("Processing user: %s", username)
exception soar_sdk.logging.progress[source]

Bases:

Log a progress message using the default SOAR logger.

Convenience function for progress-level logging without needing to instantiate a logger. This is a custom logging level specific to SOAR that’s used to report action progress and status updates to users. Progress messages are typically displayed in the SOAR UI to show action execution status.

Parameters:
  • msg (str) – The progress message. Supports Python string formatting with positional arguments.

  • *args (Any) – Variable length argument list for string formatting.

  • **kwargs (Any) – Arbitrary keyword arguments passed to the underlying logger.

Return type:

None

Example

>>> from soar_sdk.logging import progress
>>> progress("Starting data collection...")

Note

Progress messages are displayed to end users in the SOAR interface, so they should be clear, informative, and user-friendly.

exception soar_sdk.logging.warning[source]

Bases:

Log a warning message using the default SOAR logger.

Convenience function for warning-level logging without needing to instantiate a logger. Use this for potentially harmful situations that don’t prevent the program from continuing but warrant attention.

Parameters:
  • msg (str) – The log message. Supports Python string formatting with positional arguments.

  • *args (Any) – Variable length argument list for string formatting.

  • **kwargs (Any) – Arbitrary keyword arguments passed to the underlying logger.

Return type:

None

Example

>>> from soar_sdk.logging import warning
>>> warning("API rate limit approaching")
exception soar_sdk.logging.error[source]

Bases:

Log an error message using the default SOAR logger.

Convenience function for error-level logging without needing to instantiate a logger. Use this for error conditions that are serious but allow the program to continue running.

Parameters:
  • msg (str) – The log message. Supports Python string formatting with positional arguments.

  • *args (Any) – Variable length argument list for string formatting.

  • **kwargs (Any) – Arbitrary keyword arguments passed to the underlying logger.

Return type:

None

Example

>>> from soar_sdk.logging import error
>>> error("Failed to connect to external API")
exception soar_sdk.logging.critical[source]

Bases:

Log a critical error message using the default SOAR logger.

Convenience function for critical-level logging without needing to instantiate a logger. Use this for very serious error events that may cause the program to abort or require immediate attention.

Parameters:
  • msg (str) – The log message. Supports Python string formatting with positional arguments.

  • *args (Any) – Variable length argument list for string formatting.

  • **kwargs (Any) – Arbitrary keyword arguments passed to the underlying logger.

Return type:

None

Example

>>> from soar_sdk.logging import critical
>>> critical("Database connection lost, cannot continue")

Exceptions

exception soar_sdk.exceptions.ActionFailure[source]

Bases: Exception

Exception raised when an action fails to execute successfully.

Parameters:
__str__()[source]

Return a formatted error message.

Return type:

str

exception soar_sdk.exceptions.ActionRegistrationError[source]

Bases: Exception

Exception raised when there is an error registering an action.

Parameters:

action (str)

exception soar_sdk.exceptions.AssetMisconfiguration[source]

Bases: ActionFailure

Exception raised when an asset is misconfigured.

Parameters:
__str__()[source]

Return a formatted error message.

Return type:

str

exception soar_sdk.exceptions.SoarAPIError[source]

Bases: ActionFailure

Exception raised when there is an error with the SOAR REST API.

Parameters:
__str__()[source]

Return a formatted error message.

Return type:

str