You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python requests调用GitHub API获取用户仓库接口遇问题

解决GitHub API仓库请求失败的问题

嘿,我来帮你搞定这个请求问题~你现在遇到的问题是因为用了URI模板语法(就是URL里带大括号的{user}和{?type,page,per_page,sort}),但requests库默认并不支持解析这种格式,所以服务器收到的是带有大括号的错误URL,自然没法正常响应。

给你两种可行的解决办法:

方法一:用requests标准参数传递方式(推荐)

这是requests最常用的写法,把路径里的动态参数(比如user)用字符串格式化替换,查询参数(type、page这些)单独放到params字典里,这样requests会自动帮你拼接成正确的URL:

import requests

# 替换成你的GitHub账号信息
your_username = "你的用户名"
your_password = "你的密码"  # 更推荐用个人访问令牌(PAT)替代密码

# 先把URL里的user占位符替换成实际用户名
base_url = f"https://api.github.com/users/{your_username}/repos"
# 定义查询参数,根据你的需求调整值
query_params = {
    "type": "all",  # 可选值:all、public、private、forks等
    "page": 1,
    "per_page": 30,  # GitHub默认最多30条,上限100
    "sort": "updated"  # 可选排序:created、updated、pushed、full_name
}

# 发送请求
response = requests.get(base_url, auth=(your_username, your_password), params=query_params)

# 验证请求结果
if response.status_code == 200:
    repo_list = response.json()
    print(f"成功获取到{len(repo_list)}个仓库")
else:
    print(f"请求出错啦!状态码:{response.status_code},错误详情:{response.text}")

方法二:使用URI模板解析库(可选)

如果你习惯用URI模板语法,可以安装uritemplate库来解析模板,再传给requests:

import requests
from uritemplate import expand

template_url = "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}"
# 解析模板,替换参数
full_url = expand(template_url, {
    "user": "你的用户名",
    "type": "all",
    "page": 1,
    "per_page": 30,
    "sort": "updated"
})

response = requests.get(full_url, auth=("你的用户名", "你的密码"))

不过更推荐第一种方法,因为它是requests的标准用法,不需要额外安装依赖,代码也更清晰。另外提醒下:现在GitHub推荐用**个人访问令牌(PAT)**代替密码进行认证,安全性更高,你可以在GitHub设置里生成一个有repo权限的令牌,然后把auth里的密码换成这个令牌就行~

内容的提问来源于stack exchange,提问作者Sean_Boothby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:41:50