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

FastAPI调用天气API时返回Not Found错误,请求排查问题

FastAPI天气接口报错问题排查与修复

用户尝试用FastAPI开发天气查询接口,启动服务器后访问返回{"detail":"Not Found"},无法获取OpenWeatherMap的天气数据,相关代码与操作如下:

原代码

from fastapi import FastAPI, requests
from pydantic import BaseModel

app = FastAPI()

class Data(BaseModel):
    user: str

@app.get("/task1")
def task1(re1: Data):
    re1= requests.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appictualappidd=a')
    z = re1.txt
    return z

启动命令

uvicorn task:app --host "0.0.0.0" --port 8000 --reload

访问后输出

{"detail":"Not Found"}

错误原因分析

  • GET请求无法接收Pydantic模型作为参数:FastAPI中@app.get接口的Pydantic模型参数会被默认解析为请求体,但GET请求不支持请求体,导致路由匹配失败,返回404错误。
  • requests库导入错误:错误地从fastapi导入requests,正确做法是单独导入第三方库import requests。
  • API参数错误:OpenWeatherMap的API密钥参数应为appid,而非appictualappidd,且示例中的密钥a无效,需替换为个人有效密钥。
  • 响应内容获取错误:获取响应文本需用response.text,代码中re1.txt会触发属性不存在的错误。

修正后的代码

from fastapi import FastAPI
import requests

app = FastAPI()

# 使用查询参数接收城市、国家,GET请求更符合规范
@app.get("/task1")
def task1(city: str = "London", country: str = "uk"):
    # 替换为你的OpenWeatherMap有效API密钥
    api_key = "your_valid_api_key"
    api_url = f"http://api.openweathermap.org/data/2.5/weather?q={city},{country}&appid={api_key}"
    response = requests.get(api_url)
    # 直接返回API的JSON响应,或按需处理后返回
    return response.json()

正确访问方式

启动服务器后,在浏览器中访问默认地址:

http://localhost:8000/task1

也可通过查询参数指定城市:

http://localhost:8000/task1?city=Paris&country=fr

内容的提问来源于stack exchange,提问作者Muhammad Osama Shahzad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:20:29