> For the complete documentation index, see [llms.txt](https://cortex-docs.paloaltonetworks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cortex-docs.paloaltonetworks.com/python-development-quick-start-guide/cortex-xsoar-python-development-quick-start-guide/script-code-snippets.md).

# Script Code Snippets

The following code snippets perform common actions that you can modify as needed.

### Basic Automation Template

This template can be used to create a new automation, replacing the standard boilerplate provided.

```programlisting
def main():
    try:
    except Exception as ex:
        demisto.error(traceback.format_exc())
        return_error("Failed to execute command: " + str(ex))
if __name__ in ("__main__", "__builtin__", "builtins"):    
    main()
```

### Return Results to War Room and Incident Context

The Common Server Python **`return_results()`** function outputs data to both the War Room and incident context. A simple example is to display context data as Markdown in the War Room and update context. The Common Server Python functions **`tableToMarkdown()`** and **`CommandResults()`** are used to prepare the results and then pass them to **`return_results()`**.

```programlisting
markDown   = tableToMarkdown("Table Name", outputContext)
resultsOut = CommandResults(
    readable_output      = markDown,
        outputs_prefix       = "context.path",
        outputs_key_field    = "contextFieldName",
        outputs          = outputContext
)
return_results(resultsOut)
```

### Log Errors to Cortex XSOAR Server Log

The Demisto class provides the **`demisto.error()`** function that logs errors to the Cortex XSOAR server log.

```programlisting
message = "An error message to log"
argDict = {'name': "MyAutomationName", 'value': 0}
demisto.error(message, argDict)
```

### Log Errors to the War Room

The Common Server Python **`return_error()`** function creates error entries in the War Room.

```programlisting
message     = "An error message to display" 
return_error(message)
```

An exception string can be included in the message if using try/catch to handle exceptions.

```programlisting
try:
    ## code  ##
except Exception as ex:
    message    = "An error message to display: "
        return_error(message + str(ex))
```

### Access Arguments

The Demisto class provides the **`demisto.args()`** function to retrieve arguments passed to an automation script, for example if a Cortex XSOAR playbook task calls the automation script.

To retrieve multiple arguments in a Python dictionary:

```programlisting
argDict    = demisto.args()
argValue1  = argDict['argumentName1']
argValue2  = argDict['argumentName2']
```

If only a single argument is required, access the argument directly with a key name:

```programlisting
argValue    = demisto.args()['argumentName']
```

### Access Incident Objects

The **`demisto.incident()`** function returns a Python dictionary of the incident field values.

```programlisting
incidentDict = demisto.incident()
```

If only a single field is required, access the field directly with a key name.

```programlisting
fieldValue   = demisto.incident()['fieldName']
```

### Find, Set, and Create Indicators

The **`findIndicators`** command queries for indicators.

```programlisting
findParam = {
    'fromdate':"2021-10-27T15:00:00+07:00",
    'todate':   "2021-10-28T15:00:00+07:00",
    'query':    "type:file"
}
results = demisto.executeCommand("findIndicators", 
    findParam)[0]['Contents']
```

A request to the Cortex XSOAR API (required if applying tags) updates the indicator.

```programlisting
body = {
    'CustomFields': {'tags': ["newtag"]},
    'id':       str(indId),
    'indicator_type':   indicator['indicator_type'],
    'value':        indicator['value']      
}
demisto.executeCommand("core-api-post",
    {'uri':"/indicator/edit", 'body':body})
```

### Get and Set Incident Fields

To get incident field values, the **`demisto.incident()`** function returns a dictionary of all fields or a single field.

```programlisting
fieldDict    = demisto.incident()
fieldValue   = demisto.incident()['details']
```

To set the field value, the **`demisto.executeCommand()`** function passes a dictionary of field names and field values.

```programlisting
fieldValue = "new field value"
demisto.executeCommand("setIncident", {'details': fieldValue})
```

### Get and Set Incident Custom Fields

Incidents may include custom fields created by the Cortex XSOAR user. These are contained within the incident object as a sub-dictionary. If there are multiple fields, use the **`demisto.incident()`** function with **`CustomFields`** as the key name. Individual custom field values can then be retrieved from the dictionary.

```programlisting
customDict    = demisto.incident()['CustomFields']
fieldValue    = customDict['fieldName']
```

If only a single custom field is required:

```programlisting
fieldValue    = demisto.incident()['CustomFields']['fieldName']
```

To set a custom field, a Python dictionary object with a key name that matches the field name of the value is converted to a JSON string and the **`demisto.executeCommand()`** function is called.

```programlisting
value = json.dumps({'fieldname': fieldValue})
demisto.executeCommand("setIncident", {'customFields': value})
```

{% hint style="info" %}

### Note

When setting custom fields use **`customFields`** , and when retrieving custom fields use **`CustomFields`**.
{% endhint %}

### Get and Set Grid Fields

Grid fields display data tables.

{% hint style="info" %}

### Note

Column names must be the machine name (lowercase version of the display name) for the column or the data is ignored.
{% endhint %}

```programlisting
gridDict = {
    "column1": "This is column 1",
    "column2": "This is column 2"
}
gridRows = json.dumps({ "gridfield": gridDict })
results  = demisto.executeCommand("setIncident", {
    'customFields': gridRows
})
```

### Get and Set Incident Context

To get a context value:

```programlisting
contextDict   = demisto.context()
contextValue  = contextDict['context.path']
```

To set a context value, use the **`demisto.setContext()`** function:

```programlisting
contextPath   = 'context.path'
contextValue  = "context value"
demisto.setContext(contextPath, contextValue)
```

### Get and Set Lists

Lists are separate from incident fields and context, and store data for use by automations. Two common list actions are getting and setting values in the list.

```programlisting
listDict = [
    { 'Name1': "val11", 'Name2': "val12",'Name3': "val13"},
    { 'Name1': "val21", 'Name2': "val22",'Name3': "val23"},
    { 'Name1': "val31", 'Name2': "val32",'Name3': "val33"},
    { 'Name1': "val41", 'Name2': "val42",'Name3': "val43"}
]
demisto.executeCommand("setList", {
    'listName': "Name of List",
    'listData': listDict})
listDict = demisto.executeCommand("getList", {
    'listName':"Name of List"
})[0]['Contents']
```

### Invoke the Cortex XSOAR REST API

The Cortex XSOAR REST API is available for automation tasks that require different access than what is provided through automation scripts and commands. See the [API documentation](/xsoar-6-api/cortex-xsoar-6.x-apis/cortex-xsoar-6-apis-overview.md) for each endpoint to determine the parameters to include in the body of a request.

To invoke an API, specify the endpoin&#x74;**`uri`**, in this case /incident, and provide the body of the request in a dictionary. The following sample creates an incident with the name "Incident Name”.

```programlisting
requestDict = {'name': "Incident Name"}
response    = demisto.executeCommand(
    "core-api-post", 
    {'uri': "/incident", 'body': requestDict}
)[0]['Contents']['response']
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://cortex-docs.paloaltonetworks.com/python-development-quick-start-guide/cortex-xsoar-python-development-quick-start-guide/script-code-snippets.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
