# Examples

## Basic Examples

The following examples show record creation and search using CURL.

### Authentication

Read the section on [Authentication](https://docs.cw.crisisworks.com/security-and-support/technical-reference/api-reference/authentication) for worked examples on obtaining and using authentication credentials.

### Connecting using Linux Bash

In `curl`:

```sh
curl -X GET "https://api.cw.crisisworks.com/api/json/ping" \
-H "Authorization: eyABCDEFG..." \
-H "X-Site: sandbox"
```

### Connecting using Windows PowerShell

In Windows PowerShell:

```powershell
Invoke-RestMethod `
  -Method Get `
  -Uri "https://api.cw.crisisworks.com/api/json/ping" `
  -Headers @{
    "Authorization" = "eyABCDEFG..."
    "X-Site"        = "sandbox"
  }
```

## Record manipulation and searching examples

The following examples show record creation and search.

### Record creation

The following example in Bash demonstrates how to create a register item record.

```shell
#!/bin/bash

# --- Configuration ---
HOST="api.cw.crisisworks.com"
SITE="mysite"
REGISTER_ID="recoveryInfrastructure"
TOKEN=$(cat ~/.crisisworks_token) # don't hardcode

# --- Create JSON payload ---
read -r -d '' PAYLOAD <<EOF
{
  "title": "Test submission via API",
  "requestor": "Scott Davey",
  "registerId": "$REGISTER_ID",
  "field1": "value1",
  "field2": "value2"
}
EOF

# --- Submit POST request ---
RESPONSE=$(curl -s -X POST "https://${HOST}/api/json/item" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json;charset=UTF-8" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "X-Site: ${SITE}" \
  -d "${PAYLOAD}")
```

### Record search

The following example in Bash demonstrates how to search items. This uses `curl` and `jq.`

```shell
#!/bin/bash

# --- Configuration ---
HOST="api.cw.crisisworks.com"
SITE="mysite"
REGISTER_ID="recoveryInfrastructure"
TOKEN=$(cat ~/.crisisworks_token) # don't hardcode

# -- Search term --
REGISTER_ID="recoveryCase"
CQL="is:active event:22 dateUpdated:>now-30d"
CQL_URL_ENCODED=$(jq -rn --arg x "$CQL" '$x|@uri')
#CQL_URL_ENCODED will look like this: is%3Aactive+event%3A22+dateUpdated%3A%3Enow-30d

# --- Submit GET request to search ---
RESPONSE=$(curl -s -X GET "https://${HOST}/api/json/item?registerId=${REGISTER_ID}&cql=${CQL_URL_ENCODED}'
  -H "Accept: application/json" \
  -H "Content-Type: application/json;charset=UTF-8" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "X-Site: ${SITE}")
  
# --- Parse the response with jq, etc ---

```

### Record updates

The following example shows how to update a record

```bash
#!/bin/bash

# --- Configuration ---
HOST="api.cw.crisisworks.com"
SITE="mysite"
REGISTER_ID="recoveryInfrastructure"
TOKEN=$(cat ~/.crisisworks_token) # don't hardcode

# --- This is the ID of the record being changed ---
ID=123

# --- Create JSON payload with the fields being changed ---
read -r -d '' PAYLOAD <<EOF
{
  "id": "$ID",
  "field1": "value1",
  "field2": "value2"
}
EOF

# --- Submit PUT request to update an existing item ---
RESPONSE=$(curl -s -X PUT "https://${HOST}/api/json/item/id/${ID}" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json;charset=UTF-8" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "X-Site: ${SITE}" \
  -d "${PAYLOAD}")
```

## Further Examples

The following examples provide quick integrations for popular requirements.

### Importing asset contacts via the API

Example of importing asset contacts from a CSV file.

Note the data used in this example is embedded CSV within the JSON data. If you have a CSV file, look at the next example.

```http
###
# Uses the asset contact import
#

POST /api/json/import

{
    "mode": "schedule",
    "dataType": "application/csv",
    "data": "Asset Code,Code Field,Title,First Name,Last Name,Company,Full Name,Address 1,Address 2,Address 3,Address 4,Email,Mobile,Phone,Registers,Notes,External ID,Relationship to Property\n43626,propnum,Mrs,Joy,Brown,ACMI Corp,,3 Bourke Street,Melbourne,VIC,3000,joy@acmicorp.com.au,0123 45667,,fpn,This is the CEO,,Owner\n43627,propnum,Mr,Fred,Smith,Datalink,,2 Foo Street,Fooville,,,fred.smith@foo.com,,,,,,\n43628,propnum,Mrs,Colleen,Davey,Colgate,,3 Elizabeth St,Melbourne,VIC,3000,colleen.davey@foo.com,,,,,,\n",
    "encoding": "plain",
    "selectedImportType": "Assets",
    "importType":"assets",
    "importRule": "assetContact",
    "rollbackOnError": false,
    "message": "Test Asset Contacts import",
    "regionId": "DEV1"
}


```

### Uploading an import file

The following example shows how you may upload a CSV file to the import API, using BASH.

```bash
#!/bin/bash

# Auth credentials
HOST="api.cw.crisisworks.com"
SITE="mysite"
TOKEN="your token"

# The file to send
IMPORT_FILE="myfile.csv"
IMPORT_TYPE="assets"
IMPORT_RULE="assetContact"
IMPORT_REGION="your site region"
IMPORT_MESSAGE="Import of asset contacts"

AUTH="Authorization: Bearer ${TOKEN}"
JSON="{\"mode\": \"schedule\",\"data\": \"$(base64 --input=${IMPORT_FILE})\",\"dataType\": \"application/csv\",\"encoding\": \"base64\",\"importType\": \"${IMPORT_TYPE}\",\"importRule\": \"${IMPORT_RULE}\",\"rollbackOnError\": false,\"message\": \"${IMPORT_MESSAGE}\",\"regionId\": \"${IMPORT_REGION}\"}"

curl -X POST \
     -d ${JSON} \
     -H 'Accept: application/json' \
     -H ${AUTH} \
     -H 'Content-Type: application/json\;charset=UTF-8' \
     -H 'X-Site: ${SITE}' \
     "https://${HOST}/api/json/import" 
```

Here is the equivalent in Windows Powershell.

```powershell
# Auth credentials
$HOST = "api.cw.crisisworks.com"
$SITE = "mysite"
$TOKEN = "your token"

# File and import metadata
$IMPORT_FILE = "myfile.csv"
$IMPORT_TYPE = "assets"
$IMPORT_RULE = "assetContact"
$IMPORT_REGION = "your site region"
$IMPORT_MESSAGE = "Import of asset contacts"

# Encode file to Base64
$Base64Data = [Convert]::ToBase64String([IO.File]::ReadAllBytes($IMPORT_FILE))

# Build the JSON payload
$Payload = @{
    mode = "schedule"
    data = $Base64Data
    dataType = "application/csv"
    encoding = "base64"
    importType = $IMPORT_TYPE
    importRule = $IMPORT_RULE
    rollbackOnError = $false
    message = $IMPORT_MESSAGE
    regionId = $IMPORT_REGION
} | ConvertTo-Json -Depth 10

# Set headers
$Headers = @{
    "Accept"        = "application/json"
    "Content-Type"  = "application/json;charset=UTF-8"
    "Authorization" = "Bearer $TOKEN"
    "X-Site"        = "$SITE"    
}

# Send the POST request
Invoke-RestMethod -Uri "https://$HOST/api/json/import" `
                  -Method Post `
                  -Headers $Headers `
                  -Body $Payload
```

### Adding images to Infrastructure Assessments

Attaching images to Register Items in Crisisworks happens in 2 steps.

1. **Upload the image**

First, the image needs to be be uploaded to Crisisworks. On successful upload, a file id is returned. Example Request

```bash
curl --location 'https://$HOST/api/json/file' \
     --header 'X-Site: $YOUR_SITE' \
     --header 'Authentication: Bearer $YOUR_TOKEN' \
     --form 'file=@"$PATH_TO_FILE"' \
     --form 'filename="test-api-upload.png"' \
     --form 'uuid="$YOUR_DEVICE_UUID"' \
```

Example Response:

```json
{"code":200,"message":"OK","id":"289"}
```

The file id 289 from the response is used to update the register item.

2. **Update the item to attached the file**\
   The specific item then needs to be updated to include the file. In the case of an Infrastructure Item, we are adding to the "**Damage Photos**"  - field name ***descriptionPhotos***

```bash
curl --location --request PUT 'https://$HOST/api/json/item/id/220' \
     --header 'X-Site: $YOUR_SITE' \
     --header 'Authentication: Bearer $YOUR_TOKEN' \
     --header 'Content-Type: application/json' \
     --data '{
         "uuid":"$YOUR_DEVICE_UUID",
         "token":"$YOUR_TOKEN",
         "type":"recoveryInfrastructure",
         "itemSchemaName":"default",
         "id": "220",
         "infrastructureType": "facility",
         "damageLevel": "6",
         "description":"<p>qew</p>",
         "priority":"2",
         "eventId":"26",
         "descriptionPhotos": [
             {
                 "id": "289",
                 "name": "test-api-upload.png",
                 "type": "image/png",
                 "path": null
             }
         ]
     }'
```

**Please note**, when updating an item, all the required fields also need to be included in the payload, so you will need to get this data before making any updates.

In the instance of Infrastructure Assessment, the required fields are:

| **Field Name**     | **Description**                             |
| ------------------ | ------------------------------------------- |
| id                 | The item ID of the record being updated.    |
| type               | Should be set to  "recoveryInfrastructure". |
| itemSchemaName     | Set to "default".                           |
| infrastructureType | Set to the existing value for this field.   |
| damageLevel        | Set to the existing value for this field.   |
| description        | Set to the existing value for this field.   |
| priority           | Set to the existing value for this field.   |
| eventId            | Set to the existing value for this field.   |

### Using Windows Command Prompt

Users may receive the following message when attempting to register an API Token when using Windows Command Prompt.

```json
{“code”:400, “message”:”Missing parameters”}
```

Windows command prompt has no support for single quotes like the Unix-like shells. As a result, you will need to replace the single quotes with double quotes AND escape them wherever necessary using back slashes.&#x20;

**Example**

```
curl -d "{\"uuid\": \"$YOUR_DEVICE_UUID\",\"platform\": \"Windows\",\"version\": \"1\",\"name\": \"$YOUR_NAME\",\"username\": \$YOUR_USERNAME\,\"password\": \"$YOUR_PASSWORD\"}" -H "Content-Type: application/json"
```
