13.python学习笔记-API调用_python通过api获取数据

liftword5个月前 (02-09)技术文章46

Web 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=stars

1.通过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”表示项目名称;“html_url”表示项目在GitHub仓库的URL地址;“stargazers_count”表示项目星级;“description”表示项目描述;“owner.login”表示项目所有者的登录名。

2.通过requests调用

#调用Web API
import requests
from requests.models import Response
url="https://api.github.com/search/repositories?q=language:python&sort=stars"
headers = {"Accept": "application/vnd.github.v3+json"}
#返回一个的对象
response=requests.get(url,headers=headers)
#状态码
status_code=response.status_code
if 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 API
import requests
import 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"}
#返回一个的对象
response=requests.get(url,headers=headers)
#状态码
status_code=response.status_code
if 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"{repo_name}"
        repo_links.append(repo_link)
        stars.append(star)
        hover_text = f"{owner}
{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项目。

相关文章

C# 中调用 Python 代码的实现方式

一、引言在软件开发中,经常会遇到需要结合不同编程语言优势的场景。C# 和 Python 作为两种广泛应用的语言,各自在某些领域有着独特的优势。C# 以其高性能和强大的类型系统在企业级应用中占据重要地位...

PySpark源码解析,用Python调用高效Scala接口,搞定大规模数据分析

机器之心专栏作者:汇量科技-陈绪相较于Scala语言而言,Python具有其独有的优势及广泛应用性,因此Spark也推出了PySpark,在框架上提供了利用Python语言的接口,为数据科学家使用该框...

python调用热门的Kimi:利用 API 生成文本的强大工具

代码概述下面给定的 Python 代码展示了如何利用 Moonshot AI API 的 Kimi 模型生成文本。Kimi 是一个由 Moonshot AI 开发的多模态 AI 模型,擅长生成中文和英...

Python发送微信消息(文字、图片、文件)给指定好友和微信群

本示例是调用Windows API模拟发送,用Python调用win32api这个库来调用Windows API模拟人的手动操作来发送消息。在使用前,请将你微信的窗口设置为在最前面,这样就便于程序找到...

python之requests介绍和案例_python怎么安装requests库

requests功能: 用于发送 HTTP 请求,适合与 REST API 交互。实际案例:调用 API 获取数据: 从监控系统 API 获取服务器状态。import requestsdef get_...