Replies: 6 comments 5 replies
-
Hey, it seems like there is a problem. You can try this, but probably it is not, what you are looking for: import bson
from typing import Annotated
from pydantic import (
PlainSerializer,
WithJsonSchema,
BeforeValidator,
)
from fastapi import FastAPI
ObjectId = Annotated[
str,
BeforeValidator(lambda x: bson.ObjectId(x) if isinstance(x, str) else x),
PlainSerializer(lambda x: f"{x}", return_type=str),
WithJsonSchema({"type": "string"}, mode="validation"),
WithJsonSchema({"type": "string"}, mode="serialization"),
]
app = FastAPI()
@app.get("/test", response_model=None)
def test(id: ObjectId) -> bool:
return True |
Beta Was this translation helpful? Give feedback.
-
Hi @romabozhanovgithub, thank you a lot for your comment. Yes, unfortunately this solution does not work because Hopefully @tiangolo would have a moment to confirm if it is a bug or misunderstanding about how to use a new version of Pydantic with FastAPI. |
Beta Was this translation helpful? Give feedback.
-
I was looking for an answer to the same question and found a similar discussion here: #10131 It in turn gave me a solution that worked for me. Hopefully it also works in your case:
or
I think the docs may benefit from adding an example for this usecase 🤔 |
Beta Was this translation helpful? Give feedback.
-
Hi @UlfurOrn, thank you a lot for your suggestion, but for me the code still fails with:
Does it run for you? |
Beta Was this translation helpful? Give feedback.
-
Anybody has an idea on how to fix it? It is still a problem... |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
I am trying to figure out how to update my FastAPI app after from Pydantic v1 to Pydantic v2.
Before I had code that worked perfectly fine:
With the code that I provided above, I get the following error message:
I am a bit confused, because it seems that the problem is not with a response model (which is bool in the example), but with a custom type in query parameter.
I also checked other suggested approaches, for example:
There, it is suggested an alternative approach to introduce a custom annotation type, however, it still does not work for me.
I also did not find any relevant in the FastAPI documentation about query parameters and a list of Extra Data Types.
I would highly appreciate if you could help to find a possible solution.
Operating System
macOS
Operating System Details
No response
FastAPI Version
0.101.1
Pydantic Version
2.1.1
Python Version
Python 3.11.4
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions