Fetching JSON data from API

Some devices, such as the such as the BodyTrace scale, can send data from the API to a server based on any number of triggers. However occasionally there are times when we need to go to the API and pull the data from the API. In order to do this on the BodyTrace server you need to use the GET method, however others may require the POST method. Here’s how to do it using the GET method.

Start with the basics, URL, username, password. The API manager will need to supply you with these.

<?php

$url = "https://exampleUrl.com/1/device/deviceEMEInumber/datamessages";  // Example URL. Replace with your's

$username = "yourUsername"; 
$password = "password";

Next connect with API and get the data (JSON payload).

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

$scaleData = curl_exec($ch);

if ($scaleData === false) {
    echo "cURL Error: " . curl_error($ch);
} else {
    echo "Response:\n" . $scaleData;
}

curl_close($ch);

?>

$scaleData is your data. In our case the data is a JSON payload and it looks like this:

[{"imei":"868998031204304","ts":1718539325074,"batteryVoltage":4941,"signalStrength":31,"values":{"unit":1,"tare":0,"weight":70800},"rssi":99,"deviceId":86899803120430},{"imei":"868998031204304","ts":1718462982371,"batteryVoltage":4897,"signalStrength":27,"values":{"unit":1,"tare":0,"weight":69600},"rssi":101,"deviceId":86899803120430},{"imei":"868998031204304","ts":1718162982371,"batteryVoltage":4897,"signalStrength":27,"values":{"unit":1,"tare":0,"weight":69600},"rssi":101,"deviceId":86899803120430}]

So we have the data! Now what? Next: How to process a JSON file to get the data you want.