openblocks-dev / openblocks

🔥 🔥 🔥 The Open Source Retool Alternative
https://cloud.openblocks.dev
GNU Affero General Public License v3.0
5.83k stars 351 forks source link

Question: How to extract data from REST API response #98

Closed swright-eti closed 1 year ago

swright-eti commented 1 year ago

I am trying to create a module that contains a table that shows the result of a call to a REST API. The API returns data in the structure shown below. From the query I only want to return the _embedded.devices list. When I try to access it in a Javascript handler like this console.log(get_device_list.data.embedded); it shows as undefined.

{
    "_embedded": {
        "devices": [{
            "deviceId": "4857544311CFD669D01",
            "deviceType": "Huawei ONT",
            "deviceModel": "HG8240U Data Port",
            "deviceStatus": "In Service",
            "unitAddress": "X7-PTV1-10:1-0-1-1-1",
            "locationId": "0000006",
            "_links": {
                "self": {
                    "href": "https://beta1.dev.eti.software/device-api/v1/devices/4857544311CFD669D01"
                }
            }
        }, {
            "deviceId": "MA1034FAL654",
            "deviceType": "ROSIROSE",
            "deviceModel": "custmodel",
            "deviceStatus": "Out of Service",
            "unitAddress": null,
            "locationId": "HEADEND 01 INVENTORY",
            "_links": {
                "self": {
                    "href": "https://beta1.dev.eti.software/device-api/v1/devices/MA1034FAL654"
                }
            }
        }]
    },
    "_links": {
        "self": {
            "href": "https://beta1.dev.eti.software/device-api/v1/devices?page=0&size=20&sort=deviceId,asc"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 7,
        "totalPages": 1,
        "number": 0
    }
}

image

swright-eti commented 1 year ago

I have figured out how to get around this, and I figured out why its happening. The reason it's happening is that our APIs returns either application/hal+json or application/problem+json. OpenBlocks doesn't know about those types.

The way to get around it is to use a transformer that does this:

return JSON.parse(get_device_list.data)._embedded.devices;
neon-balcony commented 1 year ago

Hi @swright-eti ,

Bravo, looks like you're on the right track to write code and debug 😄 .

One more thing to notice, always remember to use the data browser on the left pane to check the types of your data:

image

Data shown in the result dialogue can be hard to tell whether it's a literal string or a JSON array/map.

swright-eti commented 1 year ago

"Data shown in the result dialogue can be hard to tell whether it's a literal string or a JSON array/map."

Good to know, thank you.