Public API Documentation

Welcome to the AmbientHub Public API. This API provides a simple, read-only interface to fetch the latest weather observation data from a user's device.


1. Getting Your API Token

To use the API, you first need to generate a personal Public API Token.

  1. Log in to your AmbientHub account and navigate to the Settings page.
  2. Find the "Public API" section.
  3. Click the "Generate New Token" button. Your unique token will appear in the text field.
  4. Copy this token. Keep it secure, as it provides public access to your weather data.

2. The API Endpoint

The API has a single endpoint that accepts a `GET` request:

https://www.ambienthub.online/api/public_data.json?token=YOUR_TOKEN_HERE

You must replace `YOUR_TOKEN_HERE` with the token you generated in the previous step.


3. The Response Object

A successful request will return a JSON object containing the latest observation data from any of your registered devices.

Example Success Response:

{
    "dateutc": 1759376700000,
    "tempf": 66.4,
    "humidity": 64,
    "winddir": 292,
    "windspeedmph": 0.9,
    /* ... and other data points ... */
    "macAddress": "EC:FA:BC:4D:52:AF",
    "observedAtUTC": "2025-10-03 11:00:00"
}

Example Error Response:

{
    "error": "Invalid API token."
}

4. Code Examples

JavaScript (Browser Fetch)

const token = 'YOUR_TOKEN_HERE';
const apiUrl = `https://www.ambienthub.online/api/public_data.json?token=${token}`;

fetch(apiUrl)
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.error) {
            console.error('API Error:', data.error);
        } else {
            console.log('Current Temperature:', data.tempf);
        }
    })
    .catch(error => {
        console.error('Fetch Error:', error);
    });

Python

import requests

token = 'YOUR_TOKEN_HERE'
api_url = f'https://www.ambienthub.online/api/public_data.json?token={token}'

try:
    response = requests.get(api_url)
    response.raise_for_status()  # Raises an HTTPError for bad responses
    
    data = response.json()
    
    if data.get('error'):
        print(f"API Error: {data['error']}")
    else:
        print(f"Current Temperature: {data.get('tempf')}°F")
        print(f"Humidity: {data.get('humidity')}%")

except requests.exceptions.RequestException as e:
    print(f"Request Error: {e}")

PHP (cURL)

<?php
$token = 'YOUR_TOKEN_HERE';
$apiUrl = "https://www.ambienthub.online/api/public_data.json?token=" . urlencode($token);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

if (isset($data['error'])) {
    echo "API Error: " . htmlspecialchars($data['error']);
} elseif ($data) {
    echo "Current Temperature: " . htmlspecialchars($data['tempf']) . "°F\n";
    echo "Humidity: " . htmlspecialchars($data['humidity']) . "%\n";
} else {
    echo "Failed to fetch or decode data.";
}
?>

5. Integration Guides

WordPress Weather Widget

The easiest way to display your weather data on a WordPress site is by creating a simple shortcode. This allows you to place `[ambient_weather]` in any post or page.

Step 1: Add PHP to your theme's `functions.php`

In your WordPress dashboard, go to Appearance > Theme File Editor and add the following code to the bottom of your `functions.php` file. Remember to paste your API token where indicated.


function ambienthub_weather_shortcode() {
    // --- PASTE YOUR AMBIENTHUB PUBLIC API TOKEN HERE ---
    $api_token = 'YOUR_TOKEN_HERE';
    // ----------------------------------------------------

    $api_url = 'https://www.ambienthub.online/api/public_data.json?token=' . urlencode($api_token);
    $response = wp_remote_get($api_url);

    if (is_wp_error($response) || wp_remote_retrieve_response_code($response) != 200) {
        return '<p style="color: red;">Error: Could not retrieve weather data.</p>';
    }

    $data = json_decode(wp_remote_retrieve_body($response), true);

    if (isset($data['error']) || empty($data) || !isset($data['tempf'])) {
        return '<p>Weather data is currently unavailable.</p>';
    }

    ob_start();
    ?>
    <div class="ambient-weather-widget">
        <h3 class="widget-title">Current Conditions</h3>
        <div class="weather-grid">
            <div class="weather-item">
                <span class="label">Temperature</span>
                <span class="value"><?php echo round($data['tempf']); ?>°F</span>
            </div>
            <div class="weather-item">
                <span class="label">Humidity</span>
                <span class="value"><?php echo round($data['humidity']); ?>%</span>
            </div>
            <div class="weather-item">
                <span class="label">Wind</span>
                <span class="value"><?php echo $data['windspeedmph']; ?> mph</span>
            </div>
        </div>
        <div class="last-updated">
            Last Updated: <?php echo date("g:i A T", strtotime($data['observedAtUTC'])); ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('ambient_weather', 'ambienthub_weather_shortcode');
        

Step 2: Add CSS to your site

In your WordPress dashboard, go to Appearance > Customize > Additional CSS and paste this code.


.ambient-weather-widget { /* ... CSS from previous response ... */ }
        

Simple HTML & JavaScript Widget

You can use this code on any website that allows you to embed HTML and JavaScript (like Squarespace, Wix, or a static site).


<!-- 1. Add this HTML where you want the weather to appear -->
<div id="my-weather-widget">Loading weather...</div>

<!-- 2. Add this JavaScript to your page -->
<script>
    const myToken = 'YOUR_TOKEN_HERE';
    const widgetContainer = document.getElementById('my-weather-widget');

    async function getMyWeather() { /* ... JS from previous response ... */ }

    getMyWeather();
</script>
        

6. Advanced Usage & Ideas

Auto-Refreshing Widget

To make your JavaScript widget update automatically, you can wrap the fetch call in a `setInterval` function. This example refreshes the data every 5 minutes (300,000 milliseconds).


<script>
    const myToken = 'YOUR_TOKEN_HERE';
    const widgetContainer = document.getElementById('my-weather-widget');

    async function getMyWeather() { /* ... same as above ... */ }

    // Fetch data immediately on page load
    getMyWeather();

    // Then, fetch data again every 5 minutes
    setInterval(getMyWeather, 300000); 
</script>
        

Expanding the WordPress Widget

You can easily add more data points to the WordPress shortcode. For example, to add Pressure and Daily Rain, you would modify the `ob_start()` section of the PHP function:


    // ... inside the ambienthub_weather_shortcode() function
    ?>
    <div class="ambient-weather-widget">
        <!-- ... title ... -->
        <div class="weather-grid" style="grid-template-columns: repeat(5, 1fr);">
            <!-- ... temp, humidity, wind ... -->
            <div class="weather-item">
                <span class="label">Pressure</span>
                <span class="value"><?php echo round($data['baromrelin'], 2); ?> inHg</span>
            </div>
            <div class="weather-item">
                <span class="label">Daily Rain</span>
                <span class="value"><?php echo $data['dailyrainin']; ?> in</span>
            </div>
        </div>
        <!-- ... last updated ... -->
    </div>
    <?php
    // ...
        

Note that you may need to adjust the CSS (`grid-template-columns`) to accommodate the extra items.

A Note on Caching

If you are displaying weather data on a high-traffic website, it's a very good practice to cache the API response on your server instead of calling the AmbientHub API on every single page load. In WordPress, you can use the Transients API to easily cache the results for 5-10 minutes.