MATRIX CALCULATION API

## ##

MATRIX CALCULATION API

API Details

IDs

Where ids are provided, they must be unique for the given type. Using the same id name for different types is supported, but discouraged. IDs must conform to the following: – May only contain alpha-numeric characters, “-” or “_”. – Are case-sensitive.

Optional types:

If a type parameter is suffixed with “?” the it is nullable. This means it can be provided, and be explicitly set to null, or it can be simply left out of the JSON.

Example:

{
    data: { 
        id: string,
        name: string?
    }
}

In this case, the “name” parameter in the data object is optional, and one can either explicitly provide null as its value, or can simply omit it from the JSON if one chooses. However, the id parameter is not marked as optional, and so one must provide a valid string value for it, otherwise the request would be rejected.

Data Types:

Latitude/Longitude: Must be provided in signed degrees format. Examples:

  • Dublin, Ireland: 53.339561, -6.271600
  • Tokyo, Japan: 35.659439, 139.700612
  • Auckland, New Zealand: -36.846506, 174.763439
  • Rio de Janeiro, Brazil: -22.951876, -43.210766
  • New Orleans, USA: 29.946585, -90.069699
  • North Pole: 90.0, 0

Timestamps:

Instants in time are provided in “YYYY-MM-DD HH:mm:ss” format. e.g. “2017-12-25 17:59:00”. All instants are expected to be given in UTC timezone.

Client Crentials

Every request to the RO API requires that you send your RO Account’s client credentials in the headers along with your request. Client credentials include a Client ID and a Client Secret. You can get these details from the “Account” page on the admin dashboard.


Calculate Matrix

The Calculate endpoint allows you to request a cost matrix calculation. This endpoint

Endpoint: POST https://api.squareroute.io/api/v1/ro/calculate

Headers:

Accept:   "application/json"
Content-Type: "application/json"
Client-Id: {INSERT CLIENT ID}
Client-Secret: {INSERT CLIENT SECRET} 

The following is an example JSON body for requesting a Cost Matrix for 5 locations in Dublin.

Example Matrix Calculation Request Body:

{
    "data": {
        "ro_account_id": "a1b2c3d4",
        "callback_url": "https://api.example.com/api/squareroute/ro-event/callback",
        "include_ro_result_in_callback": false,
        "task": {
            "calculation_type": "COST_MATRIX",
            "locations": [
                {
                    "id": "73-dame-street",
                    "name": "The Olympia, 72 Dame Street",
                    "lat": 53.344193,
                    "lng": -6.266069
                },
                {
                    "id": "24-wexford-street",
                    "name": "Whelans, 24 Wexford Street Dame Street",
                    "lat": 53.336586,
                    "lng": -6.265628
                },
                {
                    "id": "82-parnell-street",
                    "name": "Fibbers, 82 Parnell Street",
                    "lat": 53.352970,
                    "lng": -6.260457
                },
                {
                    "id": "15-ormond-quay-upper",
                    "name": "Sin é, 15 Ormond Quay Upper",
                    "lat": 53.345898, 
                    "lng": -6.269489
                },
                {
                    "id": "8-leeson-st-lower",
                    "name": "Sugar Club, 8 Leeson Street Lower",
                    "lat": 53.335571, 
                    "lng": -6.256543
                }
            ]
        }
  }
}

The following sections explain the content expected in each part of this request body.

Root:

{
    "data": CalculationRequest
}
  • data: CalculationRequestContains the definition of the calculation that is to be performed.

CalculationRequest:

{
    "ro_account_id": string,
    "callback_url": string?,
    "include_ro_result_in_callback": boolean,
    "task": CalculationTask
}
  • ro_account_id: string

This is the ID of the RO Account which you want to make this request with. You must have enough credits in this account in order for the task to be accepted.

  • callback_url: string?

The URL which you want to receive callback events on. OPTIONAL. If not provided, then one must poll the “GET Ro Task Status” endpoint in order to determine if the calculation has been completed. See the section “Ro Task Callback Events” for details about what data will be sent to this callback URL.

  • include_ro_result_in_callback: boolean

If TRUE, then the cost matrix result data will be included in the data body that is sent to the callback URL. If FALSE, then the cost matrix will be omitted from the callback event, and the user will have to explicitly request the data from the “GET Ro Task Result” endpoint.

  • task: CalculationTask

Contains the data for calculating the cost matrix. See below for description.


CalculationTask
{
    "calculation_type": string,
    "locations":  Array
}
  • calculation_type: string

This determines the type of calculation task that will be performed. Set this to “COST_MATRIX” in order to calculate a cost matrix for the given input locations.

  • locations: Location

An array of locations that the cost matrix will be calculated for. The Location JSON object is described below.


Location
{
    "id": string,
    "name": string,
    "lat": double,
    "lng":  double
}
  • id: string

Unique ID for this location. You can choose any name for this location, as long as it is unique among all locations in this request.

  • name: string?

The display name to use for this location. If not provided, then the id will be used as the display name.

  • lat: double

Latitude.

  • lng: double

Longitude.


Response

HTTP status: 200

A successful response code (i.e. 200) indicates that your task has been accepted and is currently being calculated.

Body:

{
    "data": {
        "task_id": "XyZ123",
        "credit_cost": 100
    }
}
  • task_id: string

This is the ID that has been assigned to your task. You must use this to request updates for your task using the GET Task Status or GET Task Result endpoints.

  • credit_cost: int

This is the number of credits that this task costs. Credits are subtracted from your account balance immediately.

The results will be executed asyncronously, and will be sent to the callback_url provided in the request body. The results can also be optained via the GET Task Result endpoint.


HTTP status: 400

If the calculation task is rejected, then a response with the following format will be returned.

{
    "error": {
        "status_code": int,
        "error_flag": string,
        "message": string?
    }
}
  • error: Error

Contains content describing the type of error that occurred.

  • status_code: int

The HTTP status code of the response.

  • error_flag: string

A specific flag that explains why the error occured. The meanings of flags are described below. Valid values: * “INSUFFICIENT_CREDITS” * “MAX_TASKS_PER_DAY_LIMIT” * “MAX_CREDITS_PER_TASK”

  • message: string

A message that provides extra details about the error. This is a human-readable explanation of the error, and one should not parse it in order to drive business logic, as the exact wording and format of any given message may be changed at any time without warning.

Error Flag: INSUFFICIENT_CREDITS

This indicates that the account does not have enough credits remaining to perform the requested calculation.

Example:

{
    "error": {
        "status_code": 400,
        "error_flag": "INSUFFICIENT_CREDITS",
        "message": "Insufficient Credits. The requested calculation requires X credits."
    }
}

Error Flag: MAX_TASKS_PER_DAY_LIMIT

Only applies to Demo accounts.

This indicates that the account has reached its maximum tasks per day limit. Demo accounts are restricted to performing a set limit of calculation tasks in any given 24 hours period. – This limit is not dependent on the size of the tasks being calculated. – This limit applies over a 24 hour period, not over a “calendar” day.

Pro accounts do not have this restriction.

Example:

{
    "error": {
        "status_code": 400,
        "error_flag": "MAX_TASKS_PER_DAY_LIMIT",
        "message": "Limit of max tasks per 24 hours has been reached."
    }
}

Error Flag: MAX_CREDITS_PER_TASK

Only applies to Demo accounts.

This indicates that the number of credits required for the requested calculation is greater than the maximum size allowed for any given task for this account.

Pro accounts can perform any size calculation, so long as their account has sufficient credits.

Example:

{
    "error": {
        "status_code": 400,
        "error_flag": "MAX_CREDITS_PER_TASK",
        "message":     "The requested calculation requires X credits, but this account's max allowed credits per task is Y."
    }
}

Ro Task Callback

If you provide a value for callback_url in the body of the POST Calculate Matrix endpoint, then the following data will be sent via a POST request to the provided URL.

Example Callback JSON:

{
    "data": {
        "client_secret": "adgasdiuyhsadhjasdjhasdkjh",
        "task_id": "xYz123",
        "status": "COMPLETE",
        "event_at": "2018-01-30 17:59:00",
        "ro_result": {
            "about": {
                "api_version_code": 1,
                "api_version_name": "v0.1.0",
                "matrix_engine": "graphite-v1",
                "attributions": [
                    "OpenStreetMap contributors"
                ]
            },
            "location_ids": [
                "73-dame-street",
                "24-wexford-street",
                "82-parnell-street"
            ],
            "cost_matrix": {
                "weights": [
                    [
                        0,
                        140843.84122226504,
                        180615.10019492012
                    ],
                    [
                        121707.41494237226,
                        0,
                        265604.4801106649
                    ],
                    [
                       139901.99881586424,
                       176652.3842115018,
                       0
                    ]
                ],
                "times": [
                 [
                     0,
                     93274,
                     119379
                 ],
                 [
                     80574,
                     0,
                     175579
                 ],
                 [
                     92453,
                     116706,
                     0
                 ]
             ],
                "distances": [
                    [
                        0,
                        777,
                        1289
                    ],
                    [
                        705,
                        0,
                        1863
                    ],
                    [
                        1019,
                        1328,
                        0
                    ]
                ]
            }
        }
    }
}

RoResult

The ro_result object will only be present in the callback if you set include_ro_result_in_callback to TRUE in your initial request when this task was created.

The size of the ro_result object scales very quickly, and if you are making requests with large numbers of input points (e.g. greater than 100 points), then the size of the data that will be posted to your callback may become larger than the limit that your server allows for incoming requests. We advise to err on the side of caution here: if you are not entirely sure that your server will allow a large amount of data to be POSTed to your callback endpoint, then you should set include_ro_result_in_callback to FALSE, since the entire callback will then fail and you will not be notified that your task has finished being calculated. You can download the ro_result data from the GET Ro Task Result endpoint, which is described later in this document.

{
    "about": {
        "api_version_code": int,
        "api_version_name": string,
        "matrix_engine": string,
        "attributions": Array
    },
    "location_ids": Array,
    "cost_matrix": {
        "weights": Array<Array>,
        "times": Array<Array>,
        "distances": Array<Array>
    }
}
  • about: About (object)

Gives information about the result.

  • location_ids: Array

The ids of the input request, in the order that they appear in the cost_matrix.

  • cost_matrix: CostMatrix (object)

CostMatrix

Contains 3 matrices that describe the costs of travelling between the given locations in terms of time, distance and overall cost (weights).

Each matrix is an array of arrays of numeric values. The outer array defines the “from” location, the inner array determines the “to” location.

Take the following simplified example (details have been removed from the JSON):

{
    "location_ids": [
        "A", "B", "C"
    ],
    "cost_matrix": {
        "distances": [
            [
                0,
                100,
                200
            ],
            [
                110,
                0,
                300
            ],
            [
                180,
                310,
                0
            ]
        ]
   }
}

There are 3 locations in the Task, which have LocationIds “A”, “B” and “C”.

The “locations” array tells us which order each location’s cost appears relative to each other in the each of the matrices in the “cost_matrix” object.

The first inner array (i.e. the first row) in the “distances” matrix gives the distance from “A” to each other element in the “location” array (including “A” itself) respective to the order in which they appear in the array. Therefore, the distance from A to B is 0; from A to B is 100; from A to C is 200.

The second array (i.e. the second row) in the “distances” matrix contains distances from B to the other elements. The cost are as follows: * B to A = 110 * B to B = 0 * B to C = 300

And likewise, for C we have: * C to A = 180 * C to B = 310 * C to C = 0

In the above example, we have omitted the “weights” and “times” matrices, but these would contain data for each location in the same order as they appear in the “distances” matrix.

  • weights: Array

Matrix, representing “total cost”, which is a combination of distance and time.

  • times: Array

Matrix: The time cost in seconds.

  • distances: Array

Matrix: The distance cost in meters.


GET RoTask Status

Endpoint: GET https://api.squareroute.io/api/v1/ro/task/{task_id}/status

Gets the current status of the RoTask.

Note: You must replace “{task_id}” in the URL with the ID of your calculation task.

For example, if you post a request to the calculate endpoint and it returns the following:

{
    "data": {
        "task_id": "xYz123",
        "credit_cost": 100
    }
}

Then to poll for updates about the status of this task, you would send a GET request to:

https://api.squareroute.io/api/v1/ro/task/xYz123/status

Response:

{
  "data": {
    "task_id": string,
    "status": string,
    "updated_at": string
  }
}

task_id: string

The ID of the task.

status: string

Can be one of the following values:

  • QUEUED
  • STARTED
  • FINISHED
  • ERROR

updated_at: string

A timestamp string that provides information about the last time the status of the task changed.


GET Ro Task Result

Endpoint: GET https://api.squareroute.io/api/v1/ro/task/{task_id}/result

Gets the RoResult data, which contains the calculated Matrix for your requested task.

Example URL for task_id=”xYz123″: https://api.squareroute.io/api/v1/ro/task/xYz123/status

{
  "data": {
     "task_id": string,
     "ro_result": RoResult
  }
}

RoResult is as described above.

If you set include_ro_data_in_callback to FALSE in your initial request, then you will need to call this endpoint in order to retrieve the result of your task once it is ready.

If you set include_ro_data_in_callback to TRUE, then you will only need to make requests to this endpoint if the callback request that we make to your provided callback_url fails.