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)