[BUG] OpenAPI schema generation sometimes fails
See original GitHub issueDescribe the bug FastAPI version 0.30.0 Pydantic version 0.28
I recently upgraded to these versions, and the server is now (sometimes) hitting a ValidationError while trying to generate the OpenAPI spec (rendering the swagger docs broken).
I haven’t yet been able to produce a reproducible example (I think because the behavior is non-deterministic and is more likely to occur when there are many models present), but I dug into it a little and I think I have pinpointed the source of the problem: fastapi.utils.get_model_definitions
is occasionally returning some of its values as None
. (Strangely, this is non-deterministic; on each refresh of the docs page, a different subset of the keys have value None
; I’m guessing this has to do with the fact that the relevant function iterates over a set, in a non-deterministic order.)
If I comment the following line, all the issues go away:
def get_model_definitions(
*, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str]
) -> Dict[str, Any]:
definitions: Dict[str, Dict] = {}
for model in flat_models:
m_schema, m_definitions = model_process_schema(
model, model_name_map=model_name_map, ref_prefix=REF_PREFIX
)
# definitions.update(m_definitions) # THIS LINE COMMENTED
model_name = model_name_map[model]
definitions[model_name] = m_schema
return definitions
(I am confident this is not introducing other problems, at least for my entire app, because with this change I am able to use the openapi.json to generate precisely the same openapi client I was generating before I upgraded.)
I dug into the model_process_schema
function to see how m_definitions
was getting None
as a value in some cases, and I believe this is coming from pydantic.schema.field_type_schema
or pydantic.schema.field_singleton_schema
(and probably the singleton one; that’s the only place I saw None
ever being set as a value).
It looks like None
only gets set if the field is not a subclass of BaseModel, but I can confirm that all of the models involved are subclasses of BaseModel. (Besides, if this were the problem, I wouldn’t expect commenting the above mentioned line to fix the problem).
If I figure out more I’ll update this issue, but any guesses about what’s going wrong would be appreciated!
(This problem doesn’t seem to have had any effect on the handling of any requests besides the one for generating the OpenAPI spec.)
Environment:
- OS: Ubuntu
- FastAPI version: 0.30.0
- Pydantic version: 0.28
- Python version: 3.7.3
Issue Analytics
- State:
- Created 4 years ago
- Comments:16 (9 by maintainers)
Top GitHub Comments
Thanks everyone!
The latest version of FastAPI,
0.33.0
, includes Pydantic0.30.0
. That should fix these problems.Could you please update and check it with your specific cases? ✔️ 🚀
Also for me. Thanks