Akash Pattnaik
Akash Pattnaik

Reputation: 103

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?

Upvotes: 4

Views: 6263

Answers (3)

Yagiz Degirmenci
Yagiz Degirmenci

Reputation: 20756

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):
    ...

Upvotes: 7

vasa.v03
vasa.v03

Reputation: 157

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

Upvotes: 0

Don Dilidili
Don Dilidili

Reputation: 31

I edited Yagiz's code to:

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

Upvotes: 3

Related Questions