Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
d8d840d
made quotation marks consistent for strings.
Ruefa Jun 25, 2019
3ff0e00
fixed styling to be consistent with flake8 and osu style guides.
Ruefa Jun 25, 2019
fec830b
created readme
Ruefa Jun 25, 2019
b6c47af
added requirements.txt
Ruefa Jun 25, 2019
8df0c30
added Usage steps to the readme
Ruefa Jun 25, 2019
bc2125c
fixed typo on usage step 1. L -> :
Ruefa Jun 25, 2019
310ee21
changed from sting concatenation to use f string
Ruefa Jun 25, 2019
5ab69f3
created example configuration file
Ruefa Jun 25, 2019
4a2ea6a
removed api urls from main script. They exist in configuration-exampl…
Ruefa Jun 25, 2019
472a0e4
changed double quotes to single quotes
Ruefa Jun 25, 2019
ee88f4a
added persons api url to configuration
Ruefa Jun 25, 2019
172ba78
changed to read oauth2 and api urls from configuration file.
Ruefa Jun 25, 2019
5054daa
changed locations to directory.
Ruefa Jun 25, 2019
d6fc3af
had trouble getting directory working. switched back to persons
Ruefa Jun 25, 2019
bc8f619
wrote configuration section on readme
Ruefa Jun 25, 2019
6157068
added error handling
Ruefa Jun 25, 2019
c7b687f
fixed typo in readme
Ruefa Jun 25, 2019
b14b307
updated to python3 in readme
Ruefa Jun 25, 2019
3816016
Made directory request work now that the app has access
Ruefa Jun 25, 2019
6e4a8ef
added comments to get_directory method
Ruefa Jun 25, 2019
80e8476
fixed json import placement since it is part of python system files
Ruefa Jun 25, 2019
6adbe9d
started checking for not 200 error codes instead of a particular erro…
Ruefa Jun 25, 2019
d4a8123
used f strings instead of concatination
Ruefa Jun 25, 2019
b72a850
renamed all variables from camel case to snake case
Ruefa Jun 25, 2019
84142a1
changed method comment blocks into docstrings
Ruefa Jun 25, 2019
0da7e83
fixed formatting of input loops
Ruefa Jun 25, 2019
fd0107d
made final string for configuration json objects 'api' and 'oauth2'
Ruefa Jun 25, 2019
c4a7950
added method to check if a request has returned with an error
Ruefa Jun 25, 2019
b6a5f97
added request error handling to methods
Ruefa Jun 25, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Alex API Intro ![python](https://img.shields.io/badge/python-3.7-blue.svg)

Introduction to using OSU's APIs

## Configuration

1. Register an application on [OSU Developer Portal](https://developer.oregonstate.edu/)
2. Get `client_id` and `client_secret` from your app, then copy [configuration-example.json](./configuration-example.json) as `configuration.json` and fill in the oauth2 section:

```json
"oauth2": {
"auth_api_url": "https://api.oregonstate.edu/oauth2/token",
"client_id": "your_client_id",
"client_secret": "your_client_secret"
}
```

## Usage

1. Install dependencies via pip:

```shell
$ pip3 install -r requirements.txt
```
2. Run the script:

```shell
$ python3 api_intro.py path/to/configuration.json
```
121 changes: 96 additions & 25 deletions api_intro.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,110 @@
# api_intro.py
# authorize and send requests using OSU's API
import json
import sys

import requests

personsUrl = "https://api.oregonstate.edu/v1/persons"
authUrl = "https://api.oregonstate.edu/oauth2/token"

# Request access_token from osu api
# Read in consumer key and consumer secret from user
def get_access_token():
key = input("Enter Consumer Key: ")
secret = input("Enter Consumer Secret: ")
def get_access_token(authUrl, id, secret):
"""Request access_token from osu api
Read in consumer key and consumer secret from user"""

data = {"client_id": key, "client_secret": secret, "grant_type": "client_credentials"}
data = {'client_id': id, 'client_secret': secret,
'grant_type': 'client_credentials'}
request = requests.post(authUrl, data=data)
response = request.json()

return response["access_token"]
try:
response['access_token']
return response['access_token']
except KeyError:
if request.status_code != 200:
print('Client Id or Client Secret invalid. '
f'Please check your configuration.json '
f'file and try again.')
else:
print('Unknown error occurred.')
exit()

# Make get request for information about a person at osu
# Read in ONID from user
# requires access_token retrieved in get_access_token()
def get_person(access_token):
onid = input("Enter Person's ONID: ")

params = {'onid': onid}
headers = {"Content-Type": "application/json", "Authorization": "Bearer " + access_token}
def get_person(access_token, api_url):
"""Make get request for information about a person at osu
Read in ONID from user
requires access_token retrieved in get_access_token()"""

request = requests.get(personsUrl, params=params, headers=headers)
response = request.json()
return response["data"]
while True:
onid = input('Enter Person\'s ONID: ')

params = {'onid': onid}
headers = {'Content-Type': 'application/json',
'Authorization': f'Bearer {access_token}'}

request = requests.get(api_url, params=params, headers=headers)
if not check_request_errors(request):
response = request.json()
response_data = response['data']
if response_data:
return response_data
else:
print(f'No data found for \"{onid}\". '
f'Please try a different search query.')


def get_directory(access_token, apiUrl):
"""Requests OSU directory information using api
requires an access token and api url to be passed in
asks for search query from user
returns data if the search query finds some.
If no data is found the user is asked again to enter a query"""

while True:
query = input('Enter Directory Search Query: ')

params = {'q': query}
headers = {'Content-Type': 'application/json',
'Authorization': f'Bearer {access_token}'}

request = requests.get(apiUrl, params=params, headers=headers)
if not check_request_errors(request):
response = request.json()
response_data = response['data']
if response_data:
return response['data']
else:
print(f'No data found for \"{query}\". '
f'Please try a different search query.')


def check_request_errors(request):
"""Checks if a request has returned with an error
returns False if the status code is equal to 200, otherwise returns True"""

error = True

if request.status_code == 200:
error = False
else:
print(request.json()['userMessage'])

return error


if __name__ == '__main__':
CONFIG_API = 'api'
CONFIG_OAUTH = 'oauth2'

config_path = sys.argv[1]
with open(config_path, 'r') as configFile:
config = json.load(configFile)
persons_url = config[CONFIG_API]['persons_url']
directory_url = config[CONFIG_API]['directory_url']
auth_url = config[CONFIG_OAUTH]['auth_api_url']
client_id = config[CONFIG_OAUTH]['client_id']
client_secret = config[CONFIG_OAUTH]['client_secret']

access_token = get_access_token(auth_url, client_id, client_secret)
directory_data = get_directory(access_token, directory_url)

if __name__ == "__main__":
access_token = get_access_token()
personData = get_person(access_token)

for person in personData:
print("Person's Name: " + person["attributes"]["firstName"])
for directory in directory_data:
print(directory['attributes']['firstName'])
11 changes: 11 additions & 0 deletions configuration-example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"api": {
"directory_url": "https://api.oregonstate.edu/v1/directory",
"persons_url": "https://api.oregonstate.edu/v1/persons"
},
"oauth2": {
"auth_api_url": "https://api.oregonstate.edu/oauth2/token",
"client_id": "your_client_id",
"client_secret": "your_client_secret"
}
}
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
requests==2.22.0