Code Examples

Sample clients and payloads for posting sensor data to Agrogat ingest.

These examples apply to POST /ingest.php only (API key required). Gateway identity is set server-side via GATEWAY_CODE in .env, not in the JSON body.

Replace the placeholders below with your own values:

Variable Example value
GATEWAY_URL https://your-gateway.example.com
API_KEY Value from your server .envINGEST_API_KEY

cURL (terminal)

BASH
curl -X POST https://your-gateway.example.com/ingest.php \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_INGEST_API_KEY" \
  -d '{
    "sensor_id": "sensor-001",
    "payload": {
      "temperature": 22.5,
      "humidity": 61
    }
  }'

Python

PYTHON
import requests

GATEWAY_URL = "https://your-gateway.example.com"
API_KEY     = "YOUR_INGEST_API_KEY"

def send_sensor_data(sensor_id: str, payload: dict) -> dict:
    response = requests.post(
        f"{GATEWAY_URL}/ingest.php",
        json={"sensor_id": sensor_id, "payload": payload},
        headers={"X-API-Key": API_KEY},
        timeout=10,
    )
    response.raise_for_status()
    return response.json()

# Example
result = send_sensor_data("sensor-001", {"temperature": 22.5, "humidity": 61})
print(result)  # {'status': 'success', 'id': '42'}

MicroPython (Raspberry Pi Pico W / ESP32)

PYTHON
import urequests
import ujson

GATEWAY_URL = "https://your-gateway.example.com"
API_KEY     = "YOUR_INGEST_API_KEY"

def send_sensor_data(sensor_id, payload):
    headers = {
        "Content-Type": "application/json",
        "X-API-Key": API_KEY,
    }
    body = ujson.dumps({"sensor_id": sensor_id, "payload": payload})
    response = urequests.post(GATEWAY_URL + "/ingest.php", data=body, headers=headers)
    result = response.json()
    response.close()
    return result

# Example
result = send_sensor_data("pico-001", {"temperature": 23.1})
print(result)

Arduino (ESP8266 / ESP32 with WiFiClient)

CPP
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

const char* GATEWAY_URL = "https://your-gateway.example.com/ingest.php";
const char* API_KEY     = "YOUR_INGEST_API_KEY";

void sendSensorData(const char* sensorId, float temperature) {
    WiFiClient client;
    HTTPClient http;

    http.begin(client, GATEWAY_URL);
    http.addHeader("Content-Type", "application/json");
    http.addHeader("X-API-Key", API_KEY);

    StaticJsonDocument<256> doc;
    doc["sensor_id"] = sensorId;
    doc["payload"]["temperature"] = temperature;

    String body;
    serializeJson(doc, body);

    int httpCode = http.POST(body);

    if (httpCode == 200) {
        Serial.println("Data sent OK: " + http.getString());
    } else {
        Serial.printf("Error: HTTP %d\n", httpCode);
    }

    http.end();
}

JavaScript / Node.js

JAVASCRIPT
const GATEWAY_URL = 'https://your-gateway.example.com';
const API_KEY     = 'YOUR_INGEST_API_KEY';

async function sendSensorData(sensorId, payload) {
    const response = await fetch(`${GATEWAY_URL}/ingest.php`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-API-Key': API_KEY,
        },
        body: JSON.stringify({ sensor_id: sensorId, payload }),
    });

    if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
    }

    return response.json();
}

// Example
sendSensorData('node-001', { temperature: 21.0, pressure: 1013 })
    .then(console.log)
    .catch(console.error);

PHP

PHP
<?php

$gatewayUrl = 'https://your-gateway.example.com/ingest.php';
$apiKey     = 'YOUR_INGEST_API_KEY';

function sendSensorData(string $url, string $apiKey, string $sensorId, array $payload): array
{
    $body = json_encode(['sensor_id' => $sensorId, 'payload' => $payload]);

    $context = stream_context_create([
        'http' => [
            'method'  => 'POST',
            'header'  => implode("\r\n", [
                'Content-Type: application/json',
                'X-API-Key: ' . $apiKey,
            ]),
            'content' => $body,
            'timeout' => 10,
        ],
    ]);

    $response = file_get_contents($url, false, $context);

    if ($response === false) {
        throw new RuntimeException('Request failed');
    }

    return json_decode($response, true);
}

// Example
$result = sendSensorData($gatewayUrl, $apiKey, 'php-001', ['temperature' => 19.5]);
print_r($result);

Troubleshooting

Problem Possible cause
401 Unauthorized Wrong or missing X-API-Key header
400 Bad Request Missing sensor_id in JSON body
415 Unsupported Media Type Content-Type is not application/json
500 Internal Server Error Database error — check server log
No response / timeout Firewall blocking port 443/80, or gateway is down