Bootstrap FreeKB - FastAPI - Catch All
FastAPI - Catch All

Updated:   |  FastAPI articles

Here is an example of how you could create a catch all route so that all requests return 200 OK and to then return some friendly message if an invalid endpoint is requested.

from fastapi import FastAPI


valid_endpoints = ['/api/v1/lab', '/api/v1/dev', '/api/v1/stage', '/api/v1/prod']

app = FastAPI()

@app.get("/{rest_of_path:path}")
async def catch_all(rest_of_path: str):

  if f"/{rest_of_path}" not in valid_endpoints:
    message = f"/{rest_of_path} is NOT a valid endpoint. The valid endpoints are: {valid_endpoints}"
  else:
    message = f"/{rest_of_path} is a valid endpoint. The valid endpoints are: {valid_endpoints}"

  return {"message": message}



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 02a931 in the box below so that we can be sure you are a human.