Provide a more useful response when a ValueError is encountered parsing a user's API request. #59

This commit is contained in:
Ian Renton
2025-10-20 08:54:07 +01:00
parent 8c2ab61049
commit b4d88a4770

View File

@@ -31,8 +31,8 @@ class WebServer:
bottle.BaseTemplate.defaults['software_version'] = SOFTWARE_VERSION bottle.BaseTemplate.defaults['software_version'] = SOFTWARE_VERSION
# Routes for API calls # Routes for API calls
bottle.get("/api/v1/spots")(lambda: self.serve_api(self.get_spot_list_with_filters())) bottle.get("/api/v1/spots")(lambda: self.serve_spots_api())
bottle.get("/api/v1/alerts")(lambda: self.serve_api(self.get_alert_list_with_filters())) bottle.get("/api/v1/alerts")(lambda: self.serve_alerts_api())
bottle.get("/api/v1/options")(lambda: self.serve_api(self.get_options())) bottle.get("/api/v1/options")(lambda: self.serve_api(self.get_options()))
bottle.get("/api/v1/status")(lambda: self.serve_api(self.status_data)) bottle.get("/api/v1/status")(lambda: self.serve_api(self.status_data))
bottle.post("/api/v1/spot")(lambda: self.accept_spot()) bottle.post("/api/v1/spot")(lambda: self.accept_spot())
@@ -56,6 +56,38 @@ class WebServer:
self.status = "Waiting" self.status = "Waiting"
run(host='localhost', port=self.port) run(host='localhost', port=self.port)
# Serve the JSON API /spots endpoint
def serve_spots_api(self):
try:
data = self.get_spot_list_with_filters()
return self.serve_api(data)
except ValueError as e:
logging.error(e)
response.content_type = 'application/json'
response.status = 400
return json.dumps("Bad request - " + str(e), default=serialize_everything)
except Exception as e:
logging.error(e)
response.content_type = 'application/json'
response.status = 500
return json.dumps("Error - " + str(e), default=serialize_everything)
# Serve the JSON API /alerts endpoint
def serve_alerts_api(self):
try:
data = self.get_alert_list_with_filters()
return self.serve_api(data)
except ValueError as e:
logging.error(e)
response.content_type = 'application/json'
response.status = 400
return json.dumps("Bad request - " + str(e), default=serialize_everything)
except Exception as e:
logging.error(e)
response.content_type = 'application/json'
response.status = 500
return json.dumps("Error - " + str(e), default=serialize_everything)
# Serve a JSON API endpoint # Serve a JSON API endpoint
def serve_api(self, data): def serve_api(self, data):
self.last_api_access_time = datetime.now(pytz.UTC) self.last_api_access_time = datetime.now(pytz.UTC)
@@ -109,6 +141,7 @@ class WebServer:
response.content_type = 'application/json' response.content_type = 'application/json'
response.set_header('Cache-Control', 'no-store') response.set_header('Cache-Control', 'no-store')
response.status = 201
return json.dumps("OK", default=serialize_everything) return json.dumps("OK", default=serialize_everything)
except Exception as e: except Exception as e:
logging.error(e) logging.error(e)