[SOLVED] Python API - Retrieve multiple values of one variable

Hi,

I want to retrieve the last 10 values from a variable using the Python API. Below script is done in python 2.7, from a Ubuntu machine.

I actually do manage to retrieve the lastest value stored in the variable, as you can see below:

from ubidots import ApiClient

api = ApiClient(token=‘xxxxxxx’)

my_specific_variable = api.get_variable(‘yyyyyy’)

values = my_specific_variable.get_values(10)

values[0][‘value’]

Output: 58.84375

However, when I try to retrieve the second last value, then python is throwing an error message “list index out of range”, as you can see below:

values[1][‘value’]

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
in ()
----> 1 values[1][‘value’]

IndexError: list index out of range

I can confirm that there are actually hundrets of values in that variable on the Ubidots server. So that shouldn’t be the list’s index limitation.

Do I use the API wrong?

Thanks a lot in advance for any hint!

Hi there! Here’s an example I use using Python’s HTTP Requests library directly. Turns out Python already made it soo easy to do HTTP requests, that using the Ubidots Python library is not “must” if you are familiar with Python:

import json
import requests

token = "your-token"

"""
Get values from variable 
"""
def get_values(device_label, var_label, items):

    base_url = "http://things.ubidots.com/api/v1.6/devices/" + device_label + "/" + var_label + "/values"
    try:
        r = requests.get(base_url + '?token=' + token + "&page_size=" + str(items), timeout=20)
        return r.json()
    except Exception as e:
        print(e)
        return {'error':'Request failed or timed out'}

"""
Main function
"""
if __name__ == '__main__':
    
    device_label = "machine"
    var_label = "current"
    values = get_values(device_label, var_label, 10)
    print(values)

Make sure you have Python Requests installed (http://docs.python-requests.org/en/master/user/install/)

1 Like