如何使用 Python 視覺化 API 結果
簡介..
編寫 API 最大的優勢之一是提取當前/即時資料,即使資料快速變化,API 也會始終獲取最新的資料。API 程式將使用非常具體的 URL 來請求某些資訊,例如 Spotify 或 Youtube Music 中 2020 年播放次數最多的 100 首歌曲。請求的資料將以易於處理的格式返回,例如 JSON 或 CSV。
Python 允許使用者向幾乎任何你能想到的 URL 傳送 API 呼叫。在本例中,我將展示如何提取 GitHub 的 API 結果並將其視覺化。
注意 - 計劃是展示 Spotify 的 API 結果,但 Spotify 需要更多先決條件,這可能需要不止一篇帖子,所以我們將在本帖中堅持使用 GitHUb。
Github,通常被稱為開發者的 Facebook,允許我們編寫 API 呼叫以提取各種資料。假設您想搜尋星標數較多的 Javascript Github 儲存庫。GitHub 不需要 API 金鑰,而其他 API 可能會需要。
如何操作..
1. 透過開啟 Python 命令提示符並執行 pip install requests 來安裝 requests 包。
import requests # set the siteurl site_url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars' # set the headers headers = {'Accept': 'application/vnd.github.v3+json'} # call the url and save the response response = requests.get(site_url, headers=headers) # Get the response print(f"Output \n *** Response from {site_url} is {response.status_code} ")
輸出
*** Response from https://api.github.com/search/repositories?q=language:javascript&sort=stars is 200
2. API 以 JSON 格式返回資訊,因此我們需要使用 json() 方法將資訊轉換為 Python 字典。
示例
response_json = response.json() print(f"Output \n *** keys in the Json file \n {response_json.keys()} \n") print(f" *** Total javascript repositories in GitHub \n {response_json['total_count']}" )
輸出
*** keys in the Json file dict_keys(['total_count', 'incomplete_results', 'items']) *** Total javascript repositories in GitHub 11199577
因此,我們有 3 個鍵,其中我們可以忽略 incomplete_results。現在讓我們檢查一下我們的第一個儲存庫。
示例
repositories = response_json['items'] first_repo = repositories[0] print(f"Output \n *** Repository information keys total - {len(first_repo)} - values are -\n") for keys in sorted(first_repo.keys()): print(keys) print(f" *** Repository name - {first_repo['name']}, Owner - {first_repo['owner']['login']}, total watchers - {first_repo['watchers_count']} ")
輸出
*** Repository information keys total - 74 - values are - archive_url archived assignees_url blobs_url branches_url clone_url collaborators_url comments_url commits_url compare_url contents_url contributors_url created_at default_branch deployments_url description disabled downloads_url events_url fork forks forks_count forks_url full_name git_commits_url git_refs_url git_tags_url git_url has_downloads has_issues has_pages has_projects has_wiki homepage hooks_url html_url id issue_comment_url issue_events_url issues_url keys_url labels_url language languages_url license merges_url milestones_url mirror_url name node_id notifications_url open_issues open_issues_count owner private pulls_url pushed_at releases_url score size ssh_url stargazers_count stargazers_url statuses_url subscribers_url subscription_url svn_url tags_url teams_url trees_url updated_at url watchers watchers_count *** Repository name - freeCodeCamp, Owner - freeCodeCamp, total watchers - 316079
4. 視覺化時間,有很多資訊需要消化,所以最好的方法是將結果視覺化。記住 - “一張圖片勝過千言萬語”。
我已經在其他帖子中介紹過 matplotlib,所以為了改變一下,我們將使用 plotly 繪製圖表。
安裝模組 - plotly。我們將從匯入 plotly 開始。
示例
from plotly.graph_objs import Bar from plotly import offline
6. 我們將使用儲存庫與星標數繪製條形圖。星標越多,儲存庫越受歡迎。所以,這是一個檢視誰排在頂端的好方法。因此,我們需要兩個變數:儲存庫名稱和星標數。
In[6]
示例
repo_names, repo_stars = [], [] for repo_info in repositories: repo_names.append(repo_info['name']) repo_stars.append(repo_info['stargazers_count'])
7. 透過準備資料列表開始視覺化。這包含一個字典,它定義了繪圖的型別並提供 x 和 y 值的資料。你可能已經猜到了,是的,我們將使用 x 軸繪製專案名稱,使用 y 軸繪製星標數。
示例
data_plots = [{'type' : 'bar', 'x':repo_names , 'y': repo_stars}]
8. 我們將新增 x 軸、y 軸以及整個圖表的標題。
示例
layout = {'title': 'GItHubs Most Popular Javascript Projects', 'xaxis': {'title': 'Repository'}, 'yaxis': {'title': 'Stars'}}
9. 繪製時間。
import requests from plotly.graph_objs import Bar from plotly import offline site_url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars' headers = {'Accept': 'application/vnd.github.v3+json'} response = requests.get(site_url, headers=headers) response_json = response.json() repo_names, repo_stars = [], [] for repo_info in repositories: repo_names.append(repo_info['name']) repo_stars.append(repo_info['stargazers_count']) data_plots = [{'type' : 'bar', 'x':repo_names , 'y': repo_stars}] layout = {'title': 'GItHubs Most Popular Javascript Projects', 'xaxis': {'title': 'Repository'}, 'yaxis': {'title': 'Stars'}} fig = {'data': data_plots, 'layout': layout} offline.plot(fig, filename='Most_Popular_JavaScript_Repos.html')
示例
'Most_Popular_JavaScript_Repos.html'
輸出
Most_Popular_JavaScript_Repos.html 將與程式碼在同一目錄中建立,輸出如下所示。