Web API是网站的一部分服务端与客户端api,分为客户端和服务端。客户端通过向特定URL发送请求到服务端,服务端响应客户端的请求返回数据,这种请求方式称为API调用。目前Web项目返回数据格式常用JSON。
本章将介绍使用requests包调用GitHub提供的Web API,获取当前受欢迎的python项目,并绘制便于查看的交互式直方图。
安装requests包使用requests调用API,需要先使用pip安装。pip是一个可用于下载并安装Python包的模块。
如果使用的是python早期版本,在终端输入:
python -m pip install --user requests如果使用的是python3版本,在终端输入:
python3 -m pip install --user requests在macOS系统中,如果这样不管用,请尝试在不指定标志--user的情况下再次执行该命令。
API调用请求数据我们将访问GitHub(一个分布式版本控制系统,可以协作开发项目)提供的Web API,获取当前星级最高的python项目。URL请求地址:
https://api.github.com/search/repositories?q=language:python&sort=stars1.通过Postman调用
我们可以看到数据以JSON格式返回,部分数据如下:
{ "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.githubusercontent.com/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 } ]}我们重点关注“items”关联的列表,列表的每个元素都对应GitHub上的一个python项目。“name”表示项目名称服务端与客户端api;“html_url”表示项目在GitHub仓库的URL地址服务端与客户端api;“stargazers_count”表示项目星级;“description”表示项目描述;“owner.login”表示项目所有者的登录名。
2.通过requests调用
#调用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"}#返回一个<class 'requests.models.Response'>的对象response=requests.get(url,headers=headers)#状态码status_code=response.status_codeif response.ok:#注意:这里添加了@property,所以是个属性,而不是方法 #返回json格式的响应内容 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}")绘制交互式的直方图我们将通过绘制交互式的直方图的方式,呈现GitHub上受欢迎的python项目。点击项目名称会跳转到对应的GitHub项目,鼠标悬停在条形上会展示项目信息。
#调用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"}#返回一个<class 'requests.models.Response'>的对象response=requests.get(url,headers=headers)#状态码status_code=response.status_codeif response.ok:#注意:这里添加了@property,所以是个属性,而不是方法 #返回json格式的响应内容 content=response.json() #print(content) repo_dicts=content['items'] # 链接地址,星级,鼠标悬停展示信息 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}")绘制效果图:
我们点击项目名称“public-apis”,会跳转到对应的GitHub项目。
标签: 服务端与客户端api