Home > OS >  FastAPI response model list of json objects
FastAPI response model list of json objects

Time:06-23

I am using MongoDB and FastAPI but can't get my response for more than one document to render without an error, it's a lack of understanding on my part but no matter what I read, I can't seem to get to the bottom of it?

models.py

from pydantic import BaseModel, constr, Field

    #Class for a user
    class User(BaseModel):
       username: constr(to_lower=True)
       _id: str = Field(..., alias='id')
       name: str
       isActive : bool
       weekPlan : str

    #Example to provide on FastAPI Docs
    class Config:

        allow_population_by_field_name = True
        orm_mode = True
        schema_extra = {

        "example": {
            "name": "John Smith",
            "username": "[email protected]",
            "isActive": "true",
            "weekPlan": "1234567",
        }
    }

routes.py

from fastapi import APIRouter, HTTPException, status, Response

from models.user import User
from config.db import dbusers

user = APIRouter()    

@user.get('/users', tags=["users"], response_model=list[User])
         async def find_all_users(response: Response):
         # Content-Range needed for react-admin
         response.headers['Content-Range'] = '4'
         response.headers['Access-Control-Expose-Headers'] = 'content-range'
         users = (dbusers.find())
         return users

mongodb json data

{
    "_id" : ObjectId("62b325f65402e5ceea8a4b6f")
  },
  "name": "John Smith",
  "isActive": true,
  "weekPlan": "1234567"
   },
   {
    "_id" : ObjectId("62b325f65402e5ceea9a3d4c"),
    "username" : "[email protected]",
    "name" : "John Smith",
    "isActive" : true,
    "weekPlan" : "1234567"
    }

This is the error I get:

    await self.app(scope, receive, send)
  File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\starlette\routing.py", line 670, in __call__
    await route.handle(scope, receive, send)
  File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\starlette\routing.py", line 266, in handle
    await self.app(scope, receive, send)
  File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\starlette\routing.py", line 65, in app
    response = await func(request)
  File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\fastapi\routing.py", line 235, in app
    response_data = await serialize_response(
  File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\fastapi\routing.py", line 138, in serialize_response
    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for User
response
  value is not a valid list (type=type_error.list)

Can anyone help?

CodePudding user response:

pymongo's find method returns a Cursor - you have to exhaust this iterator first, since Pydantic doesn't have any idea what it should do with a Cursor object.

You can do this by giving it as an argument to list:

@user.get('/users', tags=["users"], response_model=List[User])
async def find_all_users(response: Response):
    ...
    return list(dbusers.find())
  • Related