4

This is my schema file

from pydantic import BaseModel
from typing import Optional


class HolidaySchema(BaseModel):
    year: int
    month: int
    country: str
    language: str


class HolidayDateSchema(BaseModel):
    name: str
    date: str
    holidays: HolidaySchema | None = None

    class Config:
        orm_mode = True

and this is the router that I have

@router.get("/holidays/",response_model = List[HolidayDateSchema])

The response I want to get is

[
    {
        "date": "2021-08-14",
        "name": "Independence Day",
        "holidays": { "year": 2022, "month":5, "country":"pk", "language":"en"},
        "id": 13
    },
]

Right now it doesn't support the pydantic schema with response model, I don't know why and it gives error pydantic.error_wrappers.ValidationError: 2 validation errors for HolidayDateSchema and value is not a valid dict

It would be great if anyone can specify the best to get deeply nested JSON objects with response_model.

  • Error comes more probably from the definition of your function than from the router annotation. Please share some code allowing to reproduce the error. Also, note that `{ year: 2022, month:5, country:pk, language:en}` is not a valid JSON: strings must be quoted, like `{"year": 2022, "month": 5, "country": "pk", "language": "en"}` – ye olde noobe Sep 08 '22 at 08:18
  • It works fine, I do not get any error at all. There is mistake if you are returning exactly same as what you have given as example response. The dict keys `year`, `month`, etc are not enclosed within quotes. – Irfanuddin Sep 08 '22 at 08:21
  • I'm not returning this at all, I'm returning sqlalchemy query object which would already be in the appropriate format. – Raheel Siddiqui Sep 08 '22 at 08:28
  • 2
    `HolidaySchema` isn't configured with `orm_mode = True`. You need this for _all_ the models that you want to automagically convert from SQLAlchemy model objects. You can [configure that setting on a common BaseModel and inherit from that instead](https://stackoverflow.com/questions/69504352/fastapi-get-request-results-in-typeerror-value-is-not-a-valid-dict) if you want the setting for all your models. – MatsLindh Sep 08 '22 at 09:40

1 Answers1

3

HolidaySchema isn't configured with orm_mode = True.

You need this for all the models that you want to automagically convert from SQLAlchemy model objects.

class HolidaySchema(BaseModel):
    year: int
    month: int
    country: str
    language: str

    class Config:
        orm_mode = True

You can configure that setting on a common BaseModel and inherit from that instead if you want the setting for all your models.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84