how to create Pydantic model with Binary field used to save/retrieve files in MongoDB

48 Views Asked by At

I am implementing a FastAPI server that allows to upload/download files in MongoDB together with other fields.

My Pydantic model is (simplified):

PyObjectId = Annotated[str, BeforeValidator(str)]

class Form(BaseModel):
    id: Optional[PyObjectId] = Field(alias="_id", default=None)
    is_attachment: bool = Field(...)
    content_type: str = Field(...)
    file_name: str = Field(...)
    file_data: Binary = Field(...)
    model_config = ConfigDict(
        arbitrary_types_allowed=True,
        json_schema_extra={
            "example": {
                "file_name": "file.pdf",
                "is_attachment": True,
                "content_type": "application/pdf",
                "file_data": "JVBERi0xLjQK...",
            }
        },
    )

I have a simple GET returning a list of the above model objects:

class FormCollection(BaseModel):
    forms: List[Form]


@app.get("/forms/", response_description="List all forms", response_model=FormCollection, response_model_by_alias=False,)
async def list_forms():
    return FormCollection(forms=await forms_collection.find().to_list(1000))

I run the server, but when opening the OpenAPI (Swagger) page, I get:

pydantic.errors.PydanticInvalidForJsonSchema: Cannot generate a JsonSchema for core_schema.IsInstanceSchema (<class 'bson.binary.Binary'>)

Pydantic seems not to like the 'file_data' Binary field. Question is, how to define a bson.binary.Binary field in Pydantic.

1

There are 1 best solutions below

0
F. F. On

Found the answer, I need to use the 'bytes' Pydantic data type.