-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsgraph.py
64 lines (49 loc) · 2.13 KB
/
msgraph.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
import requests
import msal
import json
import logging
import os
# from dotenv import dotenv_values # change os.environ => config
# loads .env file, returns dict of values
# os.environ = dotenv_values(".env")
class msgraphapi:
result = None
def getAccessToken(self):
# initialize app
app = msal.ConfidentialClientApplication(
os.environ["client_id"],
authority=os.environ["authority"],
client_credential=os.environ["secret"],)
# attempts to aquire token
msgraphapi.result = app.acquire_token_silent([os.environ["scope"]], account=None)
# if token does not esits, print error message
if not msgraphapi.result:
logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
msgraphapi.result = app.acquire_token_for_client(scopes=[os.environ["scope"]])
def getAction(self, action):
# which data to grab (e.g. Staff or Students)
self.action = action
def makeRequest(self):
# determine which endpoint to hit
if (self.action == "student"):
endpoint = os.environ["stu_endpoint"]
if (self.action == "staff"):
endpoint = os.environ["stf_endpoint"]
if (self.action == "total"):
endpoint = os.environ["tot_endpoint"]
# if access token exists
if "access_token" in msgraphapi.result:
# Call Graph API using the access token
graph_data = requests.get(
endpoint,
headers={'Authorization': 'Bearer ' + msgraphapi.result['access_token']}, ).json()
# print(f'Graph API call result for {self.action}: ')
# converts JSON obj to string
result = json.dumps(graph_data)
# converts JSON str to dict (python readable version of JSON)
data = json.loads(result)
return data
else:
print(msgraphapi.result.get("error"))
print(msgraphapi.result.get("error_description"))
print(msgraphapi.result.get("correlation_id")) # You may need this when reporting a bug