소개
API를 활용하는 가장 큰 장점 중 하나는 최신 데이터를 실시간으로 가져올 수 있다는 점입니다. 데이터가 빠르게 변하더라도 API는 항상 최신 상태의 데이터를 제공합니다. API 프로그램은 특정 정보를 요청하기 위해 매우 구체적인 URL을 사용합니다. 예를 들어 Spotify나 YouTube Music에서 2020년 가장 많이 재생된 인기 곡 TOP 100을 요청하는 식입니다. 요청된 데이터는 JSON이나 CSV처럼 손쉽게 처리할 수 있는 형식으로 반환됩니다.
Python을 사용하면 거의 모든 URL에 대해 API 호출을 작성할 수 있습니다. 이 글에서는 GitHub에서 API 결과를 추출하고 이를 시각화하는 방법을 단계별로 소개합니다.
참고 - 원래는 Spotify API 결과를 보여줄 계획이었지만, Spotify는 사전 준비 작업이 많아 여러 편의 글이 필요할 수 있어 이번 글에서는 GitHub을 다루기로 했습니다.
개발자들의 페이스북이라 불리는 GitHub은 다양한 종류의 데이터를 추출할 수 있는 API 호출을 지원합니다. 예를 들어 별(star)이 많은 JavaScript 저장소를 검색하고 싶다고 가정해 봅시다. GitHub은 별도의 API 키가 필요 없다는 점에서 다른 서비스와 차별화됩니다.
실습 방법
1. Python 명령 프롬프트를 열고 pip install requests 명령어로 requests 패키지를 설치합니다.
import requests
# 사이트 URL 설정
site_url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars'
# 헤더 설정
headers = {'Accept': 'application/vnd.github.v3+json'}
# URL 호출 후 응답 저장
response = requests.get(site_url, headers=headers)
# 응답 확인
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 모듈을 설치한 뒤 임포트하여 시작합니다.
예제
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 파일이 코드와 같은 디렉터리에 생성되며, 아래와 같은 결과를 확인할 수 있습니다.
