From c76ed6dac2dbec5723c313d5a6276e13bab338c8 Mon Sep 17 00:00:00 2001
From: Sara <sarasdj@stud.ntnu.no>
Date: Thu, 15 Feb 2024 11:58:27 +0100
Subject: [PATCH] add: get_weather()

---
 server/APIs/get_weather.py | 41 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 41 insertions(+)
 create mode 100644 server/APIs/get_weather.py

diff --git a/server/APIs/get_weather.py b/server/APIs/get_weather.py
new file mode 100644
index 00000000..69ffd747
--- /dev/null
+++ b/server/APIs/get_weather.py
@@ -0,0 +1,41 @@
+from flask import request
+import requests
+import datetime
+import json
+
+
+# get_weather retrieves weather data for a given set of coordinates
+def get_weather():
+    # Extract url parameters
+    latitude = request.args.get('lat', '')
+    longitude = request.args.get('lon', '')
+
+    # Form timestamp string with correct format
+    current_time = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
+
+    # Construct request string and execute get request to Yr API
+    url = f"https://api.met.no/weatherapi/locationforecast/2.0/compact?lat={latitude}&lon={longitude}"
+    response = requests.get(url)
+
+    if response.status_code == 200:  # Extract data from response
+        data = response.json()
+        timeseries = data['properties']['timeseries']
+
+        # Get data for current time
+        weather_data = None
+        for entry in timeseries:
+            if entry['time'] == current_time:
+                weather_data = entry['data']
+                break
+
+        if weather_data is not None:
+            resp_code = 200
+        else:
+            resp_code = 404  # Data for current time not found
+            weather_data = {}
+
+    else:  # Write empty data object and return status code 500
+        resp_code = 500
+        weather_data = {}
+
+    return json.dumps(weather_data), resp_code
-- 
GitLab