g0di / fastapi-problem-details

Structure your FastAPI API error responses with consistent and machine readable format using the RFC 9457 "Problem Details for HTTP APIs" standard
MIT License
0 stars 0 forks source link

Add ability to indicates that some API routes raises one or several errors so it is automatically documented with correspond problem details #4

Open g0di opened 1 month ago

g0di commented 1 month ago

To avoid to have to manually register possible Problem Details response per API route, it could be interesting to provide a kind of mechanism for indicating that a route can raise some errors so when the openapi spec is generated, the route responses doc is filled with the problem details corresponding to the error raised.

There is two use cases.

First one is for custom exception


class UserNotFoundError(Exception):
    pass

@app.exception_handler(UserNotFoundError):
def handle_user_not_found_error(req, exc):
    return ProblemResponse(...)

@raises(UserNotFoundError)
@app.get("/users/{user_id}"):
def get_user(user_id: str) -> Any:
    ...

The main difficulty here is to be able to do the mapping because the ProblemResponse is built when the error is handled, so the information about the schema of the problem is obtained at runtime.

Second one for regular ProblemException

class UserNotFoundError(ProblemException):
    def __init__(self):
        super().__init__(status=404)

@raises(UserNotFoundError)
@app.get("/users/{user_id}"):
def get_user(user_id: str) -> Any:
    ...

Here it might be easier if we can somehow pass the Problem schema directly in the UserNotFoundError