Query an endpoint

Overview

Previously we have been able to use curl commands and swagger docs to connect and query the TilliT API. Now we will explore some examples of querying the TilliT API in high level programming languages and change the number of results we recieve.

Get an Asset

In Javascript, it is best to use the node-fetch package to simplify the http requests we make. The following code snippet will retrieve the assets in your account and print them out.

import fetch, {Headers} from "node-fetch";
async function request(url, method, body){
    const tenant = ''
    const username = ''
    const password = ''

    const auth = 'Basic ' + Buffer.from(username + '@' + tenant +'.tillit.cloud:' + password).toString('base64')
    const head = new Headers()
    head.append('Authorization', auth)
    head.append('Content-Type', 'application/json')
    const baseUrl = 'https://tillit.cloud/api'

    return await fetch(`${baseUrl}${url}`, {
        method: method,
        headers: head,
        body: JSON.stringify(body)
    })
}
request('/core/assets', 'GET').then(async (response) => {
    console.log(await response.json())
})

An example in Python can be found below

import requests
import base64
import json

def request(path, method, body = ''):
    tenant = ''
    username = ''
    password = ''

    auth_bytes = (username + '@' + tenant +'.tillit.cloud:' + password).encode('ascii')
    base64_bytes = base64.b64encode(auth_bytes)
    base64_auth = 'Basic ' + base64_bytes.decode('ascii')
    headers = {'Authorization': base64_auth, 'Content-Type': 'application/json'}
    url = 'https://stage.tillit-stage.cloud/api' + path

    if method == 'GET':
        return requests.get(url, data=json.dumps(body), headers=headers)
    elif method == 'POST':
        return requests.post(url, data=json.dumps(body), headers=headers)
    elif method == 'PUT':
        return requests.put(url, data=json.dumps(body), headers=headers)
    elif method == 'DELETE':
        return requests.delete(url, data=json.dumps(body), headers=headers)
    else:
        return 'Bad Request: not valid method'

response = request('/core/assets', 'GET')
print(response.json())

Query Pagination with Page and Size

Depending on how many assets you have previously created, you may notice that not ALL assets have been returned. By default every GET request will only retrieve the first 20 entries. We can change this by instead changing the request to include the size param, see the following example

request('/core/assets?size=2', 'GET')

We can then combine this with page to get the next two results after the initial 'page'. The prior query is equivalent to page=0

request('/core/assets?size=2&page=1', 'GET')

Create an Asset

We can create an asset using the POST method, for this we will need a payload body. We can find out the shape of the payload required by searching the swagger docs for the /core/assets POST request. See the below image.

Now we can form the request. You will need to find the correct assetClass and site id for your database.

request('/core/assets', 'POST', {
    name: 'MyNewAsset',
    allowMultipleOrder: false,
    active: true,
    assetClass: 1,
    site: 1
})

We can confirm the above has worked by observing three things. 1. The status code returned is 200 2.We receive the entity with id in the response and 3. we can see the new Asset inside of TilliT.

Handling Errors

But what if something goes wrong? See the below request for what is a bad example.

request('/core/assets', 'POST', {
     name: 52,
     allowMultipleOrder: false,
     active: true,
     assetClass: {name: 'AREA'},
     site: 1
})

This will cause a 500 status code. The response object will detail exactly why the error occured, see below.

Asset name with value `52` has failed the following constraint(s):
 - name must be longer than or equal to 1 and shorter than or equal to 256 characters

This message is telling us that the entity Asset was supplied an invalid name, it must be a non null string. If we fix this, we get the following error.

null value in column "asset_class_id" violates not-null constraint

This message shows that asset class we supplied is invalid, it must be an id reference to. Note that assetClass: {id: 1} will work. Now we we have fixed all the errors

Last updated