简体   繁体   中英

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

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 ?

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

@app.route("/{path_name: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):
   ...

Best explained in https://sureshdsk.dev/how-to-implement-catch-all-route-in-fast-api

The only additional comment is;

if you want to mix catch-all and handle certain paths like /hello or /api.. make sure that catch all method definition is at the last.... order of route definitions matter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM