FastAPI – GET request results in typeerror (value is not a valid dict)

Pydantic 2 changed how models gets configured, so if you’re using the most recent version of Pydantic, see the section named Pydantic 2 below.

SQLAlchemy does not return a dictionary, which is what pydantic expects by default. You can configure your model to also support loading from standard orm parameters (i.e. attributes on the object instead of dictionary lookups):

class Userattribute(BaseModel):
    name: str
    value: str
    user_id: str
    id: str

    class Config:
        orm_mode = True

You can also attach a debugger right before the call to return to see what’s being returned.

Since this answer has become slightly popular, I’d like to also mention that you can make orm_mode = True the default for your schema classes by having a common parent class that inherits from BaseModel:

class OurBaseModel(BaseModel):
    class Config:
        orm_mode = True


class Userattribute(OurBaseModel):
    name: str
    value: str
    user_id: str
    id: str

This is useful if you want to support orm_mode for most of your classes (and for those where you don’t, inherit from the regular BaseModel).

Pydantic 2

Pydantic 2 has replaced the internal Config class with a model_config field:

from pydantic import ConfigDict

class OurBaseModel(BaseModel):
    model_config = ConfigDict(from_attributes=True)

This works in the same way as the old orm_mode.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)