Developer Docs Integration Guide

API Code Examples & Tutorials

Copy-paste production-ready code samples in Python, JavaScript/TypeScript, cURL/Bash, R, PowerShell, and C. Query live weather observations, automate CSV backups, and integrate data into your applications.

Py

Python Code Examples

Data science integration with Pandas, Requests, and Matplotlib

Example 1: Fetching Weather Data directly into a Pandas DataFrame

Request CSV data from the API endpoint and parse it directly into Pandas for immediate processing and statistical analysis.

import io
import pandas as pd
import requests

# Set endpoint URL
url = "http://weathertower.physics.carleton.edu/api/weather/"

# Define query parameters
params = {
    "fields": [
        "ambient_temp_LM335",
        "RH_Precon",
        "MetOne_wind_speed_average",
        "ten_Peet_WindLHX"
    ],
    "datetimes": "06/26/2026 10:00 AM - 06/26/2026 11:59 AM",
    "interval": 5,      # 5-minute sampling interval
    "format": "csv"     # Direct CSV response
}

response = requests.get(url, params=params)

if response.status_code == 200:
    # Read CSV response into Pandas DataFrame
    df = pd.read_csv(io.StringIO(response.text))
    print(f"Successfully loaded {len(df)} rows:")
    print(df.describe())
else:
    print(f"API Error {response.status_code}: {response.text}")

Example 2: Plotting Temperature & Humidity with Matplotlib

Fetch time-series observations and render a dual-axis line chart.

import requests
import pandas as pd
import matplotlib.pyplot as plt
import io

url = "http://weathertower.physics.carleton.edu/api/weather/"
params = {
    "fields": ["ambient_temp_LM335", "RH_Precon"],
    "datetimes": "06/26/2026 12:00 AM - 06/26/2026 11:59 PM",
    "interval": 10,
    "format": "csv"
}

resp = requests.get(url, params=params)
df = pd.read_csv(io.StringIO(resp.text))

# Plot temperature and humidity
fig, ax1 = plt.subplots(figsize=(10, 5))

color = 'tab:red'
ax1.set_xlabel('Timestamp')
ax1.set_ylabel('Temperature (°F)', color=color)
ax1.plot(df.index, df['ambient_temp_LM335'], color=color, label='Temp (°F)')
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Relative Humidity (%)', color=color)
ax2.plot(df.index, df['RH_Precon'], color=color, linestyle='--', label='Humidity (%)')
ax2.tick_params(axis='y', labelcolor=color)

plt.title('Carleton Weather Tower 24-Hour Observation')
plt.grid(True, alpha=0.3)
plt.savefig('weather_plot.png', dpi=300)
print("Plot saved to weather_plot.png")
JS

JavaScript & TypeScript Examples

Web applications, Node.js scripts, and React hooks

Example 1: Fetching Live Current Observations in Modern JS

Using standard web browser `fetch` with `async/await` to consume JSON endpoints.

async function getLatestWeather() {
    const url = 'http://weathertower.physics.carleton.edu/api/all_current/?format=json';
    
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        
        const result = await response.json();
        console.log('Observation Time (Central):', result.actual_time);
        
        // Loop over the first 5 current sensor fields
        result.data.slice(0, 5).forEach(item => {
            console.log(`${item.field}: ${item.value} (${item.range_status})`);
        });
    } catch (err) {
        console.error('Failed to fetch weather data:', err);
    }
}

getLatestWeather();

Example 2: React Custom Hook (useWeatherData)

Custom React hook with automatic polling for real-time dashboard components.

import { useState, useEffect } from 'react';

export function useWeatherData(pollIntervalMs = 60000) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        let isMounted = true;

        async function fetchWeather() {
            try {
                const res = await fetch('http://weathertower.physics.carleton.edu/api/all_current/?format=json');
                if (!res.ok) throw new Error(`HTTP error ${res.status}`);
                const json = await res.json();
                if (isMounted) {
                    setData(json);
                    setLoading(false);
                }
            } catch (err) {
                if (isMounted) {
                    setError(err.message);
                    setLoading(false);
                }
            }
        }

        fetchWeather();
        const timer = setInterval(fetchWeather, pollIntervalMs);

        return () => {
            isMounted = false;
            clearInterval(timer);
        };
    }, [pollIntervalMs]);

    return { data, loading, error };
}
>_

cURL & Shell Automation

Terminal commands, file downloads, and automated cron backup scripts

Example 1: Fetching JSON & Pretty-Printing with `jq`

# Query API and format output with jq
curl -s -G "http://weathertower.physics.carleton.edu/api/weather/" \
  --data-urlencode "fields=ambient_temp_LM335" \
  --data-urlencode "fields=RH_Precon" \
  --data-urlencode "format=json" | jq '.'

Example 2: Automated Hourly Backup Shell Script (backup_weather.sh)

A bash script designed for cron jobs to archive daily weather data locally.

#!/bin/bash
# Backup Weather Tower Data into CSV files by date

BACKUP_DIR="./weather_backups"
mkdir -p "$BACKUP_DIR"

DATE_STR=$(date +"%Y-%m-%d")
FILE_PATH="${BACKUP_DIR}/weather_${DATE_STR}.csv"

echo "Downloading daily weather summary for ${DATE_STR}..."

curl -s -G "http://weathertower.physics.carleton.edu/api/weather/" \
  --data-urlencode "format=csv" \
  -o "$FILE_PATH"

if [ -s "$FILE_PATH" ]; then
    echo "Backup completed: ${FILE_PATH} ($(du -h "$FILE_PATH" | cut -f1))"
else
    echo "Backup failed: Empty response received."
fi
R

R Statistical Environment

Import weather data into R dataframes using `httr` and `jsonlite`

library(httr)
library(jsonlite)

# Query Weather API for temperature and wind metrics
api_url <- "http://weathertower.physics.carleton.edu/api/weather/"

res <- GET(
  api_url,
  query = list(
    fields = c("ambient_temp_LM335", "MetOne_wind_speed_average"),
    datetimes = "06/26/2026 10:00 AM - 06/26/2026 11:59 AM",
    interval = 10,
    format = "json"
  )
)

if (status_code(res) == 200) {
  json_text <- content(res, "text", encoding = "UTF-8")
  weather_df <- fromJSON(json_text)
  
  # Output summary statistics
  print(summary(weather_df))
} else {
  cat("Error status code:", status_code(res))
}
</>

PowerShell & C

Windows scripting and scientific computing

Windows PowerShell

# Download weather data using PowerShell
$url = "http://weathertower.physics.carleton.edu/api/all_current/?format=json"
$response = Invoke-RestMethod -Uri $url -Method Get

Write-Host "Observation Time: " $response.actual_time
$response.data | Select-Object -First 10 | Format-Table -AutoSize

C (libcurl)

Fetch the latest weather data from the API using libcurl. Compile with gcc weather.c -lcurl.

#include <stdio.h>
#include <curl/curl.h>

static size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) {
    return fwrite(contents, size, nmemb, stdout);
}

int main(void) {
    CURL *curl = curl_easy_init();

    if (curl) {
        curl_easy_setopt(
            curl,
            CURLOPT_URL,
            "http://weathertower.physics.carleton.edu/api/all_current/?format=json"
        );
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

        CURLcode res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "Request failed: %s\n", curl_easy_strerror(res));
        }

        curl_easy_cleanup(curl);
    }

    return 0;
}

verified API Guidelines & Best Practices

  • No API Key Required: The Carleton Weather Tower API is public and free to access for research, education, and campus projects.
  • Caching & Polling Rate: The weather station updates data every 1 minute. Polling faster than 60-second intervals is unnecessary and creates redundant server load.
  • Timezone Conventions: Raw timestamps in database records are stored in UTC. Display timestamps and Texas/Chicago local fields are formatted in America/Chicago (CT).
  • Large Range Queries: For multi-month or multi-year historical data queries, use the interval parameter (e.g. interval=60 for 1-hour resolution) to keep response payloads lightweight.