Search code examples
pythonmongodbpymongofastapipydantic

Why my code be returning this : Input should be a valid list. If I be setting the validation?


main.py:

from typing import List
import json

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from config import collection
from model import Usuario

app = FastAPI()

app.add_middleware( #parametros pra liberar a conexao
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def read_users() -> List[Usuario]:
    itens = [Usuario(**usuario) for usuario in collection.find()]
    print(itens)
    return itens

config.py:

from pymongo import MongoClient

client = MongoClient("mongodb://allanvargensDB:vargens@localhost:27017/")

db = client['portfolio']
collection = db['usuario']

model.py:

from typing import List

from bson import ObjectId
from pydantic import BaseModel,  Field, BaseConfig


class OID(str):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        try:
            return ObjectId(str(v))
        except Exception:
            raise ValueError("not a valid ObjectId")


class MyBaseModel(BaseModel):
    def __hash__(self):
        return hash((type(self),) + tuple(self.__dict__.values()))


class Projects(MyBaseModel):
    id_project: ObjectId = Field(description='project id', alias='project_id')
    title: str
    imagePath: str
    url: str = ''

    class Config(BaseConfig):
        arbitrary_types_allowed = True
        json_encoders = {
            ObjectId: lambda oid: str(oid)
        }


class Usuario(BaseModel):
    id_user: ObjectId = Field(description='user id', alias='user_id')
    name: str
    login: str
    password: str
    projects: List[Projects] = Field(alias='projects')

    class Config(BaseConfig):
        arbitrary_types_allowed = True
        json_encoders = {
            ObjectId: lambda oid: str(oid)
        }

message erro:

pydantic_core._pydantic_core.ValidationError: 1 validation error for Usuario projects
   Input should be a valid list [type=list_type, input_value={'project_id': ObjectId('..., 'url': 'teste.com.br'}, input_type=dict]
     For further information visit https://errors.pydantic.dev/2.5/v/list_type

I am new with python. Is there any better way to do a router that return all users of my mongo db?

my database info:

{
    _id: ObjectId('656e6c2fc0feaabbfb87d63e'),
    name: 'Allan Vargens',
    login: 'allanvargens',
    password: 'password',
    projects: {
        project_id: ObjectId('656e6d7ec0feaabbfb87d640'),
        titulo: 'teste',
        imageUrl: '',
        url: 'teste.com.br'
    },
    user_id: ObjectId('656e6c2fc0feaabbfb87d63e')
}

Solution

  • Since your Usuario.projects is a list of Projects, you should wrap it in square brackets:

    {
        _id: ObjectId('656e6c2fc0feaabbfb87d63e'),
        name: 'Allan Vargens',
        login: 'allanvargens',
        password: 'password',
        projects: [
            {
                project_id: ObjectId('656e6d7ec0feaabbfb87d640'),
                titulo: 'teste',
                imageUrl: '',
                url: 'teste.com.br'
            },
        ],
        user_id: ObjectId('656e6c2fc0feaabbfb87d63e')
    }