-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
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 RootModel
as query parameter
#11134
Comments
RootModel
as query parameter
Stumbled upon this today, I was quite surprised this is not possible, this feels very FastAPI-like 😄 Is this feature difficult to implement? I get the feeling that running validations on such query fields can be problematic. That's was btw my primary motivation to do this. Just to provide another example, this is my use-case I wanted to originally implement. The idea was to have consistent validator for this type, and to have convenience methods on top of this value. class BoundingBox(RootModel[str]):
root: str = Field(pattern=BBOX_REGEX)
def expand_values(self):
...
@root_validator
def validate_number_ranges(cls, value):
...
@router.get("/")
def foo(
bbox: BoundingBox | None,
):
exapnded_values = bbox.expand_values() |
@Kludex, @marianhlavac adding support is easy so I did it here: #11306 |
These two alternative implementations also work: Both alternatives require you to declare the parameter as it's "root" type. Validation option 1 constructs the class (forcing the validators to run) then returns just the root portion. from fastapi import FastAPI
from pydantic import RootModel, AfterValidator, model_validator
from typing import Annotated
class SimpleID(RootModel[str]):
# Simulate work to validate the string here
@model_validator(mode='after')
@classmethod
def check_my_string(cls, data: str):
print(f"Validation of {data} passed!")
return data
def string_checker(data: str) -> str:
print(f"Validation of {data} passed!")
return data
app = FastAPI()
@app.get("/test1")
async def t1(param1: Annotated[str, AfterValidator(lambda v: SimpleID(v).root)]):
return {"message": f"Hello {param1}"}
@app.get("/test2")
async def t1(param1: Annotated[str, AfterValidator(string_checker)]):
return {"message": f"Hello {param1}"} |
Those don't produce proper OpenAPI specs, or don't allow the Pydantics model Configs? |
Maybe I'm misunderstanding the full requirements here -- What did you want your OpenAPI spec to look like? I see that "param1" is a string in both cases which is what I expected. You can add Query to the annotation chain to set some more pieces of the OpenAPI spec, if that helps at all: @app.get("/test1")
async def t1(param1: Annotated[str, Query(description="This param must be a SimpleID"), AfterValidator(lambda v: SimpleID(v).root)]):
return {"message": f"Hello {param1}"} If the idea was to have simple scalar root model wrapped around a type that FastAPI already knows how to support -- why would you want/need a config dictionary on that? |
Idea would be to support more complex validation/schema cases (eg customizing the spec via Config etc). Usually the support for using Pydantic models is great here so why not supporting Pydantic RootModels? The workaround is quite verbose compared to just using a RootModel. |
No, the suppport for using Pydantic models as query parameters is not "great". Everything that you're hitting with RootModel in your original issue - FastAPI wanting to make it a Body rather than a Query, and not accepting a model as a type hint to Query, etc. applies to every type of Pydantic model - not just your RootModel. |
Discussed in #11101
Originally posted by WarpedPixel February 6, 2024
First Check
Commit to Help
Example Code
Description
Simple types should be usable as query params. Pydantic provides
RootModel
(instead ofBaseModel
) precisely to implement types with rich validation based on native types likelist
orstr
(instead of the more typical object/dict). Types built withRootModel
do not seem to work as query params, even if it is functionally equivalent to a simple type likestr
.Furthermore, we cannot force them to work as query params with
Query()
annotations either.NOTE: the example is overly simplified, my RootModel-derived types do much more in terms of validation.
Operating System
macOS
Operating System Details
No response
FastAPI Version
0.108.0
Pydantic Version
2.5.3
Python Version
Python 3.11.4
Additional Context
I am not sure this is possible, but I would like for FastAPI to understand RootModel derived types, if the root type is one of the types that can be used as query param, then it should work as such.
The workaround in my case is to use
str
parameters in my FastAPI calls then manually convert to the rich Pydantic type that does validation. Which kind of defeats the purpose of FastAPI rich type annotations.The text was updated successfully, but these errors were encountered: