-
Notifications
You must be signed in to change notification settings - Fork 79
Description
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: MongoObjectIdAdditional 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
- Compatibility between releases
- Data validation/parsing
- Data serialization -
.model_dump()and.model_dump_json() - JSON Schema
- Dataclasses
- Model Config
- Field Types - adding or changing a particular data type
- Function validation decorator
- Generic Models
- Other Model behaviour -
model_construct(), pickling, private attributes, ORM mode - Plugins and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.