Forums

Unauthorized 401 PythonAnyWhere API

Good afternoon, there are problems using your API. When I run a request to get CPU data, I get a 401 code in response with the message "Authentication credentials not provided." I am attaching the source code of the script:

import requests

class Session():
    def __init__(self,username,token,domain=None):
    if domain==None: self.domain = f"{username}.pythonanywhere.com"
    self.username = username
    self.token = token
    self.host = 'https://pythonanywhere.com/'
    self.header = {
      'Content-Type':'application/json',
      'Authorization': f'Token {self.token}'
    }
    self.endpoints = {
      'reload':f"api/v0/user/{self.username}/webapps/{self.domain}/reload/",
      'consoles':f"api/v0/user/{self.username}/consoles/",
      'cpu':f"api/v0/user/{self.username}/cpu",
      'files':f"api/v0/user/{self.username}/files/",
      'webapps':f"api/v0/user/{self.username}/webapps/"
    }

def authorization(self):
    response = requests.get(
    f"{self.host}{self.endpoints['cpu']}",
    headers=self.header)
    print(self.header)
    if response.status_code == 200:
        return response.content['status']
    else:
        return 'Got unexpected status code {}: {!r}'.format(response.status_code, response.content)

s = Session(username='codefrag', token='XXX')
print(s.authorization())

All endpoints are hosted at https://www.pythonanywhere.com/ or https://eu.pythonanywhere.com/ depending on where your account is registered. So instead of assigning self.host attribute to a naked domain you should use the one starting with www.

Thanks!