How to set "/*" path to capture all routes in FastAPI?

Viewed 1551

Like in ExpressJS, app.get("/*") works for all routes.

My code -

from typing import Optional
from fastapi import FastAPI

app = FastAPI()


@app.get('/*')
def user_lost():
    return "Sorry You Are Lost !"

I tried it but the webpage result shows {"detail":"Not Found"}
How can I do the same in FastApi?

3 Answers

You can use /{full_path} to capture all routes in one path (See documentation).

@app.route("/{full_path:path}")
async def capture_routes(request: Request, full_path: str):
    ...

I edited Yagiz's code to:

@app.get("/{full_path:path}")
async def capture_routes(request: Request, full_path: str):
   ...
Related