Balena Python SDK "Unauthorized" exception

Hi everyone, I am using the Balena Python-SDK to make API calls and retrieve data from Balena. I usually face the issues of “Unauthorized” requests quite often, and I don’t really know what the root cause is. I read somewhere that the Balena team throttles the login requests per day, so if you pass a certain limit then you cannot log in anymore. Could you please confirm these issues and provide alternative solutions to it?

The reason why I use the Python-SDK over Belana CLI is that I need the output to send it elsewhere, but on the command line, I’m really limited to what I can do with the data I retrieve.

Here is the sample code that I run which faces the problem (I don’t know after how many attempts):

Class BalenaHandler():
    def __init__(self, uuid):
        """
        :param: uuid (str) : the machine id
        """
        self.balena = Balena()
        self.balena.auth.login_with_token(config.BALENA_AUTH_TOKEN)
        self.UUID = uuid

then executing a simple function like:

def get_device_name(self):
    """
    Get the device name
    :param: none
    :return: device name (str)
    """
    return self.balena.models.device.get_name(self.UUID)

Creates the following error:

Traceback (most recent call last):
  File "BalenaCloudHandler.py", line 173, in <module>
    bh = BalenaHandler(uuid)
  File "BalenaCloudHandler.py", line 25, in __init__
    print(self.balena.models.api_key.get_all())
  File "/usr/local/lib/python3.6/dist-packages/balena/models/api_key.py", line 58, in get_all
    endpoint=self.settings.get('pine_endpoint')
  File "/usr/local/lib/python3.6/dist-packages/balena/base_request.py", line 197, in request
    raise exceptions.RequestError(response._content)
balena.exceptions.RequestError: b'Unauthorized'

Hi there, thanks for reaching out. Using the Python SDK is perfectly fine, that’s why we have it in the first place :slight_smile: Based on the error you are getting, I don’t think you are rate-limited, it is either that the token is invalid, has expired, or you are doing the request unauthenticated, but that is just my hunch.

Do you see the error only after running the code snippet multiple times? If you wait for a while, does it start to work again? What happens if you run is_login, let’s say, from get_device_name?

I reset the session token, but nothing happened, I got the same error. I honestly, don’t know the root cause of it, sometimes it works, and sometimes it doesn’t. However, each time I copy and paste the token, it looks different, so I’m not sure what is the reason behind this, it is supposed to change every 7 days, but it seems that it changes more often.

Could you please clarify what you mean by unauthenticated requests? I followed the exact same instructions in this documentation here. Just instead of the username and password, I use the session token.

The behavior is strange, if I don’t make API calls for a long time, it works, and after a few calls, it stops working and gives the “unauthorized” error.

So I added this code to get_device_name() function.

# Check if user logged in.
>>> if balena.auth.is_logged_in():
...     print('You are logged in!')
... else:
...     print('You are not logged in!')

Output:

You are not logged in!
Traceback (most recent call last):
  File "BalenaCloudHandler.py", line 220, in <module>
    print('Device device name: ', bh.get_device_name(uuid))
  File "BalenaCloudHandler.py", line 80, in get_device_name
    return self.balena.models.device.get_name(uuid)
  File "/usr/local/lib/python3.6/dist-packages/balena/models/device.py", line 293, in get_name
    return self.get(uuid)['device_name']
  File "/usr/local/lib/python3.6/dist-packages/balena/models/device.py", line 93, in get
    endpoint=self.settings.get('pine_endpoint')
  File "/usr/local/lib/python3.6/dist-packages/balena/base_request.py", line 197, in request
    raise exceptions.RequestError(response._content)
balena.exceptions.RequestError: b'Unauthorized'

I just reset the session token, but it didn’t work with Balena Python-SDK, but I tested it using Balena CLI, and it worked, I could log in.

I fixed the issue by creating an API key which gives me a permanent token, then I used it instead of the session token which expired pretty quickly.

Go to Balena Cloud > preferences > Acess tokens > Create API key (it will give you a permanent token)

Hi

Great that you got it working! The session tokens are indeed supposed to be refreshed using the API, whereas the API tokens are more permanent and are valid till you go and delete them from your account page.

I have pinged our relevant team to see if they can find any logs on our end to figure out why your session token was expiring earlier than expected. Thank for sharing your logs

@anujdeshpande great, thank you