How to log request and response contents using their Pydantic models #11294
jiri-bajer
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Situation
My route handlers accept a single argument called
request
of typepydantic.BaseModel
like this:and I want to log the contents of the requests and responses using Pydantic's native support for
repr()
.Problem
The problem is that the obvious extension points do not see the deserialized Pydantic models:
I wanted to avoid the overhead of double de-serialization of the request and response just for the logging, so I had to hook between the automagic de-serialization of arguments for the API route handler and the handler itself. I wanted to avoid the need for decorating all my handlers by my custom decorator as it is repetitive boilerplate and easy to forget.
Solution
In the end I had to monkey-patch the
fastapi.routing.run_endpoint_function
by my wrapper that takes the route handler method's name fromdependant.call.__name__
, the de-serialized Pydantic model for request fromvalues.get("request", ...)
and the not-yet-serialized Pydantic model for the response from theawait original_run_endpoint_function(...)
.I wish there was an official hook that I could register via the FastAPI app's constructor, or at least if the
run_endpoint_function
was a method of a class I could inherit from and use instead of its parent.Example
Beta Was this translation helpful? Give feedback.
All reactions