-
Notifications
You must be signed in to change notification settings - Fork 0
/
hydapi.py
99 lines (78 loc) · 2.96 KB
/
hydapi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/python
import csv
import getopt
import json
import sys
try:
from urllib.request import Request, urlopen # Python 3
except ImportError:
from urllib2 import Request, urlopen # Python 2
def usage():
print()
print("Get observations from the NVE Hydrological API (HydAPI)")
print("Parameters:")
print(" -a: ApiKey (mandatory). ")
print(" -s: StationId (mandatory). Several stations can be given separated by comma. Example \"6.10.0,12.209.0")
print(" -p: Parameter (mandatory). Several Parameters can be given se")
print(" -r: Resolution time. 0 (instantenous),60 (hourly) or 1440 (daily). (mandatory)")
print(" -t: Reference time. See documentation for referencetime. Example \"P1D/\", gives one day back in time. If none given, the last observed value will be returned")
print(" -h: This help")
print()
print("Example:")
print(" python get-observations.py -a \"INSERT_APIKEY_HERE\" -s \"6.10.0,12.209.0\" -p \"1000,1001\" -r 60 -t \"P1D/\"")
print()
def main(argv):
try:
opts, args = getopt.getopt(argv, "a:s:p:r:ht:")
except getopt.GetoptError as err:
print(str(err)) # will print something like "option -a not recognized"
usage()
sys.exit(2)
station = "6.10.0,12.209.0"
parameter = "1000,1001"
resolution_time = 60
api_key = "INSERT_APIKEY_HERE"
reference_time = "P1D/"
for opt, arg in opts:
if opt == "-s":
station = arg
elif opt == "-p":
parameter = arg
elif opt == "-r":
resolution_time = arg
elif opt == "-a":
api_key = arg
elif opt == "-t":
reference_time = arg
elif opt == "-h":
usage()
sys.exit()
else:
assert False, "unhandled option"
if api_key == None:
print("Error: You must supply the api-key with your request (-a)")
usage()
sys.exit(2)
if station == None or parameter == None or resolution_time == None:
print("Error: You must supply the parameters station (-s), parameter (-p) and resolution time (-r)")
usage()
sys.exit(2)
baseurl = "https://hydapi.nve.no/api/v1/Observations?StationId={station}&Parameter={parameter}&ResolutionTime={resolution_time}"
url = baseurl.format(station=station, parameter=parameter,
resolution_time=resolution_time)
if reference_time is not None:
url = "{url}&ReferenceTime={reference_time}".format(
url=url, reference_time=reference_time)
print(url)
request_headers = {
"Accept": "application/json",
"X-API-Key": api_key
}
request = Request(url, headers=request_headers)
response = urlopen(request)
content = response.read().decode('utf-8')
parsed_result = json.loads(content)
for observation in parsed_result["data"]:
print(observation)
if __name__ == "__main__":
main(sys.argv[1:])