-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdavis_api_tool.py
84 lines (73 loc) · 2.15 KB
/
davis_api_tool.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
import collections
import hashlib
import hmac
import time
"""
Example showing API Signature calculation
for an API call to the /v2/current/{station-id}
API endpoint
"""
"""
Here is the list of parameters we will use for this example.
"""
parameters = {
"api-key": input("Input API key: "),
"api-secret": input("Input API secret: "),
"t": int(time.time()),
}
"""
Now we will compute the API Signature.
The signature process uses HMAC SHA-256 hashing and we will
use the API Secret as the hash secret key. That means that
right before we calculate the API Signature we will need to
remove the API Secret from the list of parameters given to
the hashing algorithm.
"""
"""
First we need to sort the paramters in ASCII order by the key.
The parameter names are all in US English so basic ASCII sorting is
safe. We will use an ordered dictionary to help keep the
parameters sorted.
"""
parameters = collections.OrderedDict(sorted(parameters.items()))
"""
Let's take a moment to print out all parameters for debugging
and educational purposes.
"""
for key in parameters:
print('Parameter name: "{}" has value "{}"'.format(key, parameters[key]))
"""
Save and remove the API Secret from the set of parameters.
"""
apiSecret = parameters["api-secret"]
parameters.pop("api-secret", None)
"""
Iterate over the remaining sorted parameters and concatenate
the parameter names and values into a single string.
"""
data = ""
for key in parameters:
data = data + key + str(parameters[key])
"""
Let's print out the data we are going to hash.
"""
print('Data string to hash is: "{}"'.format(data))
"""
Calculate the HMAC SHA-256 hash that will be used as the API Signature.
"""
apiSignature = hmac.new(
apiSecret.encode("utf-8"), data.encode("utf-8"), hashlib.sha256
).hexdigest()
"""
Let's see what the final API Signature looks like.
"""
print('API Signature is: "{}"'.format(apiSignature))
"""
Now that the API Signature is calculated let's see what the final
v2 API URL would look like for this scenario.
"""
print(
"v2 API URL: https://api.weatherlink.com/v2/stations?api-key={}&api-signature={}&t={}".format(
parameters["api-key"], apiSignature, parameters["t"]
)
)