Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use third party class as property in pydantic schema #68

Closed
Certary opened this issue Mar 5, 2019 · 21 comments
Closed

Use third party class as property in pydantic schema #68

Certary opened this issue Mar 5, 2019 · 21 comments

Comments

@Certary
Copy link

Certary commented Mar 5, 2019

Describe the bug
I have a pydantic schema that needs a third party class (bson.objectid.ObjectID) as a property. For this reason I created a custom validator and encoder as per pydantic documentation.

Code

from bson.objectid import ObjectId
from pydantic import BaseModel
from pydantic import validators
from pydantic.errors import PydanticTypeError
from pydantic.utils import change_exception

class ObjectIdError(PydanticTypeError):
    msg_template = 'value is not a valid bson.objectid.ObjectId'

def object_id_validator(v) -> ObjectId:
    with change_exception(ObjectIdError, ValueError):
        v = ObjectId(v)
    return v

def get_validators() -> None:
    yield validators.not_none_validator
    yield object_id_validator

ObjectId.__get_validators__ = get_validators

def encode_object_id(object_id: ObjectId):
    return str(object_id)

class UserId(BaseModel):
    object_id: ObjectId = None

    class Config:
        json_encoders = {
            ObjectId: encode_object_id
        }

class User(UserId):
    email: str
    salt: str
    hashed_password: str

# Just for testing
user = User(object_id = ObjectId(), email="john.doe@example.com", salt="12345678", hashed_password="letmein")
print(user.json())
# Outputs:
# {"object_id": "5c7e424225e2971c8c548a86", "email": "john.doe@example.com", "salt": "12345678", "hashed_password": "letmein"}


As you can see at the bottom of the code, the serialization seems to work just fine. But when I use this schema as an argument (and/or response type) in API operations and then open the automatic documentation, I get presented with an error.

Code

from bson import ObjectId
from fastapi import FastAPI
from user import User, UserId

app = FastAPI()


@app.post("/user", tags=["user"], response_model=UserId)
def create_user(user: User):
    # Create user and return id
    print(user)
    return UserId(objectId=ObjectId())

Log

INFO: ('127.0.0.1', 2706) - "GET /openapi.json HTTP/1.1" 500
ERROR: Exception in ASGI application
Traceback (most recent call last):
  File "<project-path>\venv\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 373, in run_asgi
    result = await asgi(self.receive, self.send)
  File "<project-path>\venv\lib\site-packages\uvicorn\middleware\debug.py", line 83, in __call__
    raise exc from None
  File "<project-path>\venv\lib\site-packages\uvicorn\middleware\debug.py", line 80, in __call__
    await asgi(receive, self.send)
  File "<project-path>\venv\lib\site-packages\starlette\middleware\errors.py", line 125, in asgi
    raise exc from None
  File "<project-path>\venv\lib\site-packages\starlette\middleware\errors.py", line 103, in asgi
    await asgi(receive, _send)
  File "<project-path>\venv\lib\site-packages\starlette\exceptions.py", line 74, in app
    raise exc from None
  File "<project-path>\venv\lib\site-packages\starlette\exceptions.py", line 63, in app
    await instance(receive, sender)
  File "<project-path>\venv\lib\site-packages\starlette\routing.py", line 43, in awaitable
    response = await run_in_threadpool(func, request)
  File "<project-path>\venv\lib\site-packages\starlette\concurrency.py", line 24, in run_in_threadpool
    return await loop.run_in_executor(None, func, *args)
  File "C:\Program Files (x86)\Python37-32\lib\concurrent\futures\thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "<project-path>\venv\lib\site-packages\fastapi\applications.py", line 83, in <lambda>
    lambda req: JSONResponse(self.openapi()),
  File "<project-path>\venv\lib\site-packages\fastapi\applications.py", line 75, in openapi
    openapi_prefix=self.openapi_prefix,
  File "<project-path>\venv\lib\site-packages\fastapi\openapi\utils.py", line 230, in get_openapi
    flat_models=flat_models, model_name_map=model_name_map
  File "<project-path>\venv\lib\site-packages\fastapi\utils.py", line 45, in get_model_definitions
    model, model_name_map=model_name_map, ref_prefix=REF_PREFIX
  File "<project-path>\venv\lib\site-packages\pydantic\schema.py", line 461, in model_process_schema
    model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix
  File "<project-path>\venv\lib\site-packages\pydantic\schema.py", line 482, in model_type_schema
    f, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix
  File "<project-path>\venv\lib\site-packages\pydantic\schema.py", line 238, in field_schema
    ref_prefix=ref_prefix,
  File "<project-path>\venv\lib\site-packages\pydantic\schema.py", line 440, in field_type_schema
    ref_prefix=ref_prefix,
  File "<project-path>\venv\lib\site-packages\pydantic\schema.py", line 643, in field_singleton_schema
    raise ValueError(f'Value not declarable with JSON Schema, field: {field}')
ValueError: Value not declarable with JSON Schema, field: object_id type=ObjectId default=None


To Reproduce
Copy my code and follow the instrcutions given in the "Describe the bug" section.

Expected behavior
No error should occur and the documentation should be able to show the schema correctly.

Environment:

  • OS: Windows 10
  • FastAPI: 0.6.3
  • Python: 3.7.2
@Certary Certary added the bug Something isn't working label Mar 5, 2019
@tiangolo
Copy link
Owner

Thanks for the report, sorry for the delay.

I see/assume you are using MongoDB, right?

I hope to check and debug it soon, but it might take a bit as I have to set up a stack with mongo (and I don't have a project generator with Mongo just yet).

@Certary
Copy link
Author

Certary commented Mar 28, 2019

Thanks for your response.

You are right, I'm using MongoDB.
But the problem isn't related to MongoDB, so I don't think you need it to debug the error.

You just need to install the following pip packages:

  • FastAPI
  • bson

And then put the first code snippet in a module called user.py and the second one into some arbitrary module (e.g. server.py). When you then start the server and open the automatic documentation in your browser, you should be greeted by the error in the Log accordion above.

Note: I had to slightly modify my code snippets to make it possible to just copy-paste them.

@tiangolo
Copy link
Owner

Excellent, I'll use that to debug/develop it.

@MarlieChiller
Copy link

Was there a conclusion to this? Trying to parse mongos _id field is proving to be quite tricky unless i just delete it before returning the response

@tiangolo
Copy link
Owner

@Charlie-iProov not yet, but it's on the backlog.

@stefanondisponibile
Copy link

Not sure this being a bug or a feature.
I'm still digging into fastAPI, but when you're saying:

@app.post("/user", tags=["user"], response_model=UserId)

you're basically declaring that your response will be a UserId, that is:

class UserId(BaseModel):
    object_id: ObjectId = None

if I was on the other side, receiving this response, I would then have to expect this kind of json:

{
  "object_id": ObjectId("5cdc01a6d8893f59a36d9957")
}

which would be pretty strange, since I couldn't have that ObjectId there.

Moreover, having to POST to that endpoint I would have a similar problem, since User inherits from UserId:

@app.post("/user", tags=["user"], response_model=UserId)
def create_user(user: User)
class User(UserId):
    email: str
    salt: str
    hashed_password: str

again, my problem would be what to send as an object_id:

{
  "object_id": ObjectId("5cdc01a6d8893f59a36d9957"),
  "email" : "my@mail.com",
  "password": "letmein",
  "salt":"12345678"
}

That's why defining custom json_encoders wouldn't help here.

@tiangolo
Copy link
Owner

@stefanondisponibile I'm currently working on this PR in Pydantic: pydantic/pydantic#520

It will allow you to declare object_id: str and then FastAPI will take your ObjectId("5cdc01a6d8893f59a36d9957") and convert it to a string automatically.

@stefanondisponibile
Copy link

That's great!

@tiangolo
Copy link
Owner

About pydantic/pydantic#520, it was superseded by pydantic/pydantic#562.

While reviewing it I tested with bson, and I realized that it doesn't necessarily fix the problem, but that you can fix it like this:

from bson import ObjectId
from pydantic import BaseModel


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

    @classmethod
    def validate(cls, v):
        if not isinstance(v, ObjectId):
            raise ValueError("Not a valid ObjectId")
        return str(v)


class UserId(BaseModel):
    object_id: ObjectIdStr = None


class User(UserId):
    email: str
    salt: str
    hashed_password: str

# Just for testing
user = User(object_id = ObjectId(), email="john.doe@example.com", salt="12345678", hashed_password="letmein")
print(user.json())
# Outputs:
# {"object_id": "5c7e424225e2971c8c548a86", "email": "john.doe@example.com", "salt": "12345678", "hashed_password": "letmein"}

The trick is, there's no way to declare a JSON Schema for a BSON ObjectId, but you can create a custom type that inherits from a str, so it will be declarable in JSON Schema, and it can take an ObjectId as input.

Then, if you need the ObjectId itself (instead of the str version), you can create another model that has the ObjectId as you declared it before, and copy the values from the input/to the output.

@Certary
Copy link
Author

Certary commented Jun 8, 2019

That will do for now, thanks for you effort!

I will also test my example with the changes to Pydantic you referenced when I get around to it.

@Certary Certary closed this as completed Jun 8, 2019
@stefanondisponibile
Copy link

I'm using the solution proposed by @tiangolo up above, just I preferred doing this:

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

    @classmethod
    def validate(cls, v):
        try:
            ObjectId(str(v))
        except InvalidId:
            raise ValuerError("Not a valid ObjectId")
        return str(v)

this way I can either pass a valid ObjectId string or an ObjectId instance.

This works pretty nicely also with mongoengine, as you'll be able to pass that ObjectIdStr directly to the db_model, and it will convert the ObjectIdStrings to actual ObjectIds in Mongo.

What I'm striving to understand now, though, is why can't I get an ObjectId back from the jsonable_encoder by setting this in Config's json_encoders property:

from bson import ObjectId
from pydantic import BaseModel
from upabove import ObjectIdStr

class SomeItem(BaseModel):
    some_id: ObjectIdStr
   
    class Config:
        json_encoders = {ObjectIdStr: lambda x: ObjectId(x)}

Why wouldn't some_id be converted to an ObjectId when calling jsonable_encoder on SomeItem instance? Is it maybe because being some_id a str it won't be passed further down to the custom json_encoders? This even if ObjectIds, are not json serializable.

@topsailcashew-zz
Copy link

Okay, so pardon me if I don't make much sense. I face this 'ObjectId' object is not iterable whenever I run the collections.find() functions. Going through the answers here, I'm not sure where to start. I'm new to programming, please bear with me.

Every time I hit the route which is supposed to fetch me data from Mongodb, I getValueError: [TypeError("'ObjectId' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')].

Help

@stefanondisponibile
Copy link

Hi @senjenathaniel ! Are you sure your problem fits this issue? If you could give some more details, and an example of the code you're using, I think someone could give the proper advice :)

@warvariuc
Copy link

from bson import ObjectId
from pydantic import BaseModel
from upabove import ObjectIdStr

class SomeItem(BaseModel):
    some_id: ObjectIdStr
   
    class Config:
        json_encoders = {ObjectIdStr: lambda x: ObjectId(x)}

Why wouldn't some_id be converted to an ObjectId when calling jsonable_encoder on SomeItem instance? Is it maybe because being some_id a str it won't be passed further down to the custom json_encoders? This even if ObjectIds, are not json serializable.

@stefanondisponibile Have you solved this issue? I am also getting TypeError: Object of type 'ObjectId' is not JSON serializable though I have defined json_encoders.

@warvariuc
Copy link

Actually, I found the answer here: pydantic/pydantic#1671

So it should be:

class ObjectId(bson.ObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, value):
        try:
            return cls(value)
        except bson.errors.InvalidId:
            raise ValueError("Not a valid ObjectId")


class BaseModel(p.BaseModel):

    class Config:
        json_encoders = {ObjectId: str}

@gustavorps
Copy link

gustavorps commented Feb 23, 2022

+1

INFO:     127.0.0.1:42104 - "GET /docs HTTP/1.1" 200 OK
INFO:     127.0.0.1:42104 - "GET /openapi.json HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 372, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/fastapi/applications.py", line 212, in __call__
    await super().__call__(scope, receive, send)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/starlette/middleware/cors.py", line 84, in __call__
    await self.app(scope, receive, send)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/opentelemetry/instrumentation/asgi/__init__.py", line 368, in __call__
    await self.app(scope, otel_receive, otel_send)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/starlette/routing.py", line 61, in app
    response = await func(request)
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/fastapi/applications.py", line 164, in openapi
    return JSONResponse(self.openapi())
  File "/home/gustavorps/code/issue/http/server.py", line 48, in custom_openapi
    openapi_schema = get_openapi(
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/fastapi/openapi/utils.py", line 389, in get_openapi
    definitions = get_model_definitions(
  File "/home/gustavorps/.miniconda3/envs/python3/lib/python3.8/site-packages/fastapi/utils.py", line 24, in get_model_definitions
    m_schema, m_definitions, m_nested_models = model_process_schema(
  File "pydantic/schema.py", line 617, in pydantic.schema.model_process_schema
  File "pydantic/schema.py", line 658, in pydantic.schema.model_type_schema
  File "pydantic/schema.py", line 258, in pydantic.schema.field_schema
  File "pydantic/schema.py", line 563, in pydantic.schema.field_type_schema
  File "pydantic/schema.py", line 848, in pydantic.schema.field_singleton_schema
  File "pydantic/schema.py", line 748, in pydantic.schema.field_singleton_sub_fields_schema
  File "pydantic/schema.py", line 563, in pydantic.schema.field_type_schema
  File "pydantic/schema.py", line 947, in pydantic.schema.field_singleton_schema
ValueError: Value not declarable with JSON Schema, field: name='id_ObjectId' type=ObjectId required=True
import typing as T
from datetime import datetime

from bson.errors import InvalidId
from bson.objectid import ObjectId as BsonObjectId
from pydantic import (
    BaseModel as _BaseModel,
    Field,
)


class ObjectId(BsonObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        try:
            return cls(v)
        except InvalidId:
            raise ValueError(f'{v} is not a valid ObjectId')


class BaseModel(_BaseModel):
    class Config:
        json_encoders = {ObjectId: str}


class BaseMongoCreateModel(BaseModel):
    date_created: T.Optional[datetime]
    date_updated: T.Optional[datetime]
    
    class Config:
        allow_population_by_field_name=True
        orm_mode=True


class BaseMongoRetrieveModel(BaseMongoCreateModel):
    id: T.Union[str, ObjectId] = Field(...)

    class Config:
        orm_mode = True
        allow_population_by_field_name=True
$ python
Python 3.8.12 | packaged by conda-forge | (default, Jan 30 2022, 23:53:36) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pydantic; pydantic.__version__
'1.9.0'
>>> import fastapi; fastapi.__version__
'0.73.0'

@gustavorps
Copy link

gustavorps commented Feb 23, 2022

Solved reading the implementation of hbusul/kucukdev_api#18

import typing as T
from datetime import datetime

from bson.errors import InvalidId
from bson.objectid import ObjectId as BsonObjectId
from pydantic import (
    BaseModel as _BaseModel,
    Field,
)


class ObjectId(BsonObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        try:
            return cls(v)
        except InvalidId:
            raise ValueError(f'{v} is not a valid ObjectId')
+
+   @classmethod
+   def __modify_schema__(cls, field_schema):
+       field_schema.update(type='string')


class BaseModel(_BaseModel):
    class Config:
        json_encoders = {ObjectId: str}


class BaseMongoCreateModel(BaseModel):
    date_created: T.Optional[datetime]
    date_updated: T.Optional[datetime]
    
    class Config:
        allow_population_by_field_name=True
        orm_mode=True


class BaseMongoRetrieveModel(BaseMongoCreateModel):
    id: T.Union[str, ObjectId] = Field(...)

    class Config:
        orm_mode = True
        allow_population_by_field_name=True

@haykkh
Copy link

haykkh commented Apr 18, 2022

I'm getting the same issues with trying to access geoalchemy2 data through shapely geometry types.

@gustavorps' comment above works, but doesn't seem very "safe". Why are we having to monkey patch the type of the field?

@Zaffer
Copy link

Zaffer commented Jun 21, 2022

@gustavorps thanks for that code it is useful! Here is the solution I did to make it work for my arbitary type: tiangolo/sqlmodel#235 (comment)

@tanhaa
Copy link

tanhaa commented Jul 15, 2022

I'm getting the same issues with trying to access geoalchemy2 data through shapely geometry types.

@gustavorps' comment above works, but doesn't seem very "safe". Why are we having to monkey patch the type of the field?

are you patching the geometry type to include more classmethods? I am interested to see how you have made it work as I am also facing this issue using sqlmodel + shapely

from geoalchemy2 import Geometry
from pydantic import validator, BaseConfig
from shapely.geometry import Point, asShape
from sqlalchemy import Column
from sqlmodel import Field, SQLModel

class LocBase(SQLModel):
    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True

    name: str
    [...]
    longitude: Optional[float] = None
    latitude: Optional[float] = None
    geom: Optional[Point] = Field(
        nullable=True,
        index=True,
        sa_column=Column(Geometry("POINT", srid=4326)),
        alias="point",
    )

    @validator("geom", pre=True)
    def geom_to_shape(cls, v):
        return asShape(v)

I had to add

BaseConfig.arbitrary_types_allowed = True

as arbitrary_types_allowed=True does not seem to be doing the job.
The final error that I'm getting is ValueError: Value not declarable with JSON Schema, field: name='geom' type=Optional[Point] required=False default=None alias='point'

@tiangolo tiangolo added question Question or problem answered reviewed and removed bug Something isn't working labels Feb 23, 2023
@tiangolo tiangolo changed the title [BUG] Use third party class as property in pydantic schema Use third party class as property in pydantic schema Feb 24, 2023
@tiangolo tiangolo reopened this Feb 28, 2023
@github-actions
Copy link
Contributor

Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.

@tiangolo tiangolo reopened this Feb 28, 2023
Repository owner locked and limited conversation to collaborators Feb 28, 2023
@tiangolo tiangolo converted this issue into discussion #8233 Feb 28, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Projects
None yet
Development

No branches or pull requests

10 participants