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

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

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项目。

相关文章

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

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

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

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

【Python机器学习系列】基于Flask来构建API调用机器学习模型服务

这是我的第364篇原创文章。一、引言我们知道机器学习的模型大多是使用python或者是R语言来写的,但是使用这些模型的软件工程师可能用的完全不是这些语言(机器学习模型有时只是一个软件中的一小部分,比如...

Python 集成 DeepSeek 示例_python 集成开发工具

DeepSeek 简介DeepSeek 由知名量化资管巨头幻言方量化创立于2023年7月17日,全称杭州深度求索人工智能基础技术研究有限公司。长久以来专注于开发先进的大语言模型(LLM)和相关技术。D...

使用Python调用ChatGPT API_python调用api函数

当前ChatGPT使用gpt-3.5和gpt-4等语言大模型,提供了强大的文本交互功能。用户也可以使用gpt-3.5或gpt-4提供的API接口构建自己的应用。本文简单的介绍一下使用Python调用C...