import requests class APIHandler: ''' Class to standardize the format of the headers of our http requests. ''' # TO-DO: remove static url. def __init__(self, apikey="", ELABFTW_API_URL="https://elabftw.fisica.unina.it/api/v2"): '''Init method, apikey suggested but not required (empty by default).''' self.auth = {"Authorization" : apikey} self.content = {"Content-Type" : "application/json"} self.header = {**self.auth, **self.content} self.elaburl = ELABFTW_API_URL def get_entry_from_elabid(self, elabid, entryType="items"): ''' Method which returns a resource's raw data (as dictionary) from its elabid and entry type. Entry type can be either "experiments" or "items". ''' # TO-DO: validation and error handling on entryType value. header = self.header response = requests.get( headers = header, url = f"{self.elaburl}/{entryType}/{elabid}", verify=True ) if response.status_code // 100 in [1,2,3]: entry_data = response.json() return entry_data elif response.status_code // 100 == 4: match response.status_code: case 401|403: raise ConnectionError(f"Invalid API key or authentication method.") case 404: raise ConnectionError(f"404: Not Found. This means there's no resource with this elabid (wrong elabid?) on your eLabFTW (wrong endpoint?).") case 400: raise ConnectionError(f"400: Bad Request. This means the API endpoint you tried to reach is invalid. Did you tamper with the source code? If not, contact the developer.") case _: raise ConnectionError(f"HTTP request failed with status code: {response.status_code} (NOTE: 4xx means user's fault).") else: raise ConnectionError(f"There's a problem on the server. Status code: {response.status_code}.")