python runtime_error ai_generated true

fastapi.exceptions.HTTPException: 404: 未找到

fastapi.exceptions.HTTPException: 404: Not Found

ID: python/fastapi-http-exception-404-not-found

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-05-20首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

请求的 URL 路径与 FastAPI 应用中定义的任何路由不匹配。

English

Requested URL path does not match any defined route in the FastAPI application.

generic

解决方案

  1. 95% 成功率 Check and correct the route definition
    @app.get('/items/{item_id}')
    async def read_item(item_id: int):
        return {'item_id': item_id}
    # Access /items/123, not /items/
  2. 90% 成功率 Add a custom 404 handler for better debugging
    @app.exception_handler(404)
    async def not_found_handler(request, exc):
        return JSONResponse(status_code=404, content={'message': 'Route not found'})

无效尝试

常见但无效的做法:

  1. Adding a catch-all route that returns 200 60% 失败

    Masks real errors and may cause unintended behavior.

  2. Assuming trailing slash mismatch 50% 失败

    FastAPI by default does not redirect, so /users and /users/ are different.