1

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)

enter image description here

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Eric.P
  • 67
  • 7
  • 1
    Is there a [question](https://stackoverflow.com/help/minimal-reproducible-example) here? A diagnostic error message to explain? – J_H Dec 16 '22 at 06:28
  • A 422 always comes with an explanation where the issues lies, what is the response your getting? – JarroVGIT Dec 16 '22 at 06:37
  • @JarroVGIT { "detail": [ { "loc": [ "body" ], "msg": "value is not a valid dict", "type": "type_error.dict" } ] } – Eric.P Dec 16 '22 at 06:46
  • IT is expecting a body like `{“coin”:[your array here]}` – JarroVGIT Dec 16 '22 at 06:52
  • Does this answer your question? [How do I send list of dictionary as Body parameter in FastAPI?](https://stackoverflow.com/questions/63110848/how-do-i-send-list-of-dictionary-as-body-parameter-in-fastapi) – Chris Dec 19 '22 at 06:54

2 Answers2

2

the Post request expects a body like this:

    {"data" : [
      "date": "2022-12-13",
      "symbol": "nsht",
      "price": "45.12"]
    }
notrayen
  • 131
  • 2
0

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)
Eric.P
  • 67
  • 7