Forums

Requests HTTPError: 401 with Sheety API

Hello,

I'm taking a course about Python and developed an app in Replit that uses the Sheety API, works well in Replit but when I run it in a free account of PythonAnywhere gives me the error "requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.sheety.co/.....".

The code is pretty much the same with the exception of the library dotenv for environment variables.

Any suggestions?

That 401 error is coming from the site itself. Check the content of the response to see if there's a clue to why the request is not authorised.

I don't know how else to interpret the error besides my URL is wrong, but I already copy & paste directly from the Sheety dashboard and doesn't work, copy & paste directly from the secrets seccion in Replit and doesn't work either.

I'm sure it is the correct URL and the code works in Replit and it does not work here.

import os

import requests
from dotenv import load_dotenv


class DataManager:
    def __init__(self) -> None:
        load_dotenv()
        self.sheety_url = os.getenv('SHEETY_URL')
        sheety_header = {
            'Authorization': os.getenv('SHEETY_AUTH')
        }
        response = requests.get(url=self.sheety_url, headers=sheety_header)
        response.raise_for_status()
        self.sheet_data = response.json()

For a moment I thought I was doing something wrong with the dotenv library, but when I print in console the variable type it shows it is a class 'str' and when I print the variable itself shows the URL complete and correct.

Is there something else I have to change in my code because I'm using a different service?

Are you sure that you are correctly setting the environment variables that you are using? Check that they are correctly set in the code where you use them.

Yes, I am sure. I already tried giving the values in the code without using dotenv and it's the same result.

sheety_header = {
    'Athorization': "USER AND PASSWORD"
}
response = requests.get(url="URL COPIED & PASTED DIRECTLY FROM SHEETY DASHBOARD", headers=sheety_header)
response.raise_for_status()

So, it is not the dotenv library.

I've tested the sheety api out in a Python console and can confirm that it works on my account. Your 401 error suggests that the auth is wrong. Can you confirm that your including the "Bearer" / "Basic" string in your token, it should look like Bearer =gb7zqF7/m... or Basic blhablhabl

You are right, in the .env file I had a character missing in my password. I was to focus on the URL that I never considered to be the credentials. I copied and pasted the password from the .env file when I was trying "giving the values in the code without using dotenv", that's why It was the same result.

Thank you.