# RPC APIs

## Overview

The system provides some Remote Procedure Call (RPC) commands to automate commands on the server.

They use GET for read actions and POST for write actions, and accept payload formats based on the adaptor in use (e.g. "json").

Example: calling the "ping" command:

```http
GET https://{{host}}/api/json/ping
X-Site: {{site}}
```

```json
{
  "status":200,
  "timestamp":"2025-07-22T19:50:12+10:00",
  "auth":null
}
```

## Ping

This command provides simple diagnostics, and is the "hello world" of API connectivity.

```http
GET https://{{host}}/api/json/ping
X-Site: {{site}}
```

```
"2016-10-24T08:41:07+00:00"
```

## Auth

This command is covered in depth in the section on [Authentication](https://docs.cw.crisisworks.com/security-and-support/technical-reference/api-reference/authentication).

## Asset Lookup

The Asset Lookup API provides search and lookup capability for Crisisworks API clients, using the same underlying algorithms used by the item import and asset matching systems.

There are two modes of operation:

* Single query mode — look up a single asset&#x20;
* Multiple query mode — process multiple items in a batch

{% hint style="info" %}
If looking up assets only to insert register item records, then consider using the `asset_lookup` input parameter when `POST` ing an item via `/api/json/item.` This will internally perform the same function and save an API call.
{% endhint %}

### Single Query Mode

```http
GET /api/json/asset-lookup?query={{query}}&output={{output}}&key={{val}}...
Authorization: Bearer {{token}}
X-Site: {{site}}
```

| Parameter | Purpose                                                                                                         |
| --------- | --------------------------------------------------------------------------------------------------------------- |
| query     | The string to look up as an asset                                                                               |
| output    | One of id or asset (default)                                                                                    |
| key=val   | A range of options can be supplied to fine-tune the system. See below for details of the available option keys. |

### Multiple Query Mode

To process multiple queries at once, construct a JSON payload and pass it via POST.

```http
POST https://{{host}}/api/json/asset-lookup
Authorization: Bearer {{token}}
X-Site: {{site}}

{
    "options": {
        // option key/vals go here
    },
    "query": [
        {
            "code": "{{reference code}}",
            "str": "{{query string}}"
        },
        // additional queries go here
    ]
}

```

The result of either call will be formatted in an object map of results, keyed based on the supplied code parameter, or as a 1-based record count if no code was supplied. The object will either be a full asset object (output=asset, or an asset ID output=id).

```json
{
    {{user reference code}}: {
        "reference": {{user reference code}},
        "query": {{user query}},
        "asset": {{asset return value}},
        "err": {{error message if available}}
    }
}
```

### Options

These additional options are available

| Parameter                              | Purpose                                                                                                                                                                                                                                                                                                                                                                                                         |
| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mode`                                 | One of the modes described below. The default is the soundex mode.                                                                                                                                                                                                                                                                                                                                              |
| `assetClass`                           | Optionally limits results to only those matching this asset class.                                                                                                                                                                                                                                                                                                                                              |
| `useExternalLookups`                   | Defaults to true, and engage the Google POI search as a last resort if other methods have failed.                                                                                                                                                                                                                                                                                                               |
| `maxRank`                              | For soundex searches, the maximum rank (1 = exact, 2 = all word in order, 3 = all words in any order). Default is 2.                                                                                                                                                                                                                                                                                            |
| `fallbackMode`                         | An optional second fallback mode for if the primary fails                                                                                                                                                                                                                                                                                                                                                       |
| `codeField`                            | For mode=code, this is the field to match upon (e.g. `propnum`)                                                                                                                                                                                                                                                                                                                                                 |
| `upgradeExternalLookupToInternalAsset` | <p>If the fallback POI system is invoked, you can optionally attempt to upgrade the result to a proper asset. To use this feature, you need to also specify thee <code>assetClass</code>. </p><p></p><p>You may also want to set the <code>geocoderOptions</code> to rooftop-level resolution (see below), otherwise you will get nearby but not exact properties if the search returns only a nearby road.</p> |
| `geocoderOptions`                      | <p>For <code>useExternalLookups</code>, this is a JSON options array to configure the plugin. The most useful option is restrict matches to houses only:<br><br><code>{"requiredFeatures": \["premise"]}</code></p>                                                                                                                                                                                             |

### Modes <a href="#available-modes" id="available-modes"></a>

When looking up assets, the `mode` can be one of the following:

* `id`: will match on the Crisisworks Asset ID
* `code`: will match on a variety of the `extra` asset codes
* `name`: will match on the asset name, code or lookup
* `contains`: will match on the asset's name using a contains string query
* `soundex`: will match on the asset's name using a sounds-like algorithm
* `geo`: will match on an asset by using the `geo` field in the input source and find an asset that contains it geo-spatially.
* `auto`: if there is no space in input, it sets the mode to `code`, otherwise it sets to `soundex`. This allows the user to specify either a code or an address. The space must be within the address string, and not at the start or end.

The mode for the UI when entering in addresses is `soundex`, and this is also the default for the import system for consistency.

#### Example: Look up a single address

```http
GET https://{{host}}/api/json/asset-lookup?query=555+Bourke+Street&output=id
Authorization: Bearer {{token}}
X-Site: {{site}}
```

Result

```json
{
    "1": {
        "reference": 1,
        "query": "555 Bourke Street",
        "asset": "123",
        "err": null
    }
}
```

#### Look up multiple addresses&#x20;

```http
POST https://{{host}}/api/json/asset-lookup
Authorization: Bearer {{token}}
X-Site: {{site}}

{
    "options": {
        "mode": "soundex",
        "useExternalLookups": true,
        "geocoderOptions": {
            "requiredFeatures": [
                "premise"
            ]
        }
    },
    "query": [
        {
            "code": 123,
            "str": "555 Bourke Street Melbourne"
        },
        {
            "code": 124,
            "str": "100000000 Bourke Streete Melbourne"
        }
    ]
}
```

Result:

```json
{
    "123": {
        "reference": 123,
        "query": "555 Bourke Street Melbourne",
        "asset": {
            "id": "1",
            "type": "Asset_Property",
            "code": "Datalink HQ",
            "regionId": null,
            "geo": {
                "points": [
                    {
                        "longitude": "144.95731",
                        "latitude": "-37.81617"
                    }
                ],
                "polygons": [],
                "linestrings": []
            },
            "source": "Google",
            "accuracy": "3",
            "friendly": "555 Bourke Street Melbourne 3000",
            "name": "555 Bourke Street Melbourne 3000",
            "friendlyType": "Property",
            "extraInfo": [],
            "infoLabel": null,
            "infoUrl": null,
            "regionName": null
        },
        "err": null
    },
    "124": {
        "reference": 124,
        "query": "100000000 Bourke Streete Melbourne",
        "asset": null,
        "err": "No matching asset found"
    }
}
```

## Import

An RPC command to schedule an import job, or to check the status of an existing import job.

To learn about importing, refer to: [Imports](https://docs.cw.crisisworks.com/system-administration/configuring-the-system/imports). This API provides an endpoint to replace the user interface version of the import process described in that support article.

To use this API, use `mode`  parameter:

1. Call the first time with a `mode` of `schedule` to queue the import job. A `processId` is returned.
2. Now, you can poll the API once a minute or so to check the status of that process, using the `status` mode.&#x20;

{% hint style="info" %}
Like all of our API commands, the `import` endpoint has a maximum request size of 10 MB.&#x20;

If your import file exceeds that then you have some options:

1. you can upload larger files via the UI, or&#x20;
2. you can split and upload your job in multiple sections.

Contact Datalink support for assistance on this.
{% endhint %}

### Commence an import

To schedule the import, set `mode` = `schedule`.

```http
POST https://{{host}}/api/json/import
Authorization: Bearer {{token}}
X-Site: {{site}}

{
    "mode": "schedule",
    "data": "...",
    "dataType": "application/csv",
    "encoding": "plain",
    "importType": "users",
    "importRule": "userimport",
    "rollbackOnError": false,
    "selectedImportType": "Users",
    "message": "Test import",
    "regionId": "DEV1"
}
```

<table><thead><tr><th>Key</th><th>Type</th><th width="116.17578125">Required</th><th>Default</th><th>Notes</th></tr></thead><tbody><tr><td><strong>General settings</strong></td><td></td><td></td><td></td><td></td></tr><tr><td>mode</td><td>string</td><td>Y</td><td></td><td>Must be set to schedule</td></tr><tr><td>importType</td><td>string</td><td>Y</td><td></td><td>One of <code>item</code>, <code>user</code> or <code>asset</code>. Most types are "item" imports.</td></tr><tr><td>importRule</td><td>string</td><td>Y</td><td></td><td>The rule name.<br><br>See the <a href="../../../../system-administration/configuring-the-system/imports#import-instructions">inline import documentation</a> Import user interface for details, or contact Datalink's service desk for information.</td></tr><tr><td>Data</td><td></td><td></td><td></td><td></td></tr><tr><td>data</td><td>string</td><td>Y</td><td></td><td>Either plaintext or a base64-encoded string of import data</td></tr><tr><td>dataType</td><td>string</td><td>N</td><td></td><td>Not usually required, but can help the import system determine the file type in the event it cannot automatically determine the file type.<br><br>Advice can be provided by Datalink's service desk if needed.</td></tr><tr><td>encoding</td><td><code>plain</code>|<code>base64</code></td><td></td><td><code>plain</code></td><td>Sets the type of <code>data</code>. For CSV imports use <code>plain</code>, otherwise base64 encode the file.</td></tr><tr><td><strong>Rule processing</strong></td><td></td><td></td><td></td><td></td></tr><tr><td>matchingId</td><td>string</td><td>N</td><td></td><td>This is the name of the field used to match existing records. Valid field names are based on the record being imported.<br><br>Examples for importing register items:<br><br>- <code>id</code>: is the Crisisworks ID of the record<br>- <code>code</code>: for register items, this is the asset's configured code (e.g. PROPNUM). This configuration is system-wide, so consult Datalink's service desk for your system's configuration. <br>- <code>assetId</code>: for register items, this is the linked Asset ID of the record</td></tr><tr><td>overwriteRule</td><td>string</td><td>N</td><td></td><td>Defines the rule used for overwriting matched records:<br><br>- <code>updateOnly</code>: If a record matches then update it. If it doesn't match, do not insert it.<br>- <code>insertOnly</code>: If a record matches then skip it. If it doesn't match, insert it.<br>- <code>updateAndInsert</code>: If a record matches then update it. If it doesn't match, insert a new record.<br>- <code>deleteAndInsert</code>: Delete all existing records and insert all records as new records.</td></tr><tr><td>eventId</td><td>integer</td><td>Depends</td><td></td><td>Required for import types that are stored within events (e.g. items, contacts, cases, documents). Not required for import types such as users, assets and resources.</td></tr><tr><td>regionId</td><td>integer</td><td>Depends</td><td></td><td>Required for import types that are stored within events (e.g. items, contacts, cases, documents). Not required for import types such as users, assets and resources.</td></tr><tr><td><strong>Import settings</strong></td><td></td><td></td><td></td><td></td></tr><tr><td>dryRun</td><td>integer (0 or 1)</td><td>N</td><td>0</td><td>Set to 1 to have the system perform a dry run</td></tr><tr><td>rollbackOnError</td><td>integer (0 or 1)</td><td>N</td><td>0</td><td>Set to 1 to have the import system roll back the changes if any error occurs</td></tr><tr><td>importTag</td><td>string</td><td>N</td><td></td><td>If set, all records will be tagged with this tag.</td></tr><tr><td>message</td><td>string</td><td>N</td><td></td><td>If set, the audit log will contain this message.</td></tr><tr><td></td><td></td><td></td><td></td><td></td></tr></tbody></table>

#### **Supported data types**

This API receives its data in a JSON payload, however imports are generally accepted in different formats such as Shapefile or CSV. The API accepts its data by specifying the parameters **data**, **dataType** and **encoding**.

The two most common file formats are CSV and Shapefile.&#x20;

#### For CSV

1. prepare the data by escaping special characters as per the JSON specification (e.g. backslash quotes, carriage returns, etc),
2. supply the escaped data in `data`
3. set `encoding` to `plain`&#x20;
4. set `dataType` to `csv`

#### For Shapefile

1. zip the Shapefile files into a single zip file
2. base64 encode the zip file
3. supply the base64 encoded string as `data`
4. Set encoding to `base64`&#x20;
5. Set the dataType to `zip`

The API will return an ID on success. This ID can be used to query the progress of the import job.

### Check the progress of an import job

```
POST /api/json/import

{
    "mode": "status",
    "id": <processid>
}
```

If called without an `id` parameter, the API will return a summary of all import jobs. If called with an `id` parameter, it will return specifics about that job.

You will typically poll this API once a job has been submitted, until the job completes. Please poll no more than once per 60 seconds to not disrupt the user experience.

| Key           | Type    | Description                                                                           |
| ------------- | ------- | ------------------------------------------------------------------------------------- |
| code          | integer | An HTTP result code. Expect 200 for success.                                          |
| id            | integer | The process ID                                                                        |
| status        | string  | A simplified process status, one of `NOT_STARTED`, `RUNNING`, `COMPLETE` or `FAILED`. |
| dateCreated   | date    | The date in GMT that the job was scheduled                                            |
| dateCompleted | date    | The date in GMT that the job finished processing                                      |
| userId        | string  | The user that the job ran as                                                          |
| result        | string  | The result of the import job, as an HTML formatted string                             |

## Report

The reportAPI provides report run automation, and allows users to run a report, check its run status and download the results.

To run a report and retrieve the results:

1. run it — triggers the report to run asynchronously
2. check status — monitor the report execution via polling to know when it has completed
3. fetch it — pull down the report results in a number of formats

### Run a report

To enqueue a report to run, call the following API.

#### Run a report by ID

This method is simplest, and allows you to run a report and supply report parameters.

```http
POST https://{{host}}/api/json/report
Authorization: Bearer {{token}}
X-Site: {{site}}

{
    "mode": "run",
    "reportId": 2,
    "params": {
      // contact Datalink support for assistance with these
    }
}
```

This API call accepts a JSON document with either a `reportId` of a known report in the system, or a `reportInstanceId` of a previous run to repeat. It also optionally allows `params` to be specified to provide detailed configuration of the report.

If successful, the result will return the report instance ID scheduled to run.

```json
{
  "code": 200,
  "result": "Report instance scheduled",
  "id": "100203"
}
```

#### **Run a report based on a previous run ID**

This method is most convenient because you can set up a report’s parameters via the reporting user interface, and then re-run it with the same set of filters, columns and format options. If `params` are provided, they will overwrite any params of the report instance being re-run.

<pre class="language-http"><code class="lang-http">POST https://{{host}}/api/json/report
Authorization: Bearer {{token}}
X-Site: {{site}}

<strong>{
</strong>    "mode": "run",
    "reportInstanceId": 212
}
</code></pre>

If successful, the result will return the report instance ID scheduled to run.

```json
{
  "code": 200,
  "result": "Report instance scheduled",
  "id": "100203"
}
```

### Check a report's status

Reports run asynchronously and some can take a while to run, so you can poll this API to check the job’s status.

```http
POST https://{{host}}/api/json/report
Authorization: Bearer {{token}}
X-Site: {{site}}

{
    "mode": "status",
    "id": 1
}
```

When initially queued the results will return a QUEUED status:

```json
{
  "code": 200,
  "id": "1",
  "status": "QUEUED",
  "dateRun": null,
  "dateCompleted": null,
  "userId": "lance",
  "result": "Report queued for execution",
  "timeTaken": null,
  "rowCount": null,
  "params": {}
}
```

When complete it will return additional data:

```json
{
  "code": 200,
  "id": "1",
  "status": "COMPLETED",
  "dateRun": "2021-08-27T06:29:10+00:00",
  "dateCompleted": "2021-08-27T06:36:35+00:00",
  "userId": "lance",
  "result": "Report execution completed.",
  "timeTaken": "445",
  "rowCount": "1861",
  "params": {}
}
```

Note the `params` attribute which will show the params used to run the report. This is useful to return a structured set of parameters from a previous report run, which you can then modify when crafting your own API calls.

### Fetch completed report data

To fetch report data, call the API in `fetch` mode and specify the `reportInstanceId` and a `format`.

```http
POST https://{{host}}/api/json/report
Authorization: Bearer {{token}}
X-Site: {{site}}

{
    "mode": "fetch",
    "reportInstanceId": 1,
    "format": "json"
}
```

The results of the `/api/json/report` call with the `fetch` mode is a JSON document of the same shape as for the `status` mode, but with an additional `contents` property.

This contents property contains one of the following:

* for the `json` format, the report data in a nested JSON format
* for all other formats, the binary file is returned in Base-64 encoding

For example, the above example will return the following:

```json
{
  "code": 200,
  "id": "1",
  "status": "COMPLETED",
  "dateRun": "2021-08-27T06:29:10+00:00",
  "dateCompleted": "2021-08-27T06:36:35+00:00",
  "userId": "lance",
  "result": "Report execution completed. ",
  "timeTaken": "1",
  "rowCount": "2",
  "params": null,
  "contents": {
    "$schema": "https://crisisworks.com/schemas/analytics-export-v1.json#",
    "name": "My Report",
    "meta": [
      {
        "key": "summary",
        "label": "Summary",
        "value": null,
        "display": "Not set"
      },
      // ... other meta fields ...
    ],
    "filter": [
      {
        "key": "startDate",
        "label": "From date",
        "value": null,
        "display": "Not set"
      },
      ... other filters ...
    ],
    "spec": [
      {
        "key": "auditActionLogTimestamp",
        "label": "Time",
        "type": "timestamp"
      },
      {
        "key": "auditActionTitle",
        "label": "Title",
        "type": "string"
      },
      // ... other field definitions ...
    ],
    "data": [
        {
          "auditActionLogTimestamp": 1630040582,
          "auditActionTitle": "This is an example line item 1",
          // ... more fields as per 'spec' ...
        },
        {
          "auditActionLogTimestamp": 1630040582,
          "auditActionTitle": "This is an example line item 2",
          // ... more fields as per 'spec' ...
        }
    ]
  }
}  
```

This JSON format provides a tabular (e.g. two-dimensional) data structure in a parsable format, along with a built-in data dictionary for each field.

* `$schema` — a JSON Schema document URL to validate the content
* `name` — the name of the report
* `meta` — a series of metadata values indicating the data quality of the report (as set in the report instance at run-time)
* `filter` — all available report filters and their set values for this report
* `spec` — a data dictionary of all the fields contained in each data row
* `data` — the rows of data

By changing the `format` to any other supported format, the data is encoded into Base-64 and returned.

```json
{
  "code": 200,
  "id": "1",
  "status": "COMPLETED",
  "dateRun": "2021-08-27T06:29:10+00:00",
  "dateCompleted": "2021-08-27T06:36:35+00:00",
  "userId": "lance",
  "result": "Report execution completed. ",
  "timeTaken": "445",
  "rowCount": "1861",
  "params": null,
  "contents": "YXVkaXRBY3Rpb25Mb2dUaW1lc3RhbXAsYXVkaXRBY3Rpb25UaXRsZSxhdWRpdEFjdGlvblVzZXJJZCxhdWRpdEFjdGlvbkxvZ0l0....",
  "format": "csv"
}
```

### **Fetching data using the binary adapter**

{% hint style="warning" %}
This api option is not currently supported in V5 of the software.
{% endhint %}

Use the `binary` API adapter to download the report file in its raw format.

Available formats:

| Format   | Description                                       |
| -------- | ------------------------------------------------- |
| **csv**  | A CSV representation of the data                  |
| **html** | A formatted HTML report (compatible reports only) |
| **json** | The JSON representation above                     |
| **xlsx** | An Excel spreadsheet                              |
