From baf7188753f7dfeee711ee694752da149216a844 Mon Sep 17 00:00:00 2001 From: Hanne Heggdal Date: Wed, 26 Mar 2025 15:08:23 +0100 Subject: [PATCH] function to fetch current data --- src/my_package/fetch_current_data.py | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/my_package/fetch_current_data.py diff --git a/src/my_package/fetch_current_data.py b/src/my_package/fetch_current_data.py new file mode 100644 index 0000000..787f3c3 --- /dev/null +++ b/src/my_package/fetch_current_data.py @@ -0,0 +1,38 @@ +# Import of needed libaries +import requests +import os +from dotenv import load_dotenv + +load_dotenv() + +# Gets the key, from my env file +API_KEY = os.getenv("API_KEY") + +# city_name = "Trondheim" +country_code = "NO" + + +# Gets the data from the API - openweathermap.org +def fetch_current_data(city_name): + + + # f-string url, to add the "custom" variables to the API-request + url = f"https://api.openweathermap.org/data/2.5/weather?q={city_name},NO&units=metric&appid={API_KEY}" + + # Saves the API-request for the url + response = requests.get(url) + + # Checks if the status code is OK + if response.status_code == 200: + + # Converts the data into json + data = response.json() + folder = "../data/output_current_data" + + print("Data fetch: ok") + return data, folder + + + else: + # If html status code != 200, print the status code + print("Failed to fetch data from API. Status code:", response.status_code) \ No newline at end of file