如何通过Python CLI在GitHub仓库创建带内容的文件,报Not Found错误如何解决
错误原因梳理
- 创建文件的请求URL拼接错误
你定义的url变量初始值是创建仓库的接口地址https://api.github.com/user/repos,后续拼接创建文件路径后实际请求地址变为https://api.github.com/user/repos/{USERNAME}/{repo_name}/contents/{file_name},和你注释里标注的正确地址格式不符,正确的创建文件接口前缀应为https://api.github.com/repos。 - 分支参数配置错误
GitHub 2020年之后新创建的仓库默认主分支为main,你代码里写死branch: "master"会找不到对应分支,除非你创建仓库时明确指定默认分支为master。 - committer参数格式错误
committer参数本身需要传JSON对象,你额外用json.dumps序列化会把它变成字符串,导致参数解析失败。 - 缺少仓库创建成功的状态校验
你没有判断创建仓库的请求是否真的成功,直接调用后续创建文件接口,也可能因为仓库创建失败导致后续接口404。
修复后代码示例
import requests import json from base64 import b64encode # 替换为自己的配置 USERNAME = "你的GitHub用户名" TOKEN = "你的GitHub个人访问令牌" def create_repo(repo_name, file_name, file_content): # 1. 创建仓库 create_repo_url = 'https://api.github.com/user/repos' headers = {"Accept": "application/vnd.github.v3+json"} create_repo_data = {'name': repo_name} r = requests.post(create_repo_url, auth=(USERNAME,TOKEN), headers=headers, data=json.dumps(create_repo_data)) # 校验仓库创建结果 if r.status_code not in (200, 201): print(f"仓库创建失败,状态码:{r.status_code},错误信息:{r.text}") return print("Repo created") # 2. 创建文件,修正接口地址 create_file_url = f"https://api.github.com/repos/{USERNAME}/{repo_name}/contents/{file_name}" create_file_data = { "branch": "main", # 改为默认的main分支,如需用master可创建仓库时指定默认分支 'message': 'Initial commit', "path": file_name, 'content': b64encode(file_content.encode('utf-8')).decode('utf-8'), "committer": {"name": USERNAME, "email": "你的邮箱地址"}, # 去掉多余的json.dumps } response = requests.put(create_file_url, auth=(USERNAME,TOKEN), headers=headers, data=json.dumps(create_file_data)) if response.status_code in (200, 201): print("文件创建成功") else: print(f"文件创建失败,状态码:{response.status_code},错误信息:{response.text}")
通用排查步骤
- 打印实际请求的URL和状态码,和官方接口文档的格式做比对,确认路径、参数拼写正确
- 确认个人访问令牌(PAT)的权限范围包含
repo权限,GitHub为了隐私对无权限的私有资源统一返回404而非403 - 如果确实需要使用
master作为默认分支,可以在创建仓库的请求参数里添加default_branch: "master"指定
内容的提问来源于stack exchange,提问作者Jeeva
相关产品推荐
相关产品推荐

