python runtime_error ai_generated true

fastapi.exceptions.HTTPException: 404: Not Found

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-05-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

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

Workarounds

  1. 95% success 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% success 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'})

Dead Ends

Common approaches that don't work:

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

    Masks real errors and may cause unintended behavior.

  2. Assuming trailing slash mismatch 50% fail

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