Simple PHP Example to Read from Datablaze

Was having a quick play with the Datablaze API Today.

I thought I'd share this little snippet that may help others get started with accessing Data Blaze with PHP.

You will need to get you API Key and the ID of the Table you want to work with.

This simple example simply reads the values from your table and outputs X number of rows from that table.

Notes
API Documentation - Text Blaze | Getting Started with Data Blaze

<?php
// Set the API token for authorization
$token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

// Set the table ID
$tableId = "xxxxxxxxxxxxxxxxxxxxxxx";

// Set the number of rows to be returned
$row_limit = 5;

// Define the API endpoints for fetching table fields and rows using the table ID
$url = "https://data-api.blaze.today/api/database/fields/table/{$tableId}/";
$rows_url = "https://data-api.blaze.today/api/database/rows/table/{$tableId}/?user_field_names=true";

// Set the headers for API request authorization
$headers = [
    "Authorization: Token " . $token
];

// Initialize cURL to fetch table fields
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the cURL request and decode the JSON response
$response = curl_exec($ch);
$fields = json_decode($response, true);

// Set the cURL request URL to fetch table rows
curl_setopt($ch, CURLOPT_URL, $rows_url);

// Execute the cURL request and decode the JSON response
$response = curl_exec($ch);
curl_close($ch);
$rows = json_decode($response, true);

// Display the first x number of rows of the table
echo "First {$row_limit} rows:<br>";

// Initialize a counter to keep track of displayed rows
$counter = 0;

// Iterate through each row in the response
foreach ($rows['results'] as $row) {
    // Break the loop if the row limit have been reached
    if ($counter >= $row_limit) {
        break;
    }

    // Display the row ID and order
    echo "Row ID: " . $row['id'] . "<br>";
    echo "Order: " . $row['order'] . "<br>";

    // Iterate through each field in the row and display its value
    foreach ($fields as $field) {
        $field_name = $field['name'];
        echo "$field_name: " . $row[$field_name] . "<br>";
    }

    // Add a line break for readability and increment the counter
    echo "<br>";
    $counter++;
}

?>
4 Likes