Skip to content

Support for MongoDB ObjectID in Pydantic ModelsΒ #133

@SkandaPrasad-S

Description

@SkandaPrasad-S

Initial Checks

  • I have searched Google & GitHub for similar requests and couldn't find anything
  • I have read and followed the docs and still think this feature is missing

Description

I am using Pydantic in conjunction with FastAPI and MongoDB, and I would like to request support for MongoDB ObjectID as one of the field types in Pydantic models.

Background:
Currently, Pydantic supports various field types, but there isn't a specific type for MongoDB ObjectID. MongoDB ObjectID is commonly used in FastAPI applications with MongoDB databases, and having native support for it in Pydantic would greatly enhance the validation capabilities.

Suggested Solution:
I propose adding a dedicated type for MongoDB ObjectID in Pydantic, similar to how EmailStr and other specialized types work. This could be achieved by introducing a type like MongoObjectId or extending the existing PyObjectId to handle MongoDB ObjectID validation seamlessly.

from pydantic import BaseModel
from pydantic_mongo import MongoObjectId

class MyClass(BaseModel):
    my_id: MongoObjectId

Additional Context:
MongoDB ObjectID validation is a common requirement in FastAPI applications, especially when dealing with MongoDB databases. Adding native support in Pydantic would simplify the code and improve the developer experience.

I would love it if we could do something like the below with FASTAPI that works seamlessly in generating the OpenAPI schema as well.
This is because all the workarounds for the above issue face OpenAPI schema issues.

@router.get("/get_id/{my_id}")
def get_goal_by_id(my_class: MyClass ):
    return my_class.my_id

Affected Components

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions