79676189

Date: 2025-06-23 12:43:57
Score: 1.5
Natty:
Report link

1. Did you actually decorate your route?

If you call app.get('/') without the @ decorator, FastAPI registers nothing. That means no route exists, so every request returns 404. This is the most common mistake:

# ❌ WRONG:
app.get('/')
def root():
    return {'msg': 'hello'}

# ✅ CORRECT:
@app.get('/')
def root():
    return {'msg': 'hello'}

2. Are you mounting routers or static apps correctly?

Often, your script will include routers or static mounts, but if the decorators aren’t applied properly, nothing gets registered. Here's a robust minimal example that you can copy into main.py and test:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/")
def hello():
    return {"hello": "world"}

@app.get("/abc")
def abc():
    return {"hello": "abc"}

Run it with:

uvicorn main:app --reload --host 0.0.0.0 --port 8000

Navigate to GET /, /abc, or /static/…—they should all work. If GET / still returns 404, re‑check your decorators.


3. Got a router prefix? Use the right path!

If you're including an APIRouter:

from fastapi import FastAPI, APIRouter

router = APIRouter(prefix="/items")

@router.get("/")
async def list_items():
    return ["a", "b"]

app = FastAPI()
app.include_router(router)

Your route is reachable at /items/, not /. So GET / → 404, GET /items/ → 200 with ["a","b"]. This is another source of “missing” routes.


4. Behind a reverse proxy? You might need root_path

If you're hosting behind a proxy (Nginx, Traefik, API Gateway, etc.) that strips or adds leading path segments, FastAPI’s OpenAPI UI /docs or even paths can break. Use the root_path feature:

This ensures both routing and docs work with the prefixed path.


5. Template for debugging

  1. Check you’re in the correct working directory (project root).

  2. Temporarily hardcode a simple root route:

    @app.get("/")
    def debug_root():
        return {"ok": True}
    
  3. Print the registered routes to verify:

    for r in app.routes:
        print(r.path, r.methods)
    

    Then run your service and inspect output to know exactly what endpoints exist.

Reasons:
  • RegEx Blacklisted phrase (1.5): fix?
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Prashant Choudhary