It is working right? #11303
-
First Check
Commit to Help
Example Codeclass QueryParams(BaseModel):
test: str
@field_validator('test')
def check_test_starts_with(cls, v):
if not v.startswith("test"):
raise ValueError('O campo "test" deve começar com "test"')
return v
@app.get('/test')
def test(params: QueryParams = Depends()):
... DescriptionI have an endpoint that uses a Pydantic model for query parameters. This model includes validation for one of its fields. However, instead of returning a 422 invalid request error (as it would when using a Pydantic model to validate the request body), it returns a 500 error. Is it supposed to work like this? Operating SystemWindows Operating System DetailsNo response FastAPI Version0.110.0 Pydantic Version2.6.4 Python VersionPython 3.11.0rc1 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
You can work around this by creating a custom exception and adding its custom handler to your fastapi application.
|
Beta Was this translation helpful? Give feedback.
-
I believe it shouldn't return 500 error, but now it really does. But if you use Field's
|
Beta Was this translation helpful? Give feedback.
-
Reviewed this one more time. Since v0.115.0 FastAPI officially supports Pydantic models in So, after updating the code according to new docs, it works well: from typing import Annotated
from fastapi import FastAPI, Query
from pydantic import BaseModel, field_validator
class QueryParams(BaseModel):
test: str
@field_validator("test")
def check_test_starts_with(cls, v):
if not v.startswith("test"):
raise ValueError('O campo "test" deve começar com "test"')
return v
app = FastAPI()
@app.get("/test")
def test(params: Annotated[QueryParams, Query()]):
pass |
Beta Was this translation helpful? Give feedback.
Reviewed this one more time.
Since v0.115.0 FastAPI officially supports Pydantic models in
Query
parameters (and inHeader
andCookie
as well).So, after updating the code according to new docs, it works well: