简体   繁体   中英

How to Put list of object by FastAPI and Pydantic

I am trying to learn FastAPI and Pydantic to put a list of object into MongoDB, but I got an error saying 422 Unprocessable Entity . I understand the error message indicated the server understands the JSON format, but is unable to handle it. I tried to wrap it with another model, but it looks like it doesn't work.

Let's say I have a list of object as:

[
  {
    "date": "2022-12-13",
    "symbol": "nsht",
    "price": "45.12"
  },
  {
    "date": "2022-12-13",
    "symbol": "asdf",
    "price": "45.14442"
  }
]

And I want to add it to the database by following object model as:

class EODCoinModel(BaseModel):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    date: str = Field(...)
    symbol: str = Field(...)
    price: float = Field(...)
  
    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}
        schema_extra = {
            "example": {
                "date": "2022-12-13",
                "symbol": "AAPL",
                "price": "45.12"
            }
        }

class ItemList(BaseModel):
    data: List[EODCoinModel]

And PUT method as:

@app.post("/", response_description="Add new coin", response_model=ItemList)
async def create_coin(coin: ItemList = Body(...)):
    coin = jsonable_encoder(coin)
    print(coin)
    new_coin = await db["coin"].insert_one(coin)
    created_coin = await db["coin"].find_one({"_id": new_coin.inserted_id})
    return JSONResponse(status_code=status.HTTP_201_CREATED, content=created_coin)

在此处输入图像描述

the Post request expects a body like this:

    {"data" : [
      "date": "2022-12-13",
      "symbol": "nsht",
      "price": "45.12"]
    }

So then I ended up with not using Pydantic model validation. Just take the whole list and do inset_many.

@app.post("/", response_description="Add new coin")
async def create_coin(coin: List):
    coin = jsonable_encoder(coin)
    print(coin)
    new_ coin = await db["coin"].insert_many(coin)
    return JSONResponse(status_code=status.HTTP_201_CREATED)

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