how to implement catch all route in fast api?

Sometimes you would require to implement a catch all requests in your fastapi application. We can achieve it by using api_route method.

Catch all route

from fastapi import FastAPI, Request

app = FastAPI()

async def hello():
    return {"hello": "world"}

@app.api_route("/{path_name:path}", methods=["GET"])
async def catch_all(request: Request, path_name: str):
    return {"request_method": request.method, "path_name": path_name}

Run fastapi

uvicorn main:app --reload

Route matching examples

/hello -> hello()
/   -> catch_all()
/test  -> catch_all()
/hello/test   -> catch_all()