API_调用

概述

应用程序编程接口(Application Programming Interface, API),定义了一套标准化的接口规范,即调用方按照约定提交请求(输入参数),服务方按照约定返回结果(输出响应),双方据此协作。

类比

银行取钱:去银行不用进金库数钱,去窗口递单子就行。窗口就是接口,银行内部怎么记账、怎么管钱,不接触;只填单子(参数)、等回执(返回值)即可。

调用示例

通过微博 OAuth 2.0 授权码流程获取访问令牌,调用 users/show 接口查询用户账户信息。

一、登录微博账户

​ https://open.weibo.com/

二、进行必要认证

​ 开发者认证 ➡️ 创建应用

三、运行示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import requests
from datetime import datetime

APP_KEY = "WeiBo_APP_KEY" # 换成自己的APP_KEY
APP_SECRET = "WeiBo_APP_SECRET" # 换成自己的APP_SECRET
REDIRECT = "https://api.weibo.com/oauth2/default.html" # 需要和控制台【接口管理】➡️【授权机制】➡️【OAuth2.0 授权设置】➡️【授权回调页】的值保持一致

# 1. 浏览器打开授权链接,登录点"授权",把页面显示的 code 粘回来
auth_url = f"https://api.weibo.com/oauth2/authorize?client_id={APP_KEY}&response_type=code&redirect_uri={REDIRECT}"
print("浏览器打开并授权:\n" + auth_url)
code = input("粘贴 code:").strip()

# 2. code 换 access_token
token = requests.post("https://api.weibo.com/oauth2/access_token", data={
"client_id": APP_KEY, "client_secret": APP_SECRET, "grant_type": "authorization_code",
"redirect_uri": REDIRECT, "code": code,
}).json()
print(token)
access_token=token["access_token"]
uid=token["uid"]

# 3. 带 token 调 users/show 查用户信息
me = requests.get("https://api.weibo.com/2/users/show.json",
params={"access_token": access_token, "uid": uid}).json()
print("======我的微博账户======")
print(f"用户UID:{me["id"]}")
print(f"字符串型的用户UID:{me["idstr"]}")
print(f"用户昵称:{me["screen_name"]}")
print(f"友好显示名称:{me["name"]}")
print(f"用户所在省级ID:{me["province"]}")
print(f"用户所在城市ID:{me["city"]}")
print(f"用户所在地:{me["location"]}")
print(f"用户个人描述:{me["description"]}")
print(f"用户博客地址:{me["url"]}")
print(f"性别:{me["gender"]}")
print(f"粉丝数:{me["followers_count"]}")
print(f"关注数:{me["friends_count"]}")
print(f"微博数:{me["statuses_count"]}")
print(f"收藏数:{me["favourites_count"]}")
print(f"用户注册时间:{me["created_at"]}")
t = datetime.strptime(me["created_at"], "%a %b %d %H:%M:%S %z %Y")
print(f"用户注册时间:{t.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"用户的在线状态:{me["online_status"]}")

示例调用的API接口:https://open.weibo.com/wiki/2/users/show


API_调用
https://76-s.github.io/2026/10/11/API_调用/
作者
76
发布于
2026年10月11日
许可协议