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

使用Python requests.post创建GitHub仓库时出现JSON解析错误

问题原因与解决办法

错误根源

你碰到的400错误(JSON解析失败),核心问题出在请求体的格式不匹配:
当你用requests.post的data参数传入字典时,requests默认会把它编码成application/x-www-form-urlencoded(表单格式),但GitHub API明确要求请求体是application/json格式的JSON字符串。这就导致GitHub服务器无法解析你的请求内容,所以返回了"Problems parsing JSON"的错误。

而curl能成功,是因为它默认(或你隐式指定了)发送的是符合要求的JSON格式请求体,和API的预期匹配。


解决办法

有两种简单的修改方式,任选其一即可:

方法1:用json参数替代data参数

requests库提供了json参数,会自动把字典转换成JSON字符串,同时自动设置Content-Type: application/json请求头,完美适配GitHub API的要求:

import requests
import json

access_token = "..."

def create_repository():
    response = requests.post(
        url=f"https://api.github.com/user/repos",
        headers={
            "Authorization":f"token {access_token}",
            "Accept": "application/vnd.github.v3+json"
        },
        # 将data替换为json参数
        json={"name":"simp2","private":False}
    )
    # 注意:创建仓库成功的状态码是201,不是200
    if response.status_code == 201:
        # 直接用response.json()解析返回结果,更便捷
        out = response.json()
        with open("out.json","w") as file:
            json.dump(out,file)
    else:
        print(response.status_code)
        print(response.text)

if __name__ == '__main__':
    create_repository()

方法2:手动转换JSON并设置请求头

如果你坚持要用data参数,可以手动用json.dumps()把字典转成JSON字符串,同时在headers里添加Content-Type: application/json:

import requests
import json

access_token = "..."

def create_repository():
    response = requests.post(
        url=f"https://api.github.com/user/repos",
        headers={
            "Authorization":f"token {access_token}",
            "Accept": "application/vnd.github.v3+json",
            # 新增Content-Type头,指定JSON格式
            "Content-Type": "application/json"
        },
        # 将字典转为JSON字符串传入data
        data=json.dumps({"name":"simp2","private":False})
    )
    if response.status_code == 201:
        out = response.json()
        with open("out.json","w") as file:
            json.dump(out,file)
    else:
        print(response.status_code)
        print(response.text)

if __name__ == '__main__':
    create_repository()

替代方案:使用PyGitHub库

如果不想手动处理HTTP请求的细节,可以用官方推荐的PyGitHub库,它封装了GitHub API的所有操作,代码会更简洁易读:

  1. 先安装库:
pip install pygithub
  1. 改写代码:
from github import Github

access_token = "..."

def create_repository():
    g = Github(access_token)
    user = g.get_user()
    try:
        repo = user.create_repo(name="simp2", private=False)
        # 保存仓库信息到文件
        import json
        with open("out.json","w") as file:
            json.dump({"name": repo.name, "html_url": repo.html_url}, file)
    except Exception as e:
        print(f"Error: {e}")

if __name__ == '__main__':
    create_repository()

这个库会自动处理请求格式、认证、错误捕获等细节,大幅减少手动编写HTTP请求的麻烦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:12:37