-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathso4t_api_v2.py
More file actions
174 lines (138 loc) · 6.49 KB
/
Copy pathso4t_api_v2.py
File metadata and controls
174 lines (138 loc) · 6.49 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# Standard Python libraries
import time
# Third-party libraries
import requests
# Local libraries
import so4t_request_validate
class V2Client(object):
def __init__(self, args):
if not args.url: # check if URL is provided; if not, exit
print("Missing required argument. Please provide a URL.")
print("See --help for more information")
raise SystemExit
# Establish the class variables based on which product is being used
if "stackoverflowteams.com" in args.url: # Stack Internal (Business) or Basic
self.soe = False
self.api_url = "https://api.stackoverflowteams.com/2.3"
self.team_slug = args.url.split("https://stackoverflowteams.com/c/")[1]
self.token = args.token
self.api_key = None
#Updated User-Agent
self.headers = {
'X-API-Access-Token': self.token,
'User-Agent': 'so4t_user_groups/1.0 (http://your-app-url.com; your-contact@email.com)'
}
if not self.token:
print("Missing required argument. Please provide an API token.")
print("See --help for more information")
raise SystemExit
else: # Stack Internal (Enterprise)
self.soe = True
self.api_url = args.url + "/api/2.3"
self.team_slug = None
self.token = None
self.api_key = args.key
#Updated User-Agent
self.headers = {
'X-API-Key': self.api_key,
'User-Agent': 'so4t_user_groups/1.0 (http://your-app-url.com; your-contact@email.com)'
}
if not self.api_key:
print("Missing required argument. Please provide an API key.")
print("See --help for more information")
raise SystemExit
# Test the API connection and set the SSL verification variable
self.ssl_verify = self.test_connection()
def test_connection(self):
url = self.api_url + "/tags"
ssl_verify = True
params = {}
if self.token:
headers = {'X-API-Access-Token': self.token}
params['team'] = self.team_slug
else:
headers = {'X-API-Key': self.api_key}
print("Testing API 2.3 connection...")
try:
response = requests.get(url, params=params, headers=headers)
except requests.exceptions.SSLError:
print("SSL error. Trying again without SSL verification...")
response = requests.get(url, params=params, headers=headers, verify=False)
ssl_verify = False
if response.status_code == 200:
print("API connection successful")
return ssl_verify
else:
print("Unable to connect to API. Please check your URL and API key/token.")
print(response.text)
raise SystemExit
def create_filter(self, filter_attributes='', base='default'):
# filter_attributes should be a list variable containing strings of the attributes
# base can be 'default', 'withbody', 'none', or 'total'
# Filter documentation: https://api.stackexchange.com/docs/filters
# Documentation for API endpoint: https://api.stackexchange.com/docs/create-filter
endpoint = "/filters/create"
endpoint_url = self.api_url + endpoint
params = {
'base': base,
'unsafe': False
}
if filter_attributes:
# The API endpoint requires a semi-colon separated string of attributes
# This converts the list of attributes into a string
params['include'] = ';'.join(filter_attributes)
response = self.get_items(endpoint_url, params)
filter_string = response[0]['filter']
print(f"Filter created: {filter_string}")
return filter_string
def get_all_users(self, filter_string=''):
# API endpoint documentation: https://api.stackexchange.com/docs/users
endpoint = "/users"
endpoint_url = self.api_url + endpoint
params = {
'page': 1,
'pagesize': 100,
}
if filter_string:
params['filter'] = filter_string
return self.get_items(endpoint_url, params)
def get_items(self, endpoint_url, params):
# Stack Internal (Business) and Basic require a team slug parameter
if not self.soe:
params['team'] = self.team_slug
items = []
while True: # Keep performing API calls until all items are received
if params.get('page'):
print(f"Getting page {params['page']} from {endpoint_url}")
else:
print(f"Getting data from {endpoint_url}")
try:
response = requests.get(endpoint_url, headers=self.headers, params=params,
verify=self.ssl_verify,
timeout=so4t_request_validate.timeout)
except Exception as ex:
so4t_request_validate.handle_except(ex)
continue
if response.status_code != 200:
# Many API call failures result in an HTTP 400 status code (Bad Request)
# To understand the reason for the 400 error, specific API error codes can be
# found here: https://api.stackoverflowteams.com/docs/error-handling
print(f"/{endpoint_url} API call failed with status code: {response.status_code}.")
print(response.text)
print(f"Failed request URL and params: {response.request.url}")
break
items += response.json().get('items')
if not response.json().get('has_more'):
break
# If the endpoint gets overloaded, it will send a backoff request in the response
# Failure to backoff will result in a 502 error (throttle_violation)
# Rate limiting documentation: https://api.stackexchange.com/docs/throttle
if response.json().get('backoff'):
backoff_time = response.json().get('backoff') + 1
so4t_request_validate.last_api_backoff = backoff_time
print(f"API backoff request received. Waiting {backoff_time} seconds...")
time.sleep(backoff_time)
else:
so4t_request_validate.last_api_backoff = 0
params['page'] += 1
return items