Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

796
Vistas
Mypy + FastAPI response_model

I've been tasked with handling the update from Mypy 0.770 to 0.870 in our FastAPI project, and this has produced an error that I can't quite wrap my head around. My endpoint can return two different models based on some condition, and this was denoted as follows the endpont decorator:

@router.get("/", response_model=Union[Model1, Model2])

Mypy 0.870 now complains about this, stating that

Argument "response_model" to "get" of "APIRouter" has incompatible type "object"; expected "Optional[Type[Any]]"

Setting it to single types, such as Model1 or even str removes the error. Any however, does not work.

Now, looking into the get method, I see that the response_model argument is typed as Type[Any], which I assume must be a pointer.

How I can define non-simple return models for my API, and make Mypy happy?

edit: I tried to reproduce the problem in a smaller frame, but couldn't. The following code works fine:

from typing import Any, Type, Union


def test1(var, response_model: Type[Any]):
    print(f"Accepted Type[Any], {var}")

def test2(var, response_model: Union[dict, set]):
    print(f"Accepted Union, {var}")

def main():
    test1('test1', response_model=Union[dict, set])
    test2('test2', response_model=Union[dict, set])

if __name__ == '__main__':
    main()
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

This is a compatibility issue introduced in newer versions of mypy. There is an open issue on Github about this topic: https://github.com/tiangolo/fastapi/issues/2279

In the discussion they provide the following workarounds:

  • Using a different approach to create a type alias:

    NewModel = TypeVar('NewModel',Model1,Model2)

  • Creating a new Pydantic Model :

    class NewModel(BaseModel):
         __root__: Union[Model1, Model2]
    
over 4 years ago · Santiago Trujillo Denunciar

0

Type[] of something means a not instantiated class of this type, while Model1 here will mean an instance of a Model1 class or an instance of anything that inherits from Model1.

Nonetheless, the error message is enigmatic.

What python -v are you using? Typing is a new thing in a python world and things might change between python versions as well. If you bumped mypy version it might be good to upgrade python as well as they go together.

Also, what fastapi version are you using? I'd try bump it to the latest, 0.55.1, as well. Tiangolo himself wrote they have had a bug with typing

source

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda