# HTTP Decoders on API Devices and Code Examples

## 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

{% embed url="<https://www.loom.com/share/395305d318634cae9808523a43aef7fd>" %}

## 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:

```json
{
   "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:**
   * Use a tool like [ReqBin](https://reqbin.com/) to simulate API requests.
   * 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

```python
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)

```javascript
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

```csharp
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

```cpp
#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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.datacake.de/generic-api-devices/http-decoders-on-api-devices-and-code-examples.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
