pythonfastapipydanticpyrightsqlmodel

VSCode Pylance Errors on FastAPI Response Type that Converts


I'm using VSCode and the default Python Language Support extension from MS, whcih lints with Pylance. I have a Python 3.12 FastAPI project which uses type annotations to indicate which models should be returned as responses from the handlers using the pattern suggested by the FastAPI docs (https://fastapi.tiangolo.com/tutorial/response-model/#return-type-and-data-filtering). There are no errors when the code is run and the app works correctly, returning the correct results in the correct models. However, I get Pylance linting errors that my function return types are not compatible with my returns.

Here are my FastAPI SQLModel/Pydantic models:

class PetBase(SQLModel):
    name: str

class Pet(PetBase, table=True):
    id: str

class PetOutgoing(PetBase):
    id: str

Here's my handler:

@router.get("/{pet_id}")
def retrieve_one(pet_id: str) -> PetOutgoing:
    pet: Pet = get_pet_by_id(pet_id)
    return pet

This endpoint returns the PetOutgoing model. FastAPI converts it on the fly. But here's the Pylance linting error I get.

Expression of type "Pet" is incompatible with return type "PetOutgoing"
  "Pet" is incompatible with "PetOutgoing" PylancereportReturnType
(variable) pet: Pet

What am I doing wrong?


Solution

  • The answer is to type hint the handler function with the type the function returns and add the outgoing model you want to the handler decorator, using the response_model parameter.

    @router.get("/{pet_id}", response_model=PetOutgoing)
    def retrieve_one(pet_id: str) -> Pet:
        pet: Pet = get_pet_by_id(pet_id)
        return pet
    

    This lints correctly and returns the correct model.
    See docs: https://fastapi.tiangolo.com/tutorial/response-model/