Datacake Docs
  • Welcome
  • Get Started
  • Changelog
  • Best practices
    • Best practices: Getting started
    • Best practices: Resolution (Timeframe)
    • Best practices: Dashboards
    • Best practices: Reports
    • Best practices: Grouping Devices
  • Datacake LNS
    • Getting Started
    • Gateways
      • Milesight LoRaWAN Gateway - UG6x
      • RAKwireless WisGate Edge Light 2
    • Devices
    • Add Devices without Gateway
  • Device
    • Product
    • Configuration
    • Claiming
    • Historical Data
    • Database
      • Configuration Fields
      • Fields
        • Manual input
        • Field Roles
        • Formulas
        • Mapping Fields
      • Data retention & Datapoints
      • Examples
        • Mapping 4-20mA Signals
        • Converting Units
  • Dashboards
    • Global Dashboards
      • Setting Homepage
    • Device Dashboards
    • Multi-Device Dashboards
    • Widgets
      • Value Widget
      • Chart Widget
      • Image Map
      • Map Widget
      • Text Widget
      • SOS Widget
      • Boolean Widget
      • iFrame Widget
      • Downlink Widget
      • Set Value Widget
      • Measurement List Widget
      • Heatmap Widget
      • Table Widget
      • Image Widget
  • Portal
    • Multi-Tenancy (Workspaces)
    • Reports
      • Energy Report
    • Administrators
    • Members
      • API Users
    • Security & Privacy
    • Billing
      • Support Packages
      • VAT Exemption / Tax ID
      • SMS Credits
      • Access Invoices
      • Unused time and Remaining time in Invoices (Prorations)
      • Codes
    • White Label
    • Rules
      • Legacy Rule Engine
        • Sending notifications via Telegram
      • New Rule Engine
        • Rule Engine Table Overview
        • Copy/Paste and Template Functionality
        • Advanced Rule Engine E-Mail and Webhook Templates
        • Time Restrictions
    • Zones
  • Cake Red
    • Get Started
    • Overview
  • LoRaWAN
    • Get Started
      • CSV Import
      • Custom LoRaWAN Device
    • Configuring LNS
      • The Things Stack (TTN / TTI) Automated Setup
      • The Things Stack (TTN / TTI) Manual Setup
      • Loriot
      • Kerlink Wanesy
      • Helium
      • ChirpStack
      • Tektelic
      • Actility ThingPark
      • Senet
      • Milesight Gateway
      • KPN
    • Downlinks (LoRaWAN)
      • Set Time Frame
    • Securing Webhooks
    • Payload Decoders
      • Location and GPS
      • Access Gateway Metadata
      • Access Measurements
      • Global Variables
    • Using Cayenne LPP
    • Converting Payload
  • Generic API Devices
    • HTTP Downlinks
  • Integrations
    • MQTT
    • Particle
      • Get Started
      • Adding Integrations
      • Decoding Payloads
      • Calling Functions
      • Templates
        • Particle Tracker One
    • Incoming Webhooks
    • Outgoing Webhooks
      • Securing Outgoing Webhooks in Datacake
    • Golioth
    • Blues Wireless Notecard
    • Sigfox
    • Swarm Asset Tracker
    • Grandcentrix Modbus Cloud Connect
    • YuDash LYNX IoT Gateway
    • Dragino NB-IoT
      • Changing NB-IoT Bands
    • Hardwario CHESTER
    • 1NCE OS
  • API
    • Exporting Data
    • Record Measurements via API
    • Node RED to Datacake
    • Generate Access Token
    • Internal MQTT
      • Get Started
      • MQTT Documentation
      • MQTT over WebSocket
      • Example Code
    • GraphQL API
      • Using GraphQL
      • Device Creation
      • Tutorials
        • Read Group via Tags
  • Guides
    • Python
    • Send Slack Notifications
    • Forward Data to Cake Red
    • Multiple Data Feeds
    • Automated Dynamic Downlinks
    • Ingesting JSON Data into Datacake API Devices
    • Working with Default HTTP Decoder on API Devices and Code Examples
    • Accessing Measurements in Decoders
    • Connecting Datacake to Notion Using Zapier
    • How to set up and use location on non-GPS devices
    • How to integrate with AWS IoT Core
    • How to Schedule Mass-Downlinks (Multicast) using Datacake Rule Engine
    • How to Map Sensor Values to Ranges or Booleans, Strings using Mapping Fields
    • Understanding Internal vs. External MQTT Brokers on Datacake
    • Sending UDP Messages between 1NCE OS and Datacake
    • Concepts of LoRaWAN Payload Decoders on Datacake
    • How to check if a value stays above or below limits for given time
Powered by GitBook
On this page
  • Datacake API Device Setup Guide
  • Table of Contents
  • Introduction
  • Video
  • Getting Started
  • Creating a New API Device
  • Understanding the Default Decoder
  • Sending JSON Data
  • Configuring and Viewing Device Data
  • Adding and Using New Fields
  • Creating Dashboards
  • Conclusion
  • Code Examples
  • Python Example
  • JavaScript Example (using Node.js)
  • C# Example
  • Arduino Example

Was this helpful?

  1. Guides

Working with Default HTTP Decoder on API Devices and Code Examples

How to use default API device decoder and custom JSON. Includes code examples.

Last updated 11 months ago

Was this helpful?

Datacake API Device Setup Guide

This documentation provides a step-by-step guide on how to set up a Datacake API device, explaining the default decoder functionality and how to send JSON data to Datacake.

Table of Contents

  1. Introduction

  2. Creating a New API Device

  3. Understanding the Default Decoder

  4. Sending JSON Data

  5. Configuring and Viewing Device Data

  6. Adding and Using New Fields

  7. Creating Dashboards

Introduction

Welcome to the Datacake API Device setup guide. This guide will help you quickly and easily ingest your JSON style data into Datacake using the API integration. The default API device on Datacake contains a decoder that allows sending a generic JSON structure.

Video

Getting Started

Creating a New API Device

  1. Log in to Datacake:

    • Access your Datacake account. If you are new, sign up for an account.

  2. Add a New Device:

    • Click on Add Device.

  3. Select Device Type:

    • Choose API from the device type options. This device supports both MQTT and HTTP. For this guide, we will use HTTP.

  4. Create a New Product:

    • If you don't have any existing products, select New Product.

    • Name your product (e.g., "Simon's API Demo Product").

    • Click Next.

  5. Add a Device:

    • Add one device (e.g., "Simon's API Demo Device 01").

    • Click Next.

  6. Select Plan:

    • Choose the Free Plan (supports up to 5 devices).

    • Click Add One Device to finalize.

Understanding the Default Decoder

The default API device in Datacake contains a default decoder, which allows you to send JSON data in the following structure:

{
   "device": "REPLACE WITH SERIAL NUMBER",
   "temperature": 23.34,
   "battery": 3.02,
   "humidity": 56,
   "co2": 506,
   "location": "(53.4562, 6.99349)",
   "power": true,
   "energy": 39495,
   "solar": true,
   "state": "System OK",
   "counter": 9349
}

The default decoder recognizes this structure and populates the Suggested Fields section where users can click to create the devices. This functionality is dynamic, meaning new keys added to the JSON will show up in the Suggested Fields.

Sending JSON Data

  1. Retrieve the API Endpoint URL:

    • Go to the device configuration and locate the HTTP Payload Decoder section.

    • Copy the provided URL for sending data.

  2. Prepare JSON Data:

    • Use the JSON structure provided above.

    • Replace the "device" value with the serial number of your device (e.g., "Simon's API Demo Device 01").

  3. Send Data:

    • Set the method to POST.

    • Paste the API URL and the JSON data.

    • Send the request.

Configuring and Viewing Device Data

  1. Access Device Configuration:

    • Click on the device name in the list.

    • Go to the Configuration tab.

  2. View Logs:

    • In the HTTP Payload Decoder section, click Show Logs to see the JSON data received.

  3. Create Suggested Fields:

    • Scroll to the Fields section.

    • Create fields for each key in the JSON structure by clicking on them and confirming the suggested type.

Adding and Using New Fields

  1. Add New Data Keys:

    • Update your JSON data with new keys (e.g., "ambient_light": 500).

  2. Send Updated JSON:

    • Send the updated JSON data to the API endpoint.

  3. Create New Suggested Fields:

    • Go to the device configuration and view the new suggested fields.

    • Create fields for the new keys as described earlier.

Creating Dashboards

  1. Access the Dashboard:

    • Go to the Dashboard tab for your device.

  2. Enter Edit Mode:

    • Click on Enter Edit Mode.

  3. Add Widgets:

    • Click on Add Widget.

    • Select the type of widget (e.g., Value Widget).

    • Choose the data field (e.g., temperature).

    • Customize the widget and save.

  4. Add Device Fields Widget:

    • Add a Device Fields Widget to display all fields for debugging purposes.

Conclusion

You have now successfully set up a Datacake API device, configured it to receive JSON data, and created a dashboard to visualize the data. This guide provides a foundation for further customization, such as setting up rules, sharing dashboards, and adding more devices to your product. Happy monitoring!

Code Examples

Here are some code examples for Python, JavaScript, C#, and Arduino:

Python Example

import requests
import json

url = "https://your-api-endpoint-url"

data = {
    "device": "SimonsDevice01",
    "temperature": 23.34,
    "battery": 3.02,
    "humidity": 56,
    "co2": 506,
    "location": "(53.4562, 6.99349)",
    "power": True,
    "energy": 39495,
    "solar": True,
    "state": "System OK",
    "counter": 9349
}

headers = {
    "Content-Type": "application/json"
}

response = requests.post(url, headers=headers, data=json.dumps(data))

print(response.status_code)
print(response.text)

JavaScript Example (using Node.js)

const axios = require('axios');

const url = 'https://your-api-endpoint-url';

const data = {
    device: 'SimonsDevice01',
    temperature: 23.34,
    battery: 3.02,
    humidity: 56,
    co2: 506,
    location: '(53.4562, 6.99349)',
    power: true,
    energy: 39495,
    solar: true,
    state: 'System OK',
    counter: 9349
};

axios.post(url, data, {
    headers: {
        'Content-Type': 'application/json'
    }
})
.then(response => {
    console.log(response.status);
    console.log(response.data);
})
.catch(error => {
    console.error(error);
});

C# Example

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main()
    {
        var url = "https://your-api-endpoint-url";

        var data = new
        {
            device = "SimonsDevice01",
            temperature = 23.34,
            battery = 3.02,
            humidity = 56,
            co2 = 506,
            location = "(53.4562, 6.99349)",
            power = true,
            energy = 39495,
            solar = true,
            state = "System OK",
            counter = 9349
        };

        var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = await client.PostAsync(url, content);

        Console.WriteLine((int)response.StatusCode);
        var responseString = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseString);
    }
}

Arduino Example

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "your-SSID";
const char* password = "your-PASSWORD";
const char* serverName = "https://your-api-endpoint-url";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    http.begin(serverName);
    http.addHeader("Content-Type", "application/json");

    StaticJsonDocument<256> jsonDoc;
    jsonDoc["device"] = "SimonsDevice01";
    jsonDoc["temperature"] = 23.34;
    jsonDoc["battery"] = 3.02;
    jsonDoc["humidity"] = 56;
    jsonDoc["co2"] = 506;
    jsonDoc["location"] = "(53.4562, 6.99349)";
    jsonDoc["power"] = true;
    jsonDoc["energy"] = 39495;
    jsonDoc["solar"] = true;
    jsonDoc["state"] = "System OK";
    jsonDoc["counter"] = 9349;

    String requestBody;
    serializeJson(jsonDoc, requestBody);

    int httpResponseCode = http.POST(requestBody);

    if (httpResponseCode > 0) {
      String response = http.getString();
      Serial.println(httpResponseCode);
      Serial.println(response);
    } else {
      Serial.print("Error on sending POST: ");
      Serial.println(httpResponseCode);
    }

    http.end();
  }

  delay(60000); // Send data every 60 seconds
}

Feel free to merge these examples into the relevant sections of your documentation.

Use a tool like to simulate API requests.

ReqBin