minitch/lib/itch.py

57 lines
2.0 KiB
Python

import requests
from urllib.parse import urljoin
class API_ERROR(Exception):
pass
class Client:
ITCH_API_BASE = 'https://itch.io/api/1/'
def __init__(self, api_key):
self.__api_key = api_key
self.__session = requests.Session()
self.__session.headers = {
'Content-Type': 'application/json'
}
def find_game(self, query: str, page: int = 1):
url = urljoin(self.ITCH_API_BASE, f'{self.__api_key}/search/games?query={query}&page={page}')
response = self.__session.get(url)
try:
return response.json()['games']
except requests.exceptions.JSONDecodeError as err:
raise API_ERROR(str(err))
except KeyError as err:
raise API_ERROR(str(err))
def game_uploads(self, game_id: int):
url = urljoin(self.ITCH_API_BASE, f'{self.__api_key}/game/{game_id}/uploads')
response = self.__session.get(url)
try:
return response.json()['uploads']
except requests.exceptions.JSONDecodeError as err:
raise API_ERROR(str(err))
except KeyError as err:
raise API_ERROR(str(err))
def game_url(self, upload_id: int):
url = urljoin(self.ITCH_API_BASE, f'{self.__api_key}/upload/{upload_id}/download')
response = self.__session.get(url)
try:
return response.json()['url']
except requests.exceptions.JSONDecodeError as err:
raise API_ERROR('Cound not decode answer: ' + str(err))
except KeyError as err:
raise API_ERROR('Could not find ' + str(err))
def game_meta(self, game_id: int):
url = urljoin(self.ITCH_API_BASE, f'{self.__api_key}/game/{game_id}')
response = self.__session.get(url)
try:
return response.json()['game']
except requests.exceptions.JSONDecodeError as err:
raise API_ERROR('Cound not decode answer: ' + str(err))
except KeyError as err:
raise API_ERROR('Could not find ' + str(err))