Python operations

API Object#

Run#

api.run(operation, parameters, options)

Runs an operation.

ArgumentTypeDescription
operationStringThe name of the operation to be run
parametersDictionary(Optional) an object containing any operation-defined parameters
optionsDictionary(Optional) additional options:limit - limits the number of results returned. Unbounded if undefined.

Note: If you are passing in operation and options, but no parameters, you will need to pass in an empty parameters dictionary.

Returns (List): Returns the operation results or throws any operation failure.

Examples

api.run("this.hello_world")
// => [{"Hello": "World"}]

api.run("this.restart_vm", { "id": params.userId })
// passing a parameter to an operation
// => [{id:1234, ...}]

api.run("this.metrics", {}, {"limit": 10})
// => returns result array of size 10

Run bulk#

api.runBulk(operations)

Runs any number of operations in parallel and waits for all to complete, or any to fail, before returning.

ArgumentTypeDescription
operationsList of dictionariesEach dictionary describes one of the operations to run in parallel (See below)

Each dictionary in operations has the following properties:

FieldTypeDescription
operationStringThe name of the operation to be run
parametersDictionary(Optional) an object containing any operation-defined parameters
optionsDictionary(Optional) additional options - limit: limits the number of results returned, infinity if undefined.

Returns (List): Returns a list where each element is the result from one of the parallel operations. If any fail, an error is thrown.

Example

results = api.runBulk([{
"operation": "this.hello_world"
}, {
"operation": "this.restart_vm",
"parameters": { "id": params.userId }
}, {
"operation": "this.metrics",
"options": { "limit": 10 }
}])

results[0] // => [{"Hello": "World"}]
results[1] // => [{id:1234, ...}]
results[2] // => result list of size 10

Query#

api.query(query, parameters)

Run a SQL query. Note that if you have dynamic fields in your query, using parameters is highly recommended to avoid escaping issues and SQL injection attacks.

ArgumentTypeDescription
queryStringThe SQL query to be run
parametersDictionary(Optional) an object containing any operation-defined parameters

Returns (List): Returns the query results or throws any query failure.

Example

api.query("select * from this.hello_world")
// => [{"Hello": "World"}]

api.query("select * from this.restart_vm where id=@userId", {"userId": params.userId});
// => [{id:1234, ...}]

Action logs#

Currently, Transposit actions are sometimes named workflows in the Transposit Developer Platform. We understand this can be confusing and will be making updates to make this experience better in the future.

Important: All actions require a context parameter in their deployed 'execute' operation. Contextual information, such as information about the activity and and input parameters, will be accessible via this parameter.

workflow.log.<type>({display}, standardOutputParams={}, customOutputParams={})

workflow.log.<type>("summary")

workflow.log is used to log messages and provide action output. You can control the look of the log, as well as the overall output of the action, via the binding parameters. All log bindings return null.

Display#

The display object contains information used to render the message in different clients. Its properties are optional, but providing at least a summary is strongly recommended.

ArgumentTypeDescription
summaryStringA summary of the information presented
descriptionStringA longer description
htmlUrlsArrayAny html URLs used in the message
imageUrlsArrayAny image URLs used in the message
blockKitOverrideObjectSlack block kit blocks to be used to display the message in place of the other fields where applicable

Standard output parameters#

standardOutputParams is an object whose schema is defined and enforced by Transposit. Currently, it has no defined schema.

Custom output parameters#

customOutputParams is a place to store information, like the results of any api calls made, in an organized format. Soon, you will be able to access this object in subsequent actions.

Sensitive#

If you're connected to Slack and you'd like the results of the run to be shown only to you, use the sensitive keyword argument.

Examples

    output_blocks = api.run("block_kit_lib.markdown_text_section", {"text": f"This action has completed! And this text *is formatted*"})
display = {"summary": "Done",
"description": "A longer description with some more details",
"htmlUrls": ["https://myLink"],
"imageUrls": ["https://someImageLink"],
"blockKitOverride": output_blocks}
standardOutputParams = {}
customOutputParams = {"action outputs": "go here"}
sensitive = False
workflow.log.done(display, standardOutputParams, customOutputParams, sensitive)

If you do not require any special formatting, you can provide a string shorthand in place of the display object. Block kit to render in Slack and the Web UI will automatically be created. You may also omit standardOutputParams and customOutputParams if you don't have any.

    workflow.log.done("This action has completed!")

Done#

workflow.log.done({display}, standardOutputParams={}, customOutputParams={})

Log results and mark the successful completion of an action.

Once and only once: This binding should be used once and only once in a single action run:

  • At least once: It is highly encouraged that done is used at least once. The done log is what signals to Transposit that any chained actions may continue to run.
  • Not more than once: The action will throw an error if it is used more than once. This is because the done binding is intended to mark the true end of an action.
  • Oneof done or fail: The action will also fail if done is called after fail because an action cannot both finish and fail.

Fail#

workflow.log.fail({display}, standardOutputParams={}, customOutputParams={})

Log a failure of and mark the completion of an action as failed.

Once and only once: This binding should be used once and only once in a single action run:

  • Not more than once: The action will throw an error if the fail binding is used more than once in a single run. This is because the fail binding is intended for true failures of the action itself. If you find yourself wanting to write multiple fails for a single code path, you should instead use warn.
  • Oneof done or fail: The action will also fail if fail is called after done because an action cannot both finish and fail.

Warn#

workflow.log.warn({display})

Log a warning message. This includes errors that do not cause the entire workflow to fail (see above).

Status#

workflow.log.status({display}, groupId=<string>)

Log a status update. Use the groupId keyword argument to group together status updates from a specific action.

Info#

workflow.log.info({display})

Log any other information.

Data Parsers#

dataParser.response({display}, standardOutputParams={}, customOutputParams={})

dataParser.response("summary")

Data parser bindings take almost the same parameters as log bindings, but the binding and its output are used slightly differently. See the data parser documentation for more information.

Environment Variables#

Transposit operations can programmatically access environment variables based on environment variables set up when you add an action to a runbook.

get#

env.get(key)

Retrieves the value set for the specified environment variable.

ArgumentType
keyStringthe key of the environment variable.

Returns (String/Number/Boolean/Null): Returns a value matching the value that was set in the UI. If the key does not match a value defined in the schema, an exception is thrown. If no saved value exists, and no default value is defined, returns Null.

Examples

env.get("stringKey")
// => "stringValue"
env.get("numberKey")
// => 88888
env.get("booleanKey")
// => True
env.get("unsetKey")
// => null
env.get("undefinedKey")
// => exception

getBuiltin#

env.getBuiltin()

Returns (Dictionary): Returns a Dictionary containing builtin environment variables.

Examples

env.getBuiltin()
// => {
// "appUrl": "https://example-hd39c.transposit.io",
// "requestId": "bcbfa9b1-f9a9-45c7-aeaa-6e903153cd9e"
// }

Available Python packages#

Transposit provides you access to all of the Python Standard Library, as well as popular Python packages such as pytz. Below are some examples of useful modules:

import json
data = {"hello": "world"}
print(json.dumps(data))
// => "{"hello": "world"}"
import pytz, datetime
us_eastern_tz = pytz.timezone('US/Eastern')
dt = us_eastern_tz.localize(datetime.datetime(2020, 11, 2, 15, 25, 0))
print(dt)
// => "2020-11-02 15:25:0-05:00"
import base64
output_text = "Hello World"
output_text_bytes = output_text.encode("utf-8")
print(output_text_bytes)
// => "b'Hello World'"

base64_bytes = base64.b64encode(output_text_bytes)
print(base64_bytes)
// => "b'SGVsbG8gV29ybGQ='"

base64_output_text = base64_bytes.decode("utf-8")
print(base64_output_text)
// => "SGVsbG8gV29ybGQ="
import re
input = "abc123abc"
api.log(re.sub("abc", "def", input))
// => "def123def"

If you need a different Python package for your application to work, please reach out to use at support@transposit.com and let us know what you are looking for.