#! /usr/bin/env python from http import client import logging import json class TestApi: @staticmethod def __parse_arguments(): import argparse argParser = argparse.ArgumentParser( "testApi" ) argParser.add_argument("--endpoint", default="shiai" ) argParser.add_argument("--host", default="cwsvjudo.bplaced.net" ) argParser.add_argument("--path", default="participo/api" ) argParser.add_argument("--key", default=None ) argParser.add_argument("--configFile", type=argparse.FileType('r'), default="testApi.config.yaml" ) _LOG_LEVEL = ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"] argParser.add_argument("--logLevel", choices=_LOG_LEVEL, default="WARNING" ) return argParser.parse_args() def __init__(self): self.config = self.__parse_arguments() self.config.logLevel = getattr(logging, self.config.logLevel) logging.basicConfig(level=self.config.logLevel) with self.config.configFile as cf: from yaml import safe_load configData = safe_load(cf) # @todo: add the attributes from the config file to the config (if not already set) if not self.config.key and 'apiKey' in configData: self.config.key = configData['apiKey'] def apiCall(self): return apiCall.call( host=self.config.host, url="/".join([self.config.path, self.config.endpoint]), headers={ "Authorization": f"Basic {self.config.key}" } ) class apiCall: @staticmethod def call( host: str, url: str, headers: dict = None ) -> dict: import requests r = requests.get( url=f"http://{host}/{url}", # @todo The client always awaits this timeout. Even when the meaningful body is already received.params= # - I don't see any of the examples out there do it different from me. # - The browser doesn't seem to have this problem. timeout=10, headers=headers ) try: return r.json() except: logging.error(f"failed to parse json: {r.text}") if __name__ == "__main__": testApi = TestApi() response = testApi.apiCall() try: print( json.dumps( response, indent=2 ) ) except: logging.error("failed to parse to json:") logging.error(response)