Created
June 19, 2019 20:44
-
-
Save lsloan/6d4083fab6867cbdd7a53303a0d7e2eb to your computer and use it in GitHub Desktop.
Example of using the Univ. of Michigan API Directory to query the MCommunity service for a person by their uniqname.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import http.client | |
from base64 import b64encode | |
import json | |
clientId = os.getenv('UMICH_API_DIR_CLIENT_ID') | |
clientSecret = os.getenv('UMICH_API_DIR_CLIENT_SECRET') | |
uniqname = sys.argv[1] if len(sys.argv) > 1 else os.getenv('USER') | |
apiDir = http.client.HTTPSConnection('apigw.it.umich.edu') | |
def getApiDirAccessToken(clientId, clientSecret, scope = 'mcommunity'): | |
encodedIdAndSecret = b64encode('{}:{}'.format(clientId, clientSecret).encode('UTF-8')).decode('ASCII') | |
headers = { | |
'Authorization': 'Basic ' + encodedIdAndSecret, | |
} | |
apiDir.request('POST', 'um/inst/oauth2/token?grant_type=client_credentials&scope={}'.format(scope), headers=headers) | |
response = apiDir.getresponse() | |
authNData = json.loads(response.read().decode('UTF-8')) | |
return authNData.get('access_token') | |
def getMcommPersonByUniqname(uniqname, clientId, accessToken): | |
headers = { | |
'X-IBM-Client-ID': clientId, | |
'Authorization': 'Bearer ' + accessToken, | |
} | |
apiDir.request('GET', '/um/MCommunity/People/{}'.format(uniqname), headers=headers) | |
response = apiDir.getresponse() | |
return response.read() | |
if '__main__' == __name__: | |
accessToken = getApiDirAccessToken(clientId, clientSecret) | |
if not accessToken: | |
raise RuntimeError('Unable to get access token.') | |
mcommunityEntry = getMcommPersonByUniqname(uniqname, clientId, accessToken) | |
print(mcommunityEntry.decode('UTF-8')) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment