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

liftword3个月前 (02-09)技术文章32

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调用deepseek的API进行对话

import requests import json # DeepSeek 模型的 API 端点 API_URL = "https://api.deepseek.com/v1/chat/compl...

Python调用Docker API的使用方式_python控制docker

Docker是目前最流行的容器化技术之一,它提供了一种轻量级和快速的方式来构建、打包和部署应用程序。Python是一种非常流行的编程语言,可以与Docker API一起使用,以便更好地管理和定制Doc...

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

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

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

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

[Python] FastAPI基础:Query查询参数用法全面解析与实例

1. HTTP 请求格式在开始写 Restful API 前,先简单的了解一下常规 HTTP 请求的格式,以便后续遇到问题知道从哪里排查,各部分的含义。下面是一个常规的 POST 请求的例子,各部分含...

Python处理excel数据,原来这么简单,VBA要尴尬了

工作中经常会遇到一些每天都要进行的重复操作,没一点技术含量,做起来却费时费力,还时不时出点小错。为应对这种情况,有些人会用VBA进行处理。但编辑了VBA功能的文件通用性不好,遇到领导、同事的excel...