Suresh Kumar

how to implement catch all route in fast api?

Suresh Kumar's photo
Suresh Kumar

Published on Oct 11, 2021

1 min read

Subscribe to my newsletter and never miss my upcoming articles

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


Share this