1

I have an API endpoint at /devices/{id}. When I call the API without an id, I get 404 errors with the vague message "Not found" in the body.

Is there any way to customize the content / message of the 404 error in FastAPI when a parameter (in my case id) is not found/missing in the called URL?

@app.get("/devices/{id}")
async def get_cellular_data_for_device_id(request: fastapi.Request, id: str):
     print("doing something")

404 Error content:

 {
    "detail": "Not Found"
 }
Chris
  • 18,724
  • 6
  • 46
  • 80
Cribber
  • 2,513
  • 2
  • 21
  • 60
  • Does this answer your question? [How to return a custom 404 Not Found page using FastAPI?](https://stackoverflow.com/questions/71800133/how-to-return-a-custom-404-not-found-page-using-fastapi) – Chris Feb 22 '23 at 12:42
  • Related answers can also be found [here](https://stackoverflow.com/a/70954531/17865804), as well as [here](https://stackoverflow.com/a/73283272/17865804) and [here](https://stackoverflow.com/a/71682274/17865804) – Chris Feb 22 '23 at 12:43
  • The links point to customizing 404 errors for the entire API, all endpoints, which I do not want to do. The supplied answers are the correct solution to my specific problem. – Cribber Feb 22 '23 at 14:52

2 Answers2

1

You should be able to determine if the id parameter was given, then raise a custom error if not.

@app.get("/devices")
@app.get("/devices/{id}")
async def get_cellular_data_for_device_id(request: fastapi.Request, id: Optional[str] = None):
    if id is None:
        raise HTTPException(status_code=404, detail='Custom Error')

    print("doing something")

Note that I'm going off my flask knowledge here, so there's a chance this won't work exactly out of the box as I've written it.

Peter
  • 3,186
  • 3
  • 26
  • 59
0

One option other than a custom error handler is just simply adding another @app.get("/devices") decorator on it, which will return a required field missing. This will cause it to return 422.

@app.get("/devices")
@app.get("/devices/{id}")
async def get_cellular_data_for_device_id(request: fastapi.Request, id: str):
     print("doing something")

response when calling devices is

{"detail": [{"loc": ["query", "id"], "msg": "field required", "type": "value_error.missing"}]}

arrmansa
  • 518
  • 10