Skip to main content
All CollectionsDeveloper Guides
Simulate data in Ubidots using Python
Simulate data in Ubidots using Python

Send a simple Python requests from your computer's terminal to test and interact with Ubidots' REST API.

Sergio M avatar
Written by Sergio M
Updated over 7 months ago

If you have a Raspberry Pi, Onion Omega, Beaglebone or other Linux-based device, or if you just want to create a script in your PC to interact with Ubidots, here's a brief example to get you there.

Requests: HTTP for Humans

Requests is a popular Python library that simplifies making HTTP requests from any python script which can be run in your computer's terminal or any embedded Linux device. If you do not have Python configured on your computer or device, reference to this official Python documentation to get started.

With your computer configured with Python correctly, run the pip package in your computer or device's terminal to install the correct library.

$ pip install requests

With Python properly installed, we will now need to create a Python script. Run the below command in your computer terminal to create a script.

$ nano

Python Script Theory

First, let's look at how Ubidots API expects an HTTP request to process data:

  • Method: HTTP allows for several methods (GET, POST, PUT, DELETE, etc). To create a value in Ubidots we use a POST request.

  • URL:  The URL of the resource you want to access (industrial.api.ubidots.com/api/v1.6/your-device-label/?token=your-token).

  • HTTP Headers: Ubidots' API uses JSON as the data type, so the header would be "Content-Type:application/json".

  • Body: A JSON string containing the label of the variable(s) and their values. For example: {"temperature":23, "humidity":98}.

Sending data with your code

Copy and paste the below code in your terminal; assigning your Ubidots TOKEN where indicated in the code. For more information, please see the Ubidots REST API Reference.

import time
import requests
import math
import random

TOKEN = "..."  # Put your TOKEN here
DEVICE_LABEL = "machine"  # Put your device label here
VARIABLE_LABEL_1 = "temperature"  # Put your first variable label here
VARIABLE_LABEL_2 = "humidity"  # Put your second variable label here
VARIABLE_LABEL_3 = "position"  # Put your second variable label here


def build_payload(variable_1, variable_2, variable_3):
    # Creates two random values for sending data
    value_1 = random.randint(-10, 50)
    value_2 = random.randint(0, 85)

    # Creates a random gps coordinates
    lat = random.randrange(34, 36, 1) + \
        random.randrange(1, 1000, 1) / 1000.0
    lng = random.randrange(-83, -87, -1) + \
        random.randrange(1, 1000, 1) / 1000.0
    payload = {variable_1: value_1,
               variable_2: value_2,
               variable_3: {"value": 1, "context": {"lat": lat, "lng": lng}}}

    return payload


def post_request(payload):
    # Creates the headers for the HTTP requests
    url = "http://industrial.api.ubidots.com"
    url = "{}/api/v1.6/devices/{}".format(url, DEVICE_LABEL)
    headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}

    # Makes the HTTP requests
    status = 400
    attempts = 0
    while status >= 400 and attempts <= 5:
        req = requests.post(url=url, headers=headers, json=payload)
        status = req.status_code
        attempts += 1
        time.sleep(1)

    # Processes results
print(req.status_code, req.json())
    if status >= 400:
        print("[ERROR] Could not send data after 5 attempts, please check \
            your token credentials and internet connection")
        return False

    print("[INFO] request made properly, your device is updated")
    return True


def main():
    payload = build_payload(
        VARIABLE_LABEL_1, VARIABLE_LABEL_2, VARIABLE_LABEL_3)

    print("[INFO] Attemping to send data")
    post_request(payload)
    print("[INFO] finished")


if __name__ == '__main__':
    while (True):
        main()
        time.sleep(1)

Once the code has been compiled with your Ubidots TOKEN, press CONTROL + O and ENTER to save the file - assigning a file name as you save (be sure to remember the ".py" in your file name). Once the script is saved, exit the Python editor by pressing CONTROL + X and return to the computer's terminal.

Execute your script

From your computer terminal, run the script, (including the saved script from Python editor) with the following command.

$ python [saved_script_name].py

Visualize your results

Run the code in your computer or device terminal to begin simulating data and visualize your work by logging into your Ubidots account.

Did this answer your question?