mjolnir1122 commited on
Commit
cdcdaac
·
verified ·
1 Parent(s): 1bf1eee

Update data_fetcher.py

Browse files
Files changed (1) hide show
  1. data_fetcher.py +22 -28
data_fetcher.py CHANGED
@@ -2,37 +2,31 @@ import requests
2
  import pandas as pd
3
  import os
4
 
5
- # ✅ Read API key securely from environment variables
6
- NREL_API_KEY = os.getenv("NREL_API_KEY")
7
 
8
- if not NREL_API_KEY:
9
- raise ValueError(" ERROR: NREL API Key is missing! Set it as an environment variable.")
10
 
11
  def fetch_nrel_data():
12
- """Fetch real-time hydrogen station data from NREL API."""
13
- url = f"https://developer.nrel.gov/api/hydrogen/v1/stations.json?api_key={NREL_API_KEY}"
 
 
14
 
15
  try:
16
- response = requests.get(url, timeout=10) # Timeout added for reliability
17
- response.raise_for_status() # Raise error for bad responses (4xx, 5xx)
18
- return response.json()
19
-
20
- except requests.exceptions.RequestException as e:
21
- print(f"⚠️ ERROR: Failed to fetch data from NREL API: {e}")
22
- return None # Return None if the API call fails
23
 
24
- def get_hydrogen_data():
25
- """Process hydrogen station data into a DataFrame."""
26
- data = fetch_nrel_data()
27
-
28
- if data is None or "fuel_stations" not in data:
29
- return None # Return None if API data is unavailable
30
-
31
- stations = data["fuel_stations"]
32
-
33
- df = pd.DataFrame(stations)
34
-
35
- if df.empty:
36
- return None # Return None if no data is available
37
-
38
- return df[["station_name", "state", "status", "capacity_kg_day", "street_address", "latitude", "longitude"]]
 
2
  import pandas as pd
3
  import os
4
 
5
+ import requests
6
+ import os
7
 
8
+ # Set your NREL API key here or use environment variables
9
+ NREL_API_KEY = "L0l8YMg3shJjkOS9kBAUCsbDglzJ0uYd8wMCNBdT" # Replace with your actual API key
10
 
11
  def fetch_nrel_data():
12
+ """
13
+ Fetch hydrogen station data from the NREL API.
14
+ """
15
+ url = f"https://developer.nrel.gov/api/alt-fuel-stations/v1.json?limit=10&api_key={NREL_API_KEY}"
16
 
17
  try:
18
+ response = requests.get(url)
19
+ response.raise_for_status() # Raise an error for HTTP codes 4xx or 5xx
 
 
 
 
 
20
 
21
+ data = response.json()
22
+
23
+ # Check if data contains the expected key
24
+ if "fuel_stations" in data and len(data["fuel_stations"]) > 0:
25
+ return data["fuel_stations"]
26
+ else:
27
+ print("⚠️ No hydrogen data available from NREL API.")
28
+ return None
29
+
30
+ except requests.exceptions.RequestException as e:
31
+ print(f"❌ API Request Failed: {e}")
32
+ return None