From 65a9b03c57eac1fc86af40ca8627c9f137aa56ed Mon Sep 17 00:00:00 2001 From: g7azazlo Date: Wed, 3 Dec 2025 23:05:01 +0300 Subject: [PATCH] Enhance response model inference logic in APIRoute and utils - Updated the response model inference in APIRoute to check for return annotations before inferring the model from the endpoint's source code. - Added type ignore comments in utils for better type checking compatibility. - Specified the type of nodes_to_visit in the infer_response_model_from_ast function for improved clarity. --- fastapi/routing.py | 7 ++++--- fastapi/utils.py | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index 1b553e0c2..55aa7794b 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -549,9 +549,10 @@ class APIRoute(routing.Route): not lenient_issubclass(response_model, BaseModel) and not dataclasses.is_dataclass(response_model) ): - inferred = infer_response_model_from_ast(endpoint) - if inferred: - response_model = inferred + if return_annotation is not None: + inferred = infer_response_model_from_ast(endpoint) + if inferred: + response_model = inferred self.response_model = response_model self.summary = summary diff --git a/fastapi/utils.py b/fastapi/utils.py index 233bac748..9554ea97a 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -283,7 +283,7 @@ def _infer_type_from_ast( return List[Any] if first_type is not Any: - return List[first_type] + return List[first_type] # type: ignore return List[Any] if isinstance(node, ast.BinOp): @@ -316,7 +316,7 @@ def _infer_type_from_ast( else: from pydantic import create_model - return create_model(f"Model_{context_name}", **fields) + return create_model(f"Model_{context_name}", **fields) # type: ignore[call-overload] if isinstance(node, ast.Name): arg_name = node.id @@ -366,7 +366,7 @@ def infer_response_model_from_ast( return_stmt = None - nodes_to_visit = list(func_def.body) + nodes_to_visit: List[ast.AST] = list(func_def.body) while nodes_to_visit: node = nodes_to_visit.pop(0) @@ -436,6 +436,6 @@ def infer_response_model_from_ast( model_name = f"ResponseModel_{endpoint_function.__name__}" try: - return create_model(model_name, **fields) + return create_model(model_name, **fields) # type: ignore[call-overload,no-any-return] except Exception: return None