Computer >> Máy Tính >  >> Lập trình >> Python

Cách trực quan hóa kết quả API bằng Python

Giới thiệu ..

Một trong những lợi thế lớn nhất của việc viết API là trích xuất dữ liệu hiện tại / trực tiếp, ngay cả khi dữ liệu thay đổi nhanh chóng, API sẽ luôn cập nhật dữ liệu. Các chương trình API sẽ sử dụng các URL rất cụ thể để yêu cầu thông tin nhất định, ví dụ:Top 100 bài hát được phát nhiều nhất năm 2020 trên Spotify hoặc Youtube Music. Dữ liệu được yêu cầu sẽ được trả về ở định dạng dễ dàng xử lý, chẳng hạn như JSON hoặc CSV.

Python cho phép người dùng viết các lệnh gọi API tới hầu hết mọi URL mà bạn có thể nghĩ đến. Trong ví dụ này, tôi sẽ trình bày cách trích xuất các kết quả API từ GitHub và trực quan hóa chúng.

Lưu ý - Kế hoạch là hiển thị kết quả API từ Spotify, nhưng Spotify yêu cầu nhiều điều kiện tiên quyết hơn có thể yêu cầu nhiều hơn 1 bài đăng, vì vậy chúng tôi sẽ gắn bó với GitHUb cho bài đăng này.

Github, thường được gọi là nhà phát triển Facebook cho phép chúng tôi viết các lệnh gọi API để trích xuất nhiều loại dữ liệu. Giả sử bạn muốn tìm kiếm kho Javascript Github với nhiều dấu sao hơn. GitHub không yêu cầu Khóa API trong khi người khác có thể muốn.

Cách thực hiện ..

1.Cài đặt gói yêu cầu bằng cách mở dấu nhắc lệnh python và kích hoạt các yêu cầu cài đặt pip.

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} ")

Đầu ra

*** Response from https://api.github.com/search/repositories?q=language:javascript&sort=stars is 200

2. API trả về thông tin ở định dạng JSON, vì vậy chúng ta cần sử dụng phương thức json () để chuyển đổi thông tin sang từ điển Python.

Ví dụ

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']}" )

Đầu ra

Các khóa
*** keys in the Json file
dict_keys(['total_count', 'incomplete_results', 'items'])

*** Total javascript repositories in GitHub
11199577
  • Vì vậy, chúng tôi có 3 khóa trong số đó chúng tôi có thể bỏ qua kết quả không đầy đủ. Hãy để chúng tôi kiểm tra kho lưu trữ đầu tiên của chúng tôi ngay bây giờ.

Ví dụ

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']} ")

Đầu ra

*** 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. Thời gian để hình dung, có rất nhiều thông tin để tiêu hóa, vì vậy cách tốt nhất là hình dung kết quả. Hãy nhớ - "Một bức tranh có giá trị bằng một ngàn lời nói".

Tôi đã đề cập đến matplotlib trong các bài đăng ở đây, vì vậy để có sự thay đổi, chúng tôi sẽ lập biểu đồ bằng cách sử dụng cốt truyện.

  • Cài đặt mô-đun - theo cốt truyện. Chúng tôi sẽ bắt đầu với việc nhập theo cốt truyện.

Ví dụ

from plotly.graph_objs import Bar
from plotly import offline

6.Chúng tôi sẽ làm một biểu đồ thanh với kho lưu trữ và số lượng sao. Càng nhiều sao thì kho lưu trữ càng phổ biến. Vì vậy, cách tốt để xem ai là người đứng đầu. Vì vậy, chúng ta cần hai tên kho lưu trữ biến và số sao.

Trong [6]:

Ví dụ

repo_names, repo_stars = [], []
for repo_info in repositories:
repo_names.append(repo_info['name'])
repo_stars.append(repo_info['stargazers_count'])

7. Bắt đầu trực quan hóa bằng cách chuẩn bị danh sách dữ liệu. Danh sách này chứa một từ điển, xác định loại biểu đồ và cung cấp dữ liệu cho các giá trị x- và y. Bạn có thể đã đoán được, vâng, chúng tôi sẽ sử dụng trục x để vẽ tên dự án và trục y để vẽ biểu đồ các ngôi sao.

Ví dụ

data_plots = [{'type' : 'bar', 'x':repo_names , 'y': repo_stars}]

8.Chúng tôi sẽ thêm tiêu đề cho trục x, trục y và cả biểu đồ nói chung.

Ví dụ

layout = {'title': 'GItHubs Most Popular Javascript Projects',
'xaxis': {'title': 'Repository'},
'yaxis': {'title': 'Stars'}}

9.Thời gian lập kế hoạch.

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')

Ví dụ

'Most_Popular_JavaScript_Repos.html'

Đầu ra

Most_Popular_JavaScript_Repos.html sẽ được tạo trong cùng thư mục với mã có đầu ra bên dưới.

Cách trực quan hóa kết quả API bằng Python