-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
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
How to define custom objects as query parameters in FastAPI (using PydanticV2 annotations)? #10259
Comments
There's at least one issue here: the error message says there's a problem with the response field. |
Related: #10109 |
Facing the same issue while trying to migrate to pydantic v2, using FastAPI Works fine with pydantic v1, but fails with v2, getting the exact same error that says the issue is within the response, and removing the non-pydantic query parameter object solves the issue. |
If that can help, I made a very small code to reproduce @Kludex
The work-around is to not create the type in the query parameters, but in the function.
|
This is exactly the workaround that I use. It works, but then you need to do it in every API endpoint which adds quite a lot of duplicated lines in the code... |
Having this issue as well. I would like the more concise Pydantic v2 for ObjectId to work easily with |
Pydantic's
In the provided code above, lambda expression doesn't support to raise exceptions try to implement custom function that handle the validation error similar to code provided below. Additionaly, FastAPI doesn't support to raise custom error(s) (such as Version
Example Codefrom typing import Annotated
from bson import ObjectId
# from bson.errors import InvalidId
from fastapi import FastAPI
from pydantic import (
BaseModel,
BeforeValidator,
Field,
PlainSerializer,
WithJsonSchema,
)
app = FastAPI()
def check_object_id(value: ObjectId | str) -> ObjectId:
if isinstance(value, (ObjectId, str)) and ObjectId.is_valid(value):
return ObjectId(value)
raise ValueError(
f"{value} is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string"
)
# raise InvalidId(
# f"{value} is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string"
# )
OID = Annotated[
ObjectId | str | None,
Field(None),
BeforeValidator(check_object_id),
PlainSerializer(
func=lambda x: None if x is None else str(x),
return_type=str | None,
),
WithJsonSchema({"type": "string"}, mode="validation"),
WithJsonSchema({"type": "string"}, mode="serialization"),
]
class Foo(BaseModel):
model_config = {"arbitrary_types_allowed": True}
id: OID
bar: str = "test"
@app.post("/bar/")
async def bar(foo: Foo):
return foo |
Bumping this up, as is still an issue ; neither the error message nor the implementation have been fixed @tiangolo |
Encountering this as well. My use case is to validate the query param to match any of my given strings in a list. I also made a custom object for this and upon migrating to pydantic v2 it's not working. |
Same issue on 0.111.1 with code like: from typing import Any
from fastapi import FastAPI
from pydantic import PlainValidator, WithJsonSchema
from typing_extensions import Annotated, Doc
from uuid6 import UUID
def uuid_version_validator(id: Any) -> Any:
if isinstance(id, str):
id = UUIDv7(id)
if not id.version or id.version != 7:
raise ValueError(f"Run ID: {run_id} is not valid uuid. Only UUIDv7 is supported")
return run_id
UUIDv7 = Annotated[
UUID,
PlainValidator(uuid_version_validator),
WithJsonSchema({"type": "string", "format": "uuid"}),
Doc("UUID v7"),
]
app = FastAPI()
@app.get("/test")
def test(id: UUID):
pass
|
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
Discussed in #10101
Originally posted by DSamuylov August 17, 2023
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
The text was updated successfully, but these errors were encountered: