schedule · 1 min read

how to implement catch all route in fast api?

link
Part of series
Today I Learned (TIL)

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()


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

Credits: https://github.com/tiangolo/fastapi/issues/819#issuecomment-569222914

link
Part of series
Today I Learned (TIL)