简体   繁体   中英

Python / pydantic / FastAPI - describe this datastructure as a Schema Model?

Problem

I have a data structure of nested lists of Dicts that I am trying to build a response_model for in FastAPI using Pydantic models but it's proving so far impossible. As soon as I apply the response_model= directive the data returns empty from the API. If I remove the response_model= directive the same query to the API results in data returning just fine and has content.

The Data looks like the following:

[
    {
        'code': 'trabant',
        'description': 'East German Trabant',
        'listings': [
            {
                 id: 1000,
                 cat_no: "Trabi1",
                 descript: "Trabant Interior Mirror"
                 price: Decimal(16.95),
                 veh: 'trabant',
                 sec: 'interior'
             },
             {
                 id: 1001
                 cat_no: "Trabi2",
                 descript: "Trabant Interior Clock"
                 price: Decimal(56.95),
                 veh: 'trabant',
                 sec: 'interior'
             }
         ]
    },
    {
        'code': 'skoda',
        'description': 'Czech Skoda',
        'listings': [
            {
                  id: 2001,
                  cat_no: "Skoda5",
                  descript: "Front Grille",
                  price: Decimal(36.95),
                  veh: 'skoda',
                  sec: 'bodywork'
             },
             {
                  id: 2002
                  cat_no: "Skoda6",
                  descript: "Skoda Grille Badge - Front"
                  price: Decimal(16.95),
                  veh: 'skoda',
                  sec: 'bodywork'
             }
        ]
    }
]

Which when boiled down to it's structure looks like:

] # root list
    { #can be any vehicle in a list of 40+
        'code': #vehicle's db code
        'description': #vehicle's textual name>,
        'listings': [ #list of catalogue items for this vehicle
            {
                id: #db id,
                cat_no: #Customer SKU,
                descript: #Description of a part,
                price: #Decimal value for price, no evil floats here!,
                veh: #db code for vehicle,
                sec: #db code for section
            }
        ]
    }
]

I tried to describe it using these Pydantic models:

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

class CatListing(ORMBaseModel):
    id: int
    cat_no: str
    descript: str
    sec: str
    veh: str
    price: Decimal

class VehicleCatListings(ORMBaseModel):
    code: str
    description: str
    listings: List[ CatListing ]

class ListOfCatListings(ORMBaseModel):
    List[ VehicleCatListings ]

But when I use the following route:

@app.get("/api/cat_no/{ff_no}/listings", response_model=schema.ListOfCatListings)
def getListings(ff_no: str, db: Session = Depends(databases.getDb)):
    listings = crud.catalogue.getListings(db, ff_no) #db request that returns data output as shown above

    if listings is None:
        raise HTTPException(status_code=404, detail="FF No catalogue listings not found")
    
    return listings

I get a blank object {} in return as if the pydantic model is ignoring the data somehow. I am however finding it hard to debug.

NB: I don't work for a place that sells rare Eastern European Car parts, I just used these as an example ;)

Okay so after a lot of banging my head on a brick wall it turns out this is a very common problem and it's mentioned a few times on Stackoverflow already. The fault here is that:

class ListOfCatListings(ORMBaseModel):
    List[ VehicleCatListings ]

Should be:

class ListOfCatListings(ORMBaseModel):
    __root__: List[ VehicleCatListings ]

This achieves what I needed.

I hope this helps someone else out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM