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

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

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...

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

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

使用python调用文心一言API,实现批量提问

在使用文心一言网页版时,一般都是输入一个提问,文心给出该提问的结果。但是,有时候我们需要批量向文心进行提问,而且这些提问的性质都是一样的,那么如何实现这个需求呢?一、提出问题例如:有一个表格,1000...

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

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

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

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

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

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