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

使用Ergast F1 API时遭遇JSONDecodeError,请求技术排查指导

解决Ergast F1 API调用的JSONDecodeError问题

错误核心原因

你遇到的requests.exceptions.JSONDecodeError是因为请求的API地址完全不符合Ergast F1 API的规范,导致服务器返回的不是合法JSON(大概率是HTML错误页面),无法被resp.json()解析。

关键问题:请求URL格式错误

Ergast F1 API是REST风格接口,赛季赛程的正确调用方式是将年份直接拼接在URL路径中,而非通过params传递参数。比如查询2021年赛程,正确的URL是:
https://ergast.com/api/f1/2021.json

你的代码仅请求了基础地址https://ergast.com/api/f1/,并错误使用params={"Race season": raceYear}传递参数,完全不符合API调用规则。

修复步骤与代码调整

  1. 修正API请求地址:将赛季年份拼接至基础URL后,添加.json后缀(Ergast默认返回XML,需明确指定JSON格式)
  2. 增加参数校验:确保表单提交的年份有效
  3. 添加响应状态码检查:提前排查API请求失败的情况
  4. 捕获解析异常:方便排查非JSON返回的问题

修改后的代码示例:

from flask import Flask, render_template, request, jsonify
import requests

api_base = "https://ergast.com/api/f1/"

app = Flask(__name__)

@app.route('/', methods=["GET", "POST"])
def home_route():
    return render_template('index.html')

@app.route('/season', methods=["GET", "POST"])
def show_season():
    raceYear = request.form.get("season_year")
    
    # 校验年份是否为有效数字
    if not raceYear or not raceYear.isdigit():
        return jsonify({"error": "请输入有效的数字年份"}), 400
    
    # 构造正确的API请求地址
    api_url = f"{api_base}{raceYear}.json"
    resp = requests.get(api_url)
    
    # 检查API响应状态
    if resp.status_code != 200:
        return jsonify({"error": f"API请求失败,状态码: {resp.status_code}"}), resp.status_code
    
    try:
        results = resp.json()
        return jsonify(results)
    except requests.exceptions.JSONDecodeError:
        # 打印返回内容用于排查问题
        print("API返回非JSON内容:", resp.text)
        return jsonify({"error": "API返回格式无效"}), 500

额外排查方向

  • 先在浏览器中手动访问https://ergast.com/api/f1/2021.json,确认能拿到正常的JSON响应
  • 打印raceYear的值,检查表单提交的年份是否正确传递到后端
  • 确认代码已正确导入requests和Flask相关模块
  • 如果仍有问题,打印resp.text查看服务器返回的具体内容,定位错误原因

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:15:08