#! /usr/bin/env python import logging import json class TestApi: @staticmethod def __parse_arguments(): import argparse argParser = argparse.ArgumentParser( "testApi" ) argParser.add_argument( "method", choices=['GET', 'POST'] ) 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" ) argParser.add_argument( "--input", "-i", type=argparse.FileType("r"), default="-" ) 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( method=self.config.method, host=self.config.host, url="/".join([self.config.path, self.config.endpoint]), headers={ "Authorization": f"Basic {self.config.key}" }, input=load_json(self.config.input) ) def load_json(jsonFile): import json with jsonFile as f: return json.load(f) class apiCall: @staticmethod def call( method: str, host: str, url: str, headers: dict = None, input: dict = None, ) -> dict: import requests if(method=="GET"): r = requests.get( url=f"http://{host}/{url}", timeout=10, headers=headers ) elif(method=="POST"): r = requests.post( json=input, url=f"http://{host}/{url}", timeout=10, headers=headers ) else: logging.error("This line should never been reached!") try: return r.json() except Exception as e: logging.error(f"Exception {repr(e)} ({e}) while parsing json:") logging.error(r.text) if __name__ == "__main__": testApi = TestApi() response = testApi.apiCall() try: print( json.dumps( response, indent=2 ) ) except Exception as e: logging.error(f"Exception {repr(e)} ({e}) while parsing json:")