<jupyter_start><jupyter_text>Yahoo API ExampleThis notebook is an example of using yahoo api to get fantasy sports data.<jupyter_code>from rauth import OAuth2Service
import webbrowser
import json<jupyter_output><empty_output><jupyter_text>**Prerequisite**First we need to create a Yahoo APP at https://developer.yahoo.com/apps/, and select Fantasy Sports - Read for API Permissions. Then we can get the Client ID (Consumer Key) and Client Secret (Consumer Secret)<jupyter_code>clientId= "<KEY>"
clinetSecrect="<KEY>"<jupyter_output><empty_output><jupyter_text>**Step 1: Create an OAuth object**<jupyter_code>oauth = OAuth2Service(client_id = clientId,
                      client_secret = clinetSecrect,
                      name = "yahoo",
                      access_token_url = "https://api.login.yahoo.com/oauth2/get_token",
                      authorize_url = "https://api.login.yahoo.com/oauth2/request_auth",
                      base_url = "http://fantasysports.yahooapis.com/fantasy/v2/")<jupyter_output><empty_output><jupyter_text>**Step 2: Generate authorize url, and then get the verify code**For this script, the redirect_uri is set to 'oob',and open a page in brower to get the verify code.For Web APP server, we can set redirect uri as callback domain during Yahoo APP creation.<jupyter_code>params = {
    'response_type': 'code',
    'redirect_uri': 'oob'
}
authorize_url = oauth.get_authorize_url(**params)
webbrowser.open(authorize_url)
code = input('Enter code: ')<jupyter_output>Enter code: gnybkmd<jupyter_text>**Step 3: Get session with the code**<jupyter_code>data = {
    'code': code,
    'grant_type': 'authorization_code',
    'redirect_uri': 'oob'
}
oauth_session = oauth.get_auth_session(data=data,
                                      decoder= lambda payload : json.loads(payload.decode('utf-8')))<jupyter_output><empty_output><jupyter_text>**Example to get user Info**<jupyter_code>user_url='https://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1'
resp = oauth_session.get(user_url, params={'format': 'json'})
resp.json()
user_guid=resp.json()['fantasy_content']['users']['0']['user'][0]['guid']
user_guid<jupyter_output><empty_output><jupyter_text>**Example to query nba teams of logged user.**<jupyter_code>team_url = 'https://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games;game_keys=nba/teams'
resp = oauth_session.get(team_url, params={'format': 'json'})
teams = resp.json()['fantasy_content']['users']['0']['user'][1]['games']['0']['game'][1]['teams']
teams
team_count = int(teams['count'])
team_count
for idx in range(0,team_count):
    team = teams[str(idx)]['team'][0][19]['managers']
    print(team, '\n')<jupyter_output>[{'manager': {'manager_id': '2', 'nickname': '邪', 'guid': 'EQMHXVGZ65XDJ5G57ZRRBKXUTM', 'is_current_login': '1', 'image_url': 'https://ct.yimg.com/cy/4556/23861899267_82a6e0_64sq.jpg'}}] 

[{'manager': {'manager_id': '17', 'nickname': '邪', 'guid': 'EQMHXVGZ65XDJ5G57ZRRBKXUTM', 'is_current_login': '1', 'image_url': 'https://ct.yimg.com/cy/4556/23861899267_82a6e0_64sq.jpg'}}] 

[{'manager': {'manager_id': '5', 'nickname': '邪', 'guid': 'EQMHXVGZ65XDJ5G57ZRRBKXUTM', 'is_current_login': '1', 'image_url': 'https://ct.yimg.com/cy/4556/23861899267_82a6e0_64sq.jpg'}}]<jupyter_text>**Example to get nba leagues of logged user**<jupyter_code>league_url = 'https://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games;game_keys=nba/leagues'
resp = oauth_session.get(league_url, params={'format': 'json'})
leagues = resp.json()['fantasy_content']['users']['0']['user'][1]['games']['0']['game'][1]['leagues']
leagues
league_count = int(leagues['count'])
league_count
for idx in range(0,league_count):
    league = leagues[str(idx)]['league'][0]
    print(league, '\n')<jupyter_output>{'league_key': '375.l.573', 'league_id': '573', 'name': 'Never Ending', 'url': 'https://basketball.fantasysports.yahoo.com/nba/573', 'draft_status': 'postdraft', 'num_teams': 20, 'edit_key': '2018-03-13', 'weekly_deadline': 'intraday', 'league_update_timestamp': '1520922304', 'scoring_type': 'head', 'league_type': 'private', 'renew': '364_817', 'renewed': '', 'iris_group_chat_id': 'TJA2CBKGARGW7H3THMJ2WKTA4Y', 'allow_add_to_dl_extra_pos': 1, 'is_pro_league': '0', 'is_cash_league': '0', 'current_week': 21, 'start_week': '1', 'start_date': '2017-10-17', 'end_week': '23', 'end_date': '2018-04-01', 'game_code': 'nba', 'season': '2017'} 

{'league_key': '375.l.1039', 'league_id': '1039', 'name': 'Alpha2017', 'url': 'https://basketball.fantasysports.yahoo.com/nba/1039', 'draft_status': 'postdraft', 'num_teams': 18, 'edit_key': '2018-03-14', 'weekly_deadline': '', 'league_update_timestamp': '1520922491', 'scoring_type': 'head', 'league_type': 'private', 'renew': '364_24740', 'renewed': '', 'i[...]<jupyter_text>**Example to get league metadata**<jupyter_code>settings_url = 'https://fantasysports.yahooapis.com/fantasy/v2/game/nba/leagues;league_keys=375.l.1039/settings'
resp = oauth_session.get(settings_url, params={'format': 'json'})
settings = resp.json()['fantasy_content']['game'][1]['leagues']['0']['league'][1]['settings'][0]
settings
stat_categories = settings['stat_categories']['stats']
for category in stat_categories:
    print(category['stat'], '\n')<jupyter_output>{'stat_id': 9004003, 'enabled': '1', 'name': 'Field Goals Made / Field Goals Attempted', 'display_name': 'FGM/A', 'sort_order': '1', 'position_type': 'P', 'stat_position_types': [{'stat_position_type': {'position_type': 'P', 'is_only_display_stat': '1'}}], 'is_only_display_stat': '1'} 

{'stat_id': 5, 'enabled': '1', 'name': 'Field Goal Percentage', 'display_name': 'FG%', 'sort_order': '1', 'position_type': 'P', 'stat_position_types': [{'stat_position_type': {'position_type': 'P'}}]} 

{'stat_id': 9007006, 'enabled': '1', 'name': 'Free Throws Made / Free Throws Attempted', 'display_name': 'FTM/A', 'sort_order': '1', 'position_type': 'P', 'stat_position_types': [{'stat_position_type': {'position_type': 'P', 'is_only_display_stat': '1'}}], 'is_only_display_stat': '1'} 

{'stat_id': 8, 'enabled': '1', 'name': 'Free Throw Percentage', 'display_name': 'FT%', 'sort_order': '1', 'position_type': 'P', 'stat_position_types': [{'stat_position_type': {'position_type': 'P'}}]} 

{'stat_id': 10, 'e[...]<jupyter_text>**Get all teams of a league**<jupyter_code>teams_url = 'https://fantasysports.yahooapis.com/fantasy/v2/league/375.l.573/teams'
resp = oauth_session.get(teams_url, params={'format': 'json'})
league_teams = resp.json()['fantasy_content']['league'][1]['teams']
league_teams
league_team_count = int(league_teams['count'])
league_team_count
for idx in range(0,league_team_count):
    league_team = league_teams[str(idx)]['team'][0]
    print(league_team, '\n')
    team_logo = league_team[5]['team_logos'][0]['team_logo']['url']
    # print('team_log', team_logo)<jupyter_output>[{'team_key': '375.l.573.t.1'}, {'team_id': '1'}, {'name': 'C1-szrocky'}, [], {'url': 'https://basketball.fantasysports.yahoo.com/nba/573/1'}, {'team_logos': [{'team_logo': {'size': 'large', 'url': 'https://ct.yimg.com/cy/4345/25942278979_a8f154_192sq.jpg?ct=fantasy'}}]}, {'division_id': '3'}, {'waiver_priority': 14}, {'faab_balance': '10'}, {'number_of_moves': '58'}, {'number_of_trades': '1'}, {'roster_adds': {'coverage_type': 'week', 'coverage_value': 21, 'value': '1'}}, [], {'league_scoring_type': 'head'}, [], [], {'has_draft_grade': 0}, {'auction_budget_total': '200'}, {'auction_budget_spent': 195}, {'managers': [{'manager': {'manager_id': '1', 'nickname': 'Rocky', 'guid': 'GH5XETJTNQTKCUZH6MZUNH2PBM', 'is_commissioner': '1', 'email': '<EMAIL>', 'image_url': 'https://ct.yimg.com/cy/4725/37939417090_dd288c_64sq.jpg'}}]}] 

[{'team_key': '375.l.573.t.2'}, {'team_id': '2'}, {'name': 'C2-真邪门'}, {'is_owned_by_current_login': 1}, {'url': 'https://basketball.fantasysports.yahoo.c[...]<jupyter_text>**Example to get team stats of week 2**<jupyter_code>stat_url = 'https://fantasysports.yahooapis.com/fantasy/v2/team/375.l.1039.t.17/stats;type=week;week=2'
resp = oauth_session.get(stat_url, params={'format': 'json'})
team_stats = resp.json()['fantasy_content']['team'][1]['team_stats']['stats']
team_stats<jupyter_output><empty_output><jupyter_text>**Example to get team stats of whole season**<jupyter_code>stat_url = 'https://fantasysports.yahooapis.com/fantasy/v2/team/375.l.1039.t.17/stats'
resp = oauth_session.get(stat_url, params={'format': 'json'})
team_stats = resp.json()['fantasy_content']['team'][1]['team_stats']['stats']
team_stats<jupyter_output><empty_output><jupyter_text>**Example to get game stat categories**<jupyter_code>stat_url = 'https://fantasysports.yahooapis.com/fantasy/v2/game/nba/stat_categories'
resp = oauth_session.get(stat_url, params={'format': 'json'})
stat_categories = resp.json()['fantasy_content']['game'][1]['stat_categories']['stats']
stat_categories<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.20555180939536974, 'fraction_numerical': 0.045178691840863115, 'mean_word_length': 7.255102040816326, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 51, 'https://': 20, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '274451', 'license': 'MIT', 'n_tokens_mistral': 3662, 'n_tokens_neox': 3345, 'n_words': 555, 'path': 'notebooks/yahoo-api-example.ipynb', 'repo_name': 'namiszh/fba', 'size': '9029'}