Replies: 1 comment
-
In case this is seen as a viable proposal, I have opened a (quite minimalistic) PR offering the implementation: #10638 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
First Check
Commit to Help
Example Code
Description
TL;DR: Is there anything that speaks against allowing the application's
openapi
method to beasync
?The Problem
The documentation explains how to override the
openapi
method of the application instance to customize the OpenAPI schema generation.Now I think that a very prevalent reason to do so is the need to incorporate settings of some kind into the schema. These settings may come from something like environment variables that are processed by Pydantic
BaseSettings
where they're read before app initialization. But they may also very well be dynamic application settings that can change at runtime, e.g. when an admin updates the application title via some administration UI.Such changes have to be stored and persisted somewhere, most probably a database or something like Redis (or both, for that matter). Now accessing such settings often involves
async
calls to e.g. the database (see my code example). But this would – of course – fail with aTypeError: Object of type coroutine is not JSON serializable
.The Proposal
So to allow for
async
logic to be used in the generation of the OpenAPI schema withinFastAPI.openapi
, the internal call (return JSONResponse(self.openapi())
inapplications.py
) would be required to handle asyncopenapi()
implementations.As the call to
self.openapi()
happens in an async context anyway, the changes needed would be minimal and only introduce one conditional that's run once in the application setup routine (of course this last part largely depends on how the customopenapi
method is implemented, there might be good reasons to not cache the schema and fetch fresh settings data from the DB).Additional Considerations
This wouldn't even need a change of the documentation. It would simply make FastApi support async implementations of
openapi
in case people need it (as you might have guessed, I am one of those people).Operating System
Linux
Operating System Details
No response
FastAPI Version
0.104.1
Pydantic Version
2.4.2
Python Version
3.10.12
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions