Web API是網(wǎng)站的一部分,分為客戶端和服務(wù)端。客戶端通過向特定URL發(fā)送請(qǐng)求到服務(wù)端,服務(wù)端響應(yīng)客戶端的請(qǐng)求返回?cái)?shù)據(jù),這種請(qǐng)求方式稱為API調(diào)用。目前Web項(xiàng)目返回?cái)?shù)據(jù)格式常用JSON。 本章將介紹使用requests包調(diào)用GitHub提供的Web API,獲取當(dāng)前受歡迎的python項(xiàng)目,并繪制便于查看的交互式直方圖。 安裝requests包使用requests調(diào)用API,需要先使用pip安裝。pip是一個(gè)可用于下載并安裝Python包的模塊。 如果使用的是python早期版本,在終端輸入: python -m pip install --user requests
如果使用的是python3版本,在終端輸入: python3 -m pip install --user requests
在macOS系統(tǒng)中,如果這樣不管用,請(qǐng)嘗試在不指定標(biāo)志--user的情況下再次執(zhí)行該命令。 API調(diào)用請(qǐng)求數(shù)據(jù)我們將訪問GitHub(一個(gè)分布式版本控制系統(tǒng),可以協(xié)作開發(fā)項(xiàng)目)提供的Web API,獲取當(dāng)前星級(jí)最高的python項(xiàng)目。URL請(qǐng)求地址: https://api.github.com/search/repositories?q=language:python&sort=stars
1.通過Postman調(diào)用 我們可以看到數(shù)據(jù)以JSON格式返回,部分?jǐn)?shù)據(jù)如下: { 'total_count': 14436180, 'incomplete_results': false, 'items': [ { 'id': 54346799, 'node_id': 'MDEwOlJlcG9zaXRvcnk1NDM0Njc5OQ==', 'name': 'public-apis', 'full_name': 'public-apis/public-apis', 'private': false, 'owner': { 'login': 'public-apis', 'id': 51121562, 'node_id': 'MDEyOk9yZ2FuaXphdGlvbjUxMTIxNTYy', 'avatar_url': 'https://avatars./u/51121562?v=4', 'gravatar_id': '', 'url': 'https://api.github.com/users/public-apis' }, 'html_url': 'https://github.com/public-apis/public-apis', 'description': 'A collective list of free APIs', 'fork': false, 'created_at': '2016-03-20T23:49:42Z', 'updated_at': '2024-04-12T01:39:41Z', 'pushed_at': '2024-04-11T20:45:49Z', 'size': 5088, 'stargazers_count': 290914, 'watchers_count': 290914, 'language': 'Python', 'has_issues': true, 'has_projects': false, 'has_downloads': true, 'has_wiki': false, 'has_pages': false, 'has_discussions': false, 'forks_count': 31715, 'mirror_url': null, 'archived': false, 'disabled': false, 'open_issues_count': 250, 'visibility': 'public', 'forks': 31715, 'open_issues': 250, 'watchers': 290914, 'default_branch': 'master', 'score': 1.0 } ]}
我們重點(diǎn)關(guān)注“items”關(guān)聯(lián)的列表,列表的每個(gè)元素都對(duì)應(yīng)GitHub上的一個(gè)python項(xiàng)目。“name”表示項(xiàng)目名稱;“html_url”表示項(xiàng)目在GitHub倉庫的URL地址;“stargazers_count”表示項(xiàng)目星級(jí);“description”表示項(xiàng)目描述;“owner.login”表示項(xiàng)目所有者的登錄名。 2.通過requests調(diào)用 #調(diào)用Web APIimport requestsfrom requests.models import Responseurl='https://api.github.com/search/repositories?q=language:python&sort=stars'headers = {'Accept': 'application/vnd.github.v3+json'}#返回一個(gè)<class 'requests.models.Response'>的對(duì)象response=requests.get(url,headers=headers)#狀態(tài)碼status_code=response.status_codeif response.ok:#注意:這里添加了@property,所以是個(gè)屬性,而不是方法 #返回json格式的響應(yīng)內(nèi)容 content=response.json() #print(content) repo_dicts=content['items'] for repo_dict in repo_dicts: repo_name = repo_dict['name'] repo_url = repo_dict['html_url'] owner = repo_dict['owner']['login'] description = repo_dict['description'] star=repo_dict['stargazers_count'] print(f'{repo_name} {star} {repo_url} {owner} {description}')else: print(f'invoke {url} failed,code:{status_code}')
繪制交互式的直方圖我們將通過繪制交互式的直方圖的方式,呈現(xiàn)GitHub上受歡迎的python項(xiàng)目。點(diǎn)擊項(xiàng)目名稱會(huì)跳轉(zhuǎn)到對(duì)應(yīng)的GitHub項(xiàng)目,鼠標(biāo)懸停在條形上會(huì)展示項(xiàng)目信息。 #調(diào)用Web APIimport requestsimport plotly.express as px#繪制交互式的直方圖def draw_histogram(x,y,title,x_label,y_label,hover_texts): labels = {'x': x_label, 'y': y_label} fig = px.bar(x=x, y=y, title=title, labels=labels, hover_name=hover_texts) fig.update_layout(title_font_size=28, xaxis_title_font_size=20, yaxis_title_font_size=20) fig.update_traces(marker_color='SteelBlue', marker_opacity=0.6) fig.show()url='https://api.github.com/search/repositories?q=language:python&sort=stars'headers = {'Accept': 'application/vnd.github.v3+json'}#返回一個(gè)<class 'requests.models.Response'>的對(duì)象response=requests.get(url,headers=headers)#狀態(tài)碼status_code=response.status_codeif response.ok:#注意:這里添加了@property,所以是個(gè)屬性,而不是方法 #返回json格式的響應(yīng)內(nèi)容 content=response.json() #print(content) repo_dicts=content['items'] # 鏈接地址,星級(jí),鼠標(biāo)懸停展示信息 repo_links, stars, hover_texts = [], [], [] for repo_dict in repo_dicts: repo_name = repo_dict['name'] repo_url = repo_dict['html_url'] owner = repo_dict['owner']['login'] description = repo_dict['description'] star=repo_dict['stargazers_count'] #print(f'{repo_name} {star} {repo_url} {owner} {description}') repo_link = f'<a href='{repo_url}'>{repo_name}</a>' repo_links.append(repo_link) stars.append(star) hover_text = f'{owner}<br />{description}' hover_texts.append(hover_text) x = repo_links y = stars title = 'Most-Starred Python Projects on GitHub' x_label='Repository' y_label='Stars' draw_histogram(x,y,title,x_label,y_label,hover_texts)else: print(f'invoke {url} failed,code:{status_code}')
繪制效果圖: 我們點(diǎn)擊項(xiàng)目名稱“public-apis”,會(huì)跳轉(zhuǎn)到對(duì)應(yīng)的GitHub項(xiàng)目。
|