fastapi
fastapi copied to clipboard
Use `RootModel` as query parameter
Discussed in https://github.com/tiangolo/fastapi/discussions/11101
Originally posted by WarpedPixel February 6, 2024
First Check
- [X] I added a very descriptive title here.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I searched the FastAPI documentation, with the integrated search.
- [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
- [X] I already read and followed all the tutorial in the docs and didn't find an answer.
- [X] I already checked if it is not related to FastAPI but to Pydantic.
- [X] I already checked if it is not related to FastAPI but to Swagger UI.
- [X] I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- [X] I commit to help with one of those options 👆
Example Code
# fail.py
# uvicorn fail:app --reload
from fastapi import FastAPI
from pydantic import RootModel
SimpleID = RootModel[str]
app = FastAPI()
@app.get("/test1")
async def t1(param1: SimpleID): # BUG: expected to be query param, but it is body
return {"message": f"Hello {param1}"}
# @app.get("/test2")
# async def t2(param1: Annotated[SimpleID, Query()]): # this workaround does NOT work
# return {"message": f"Hello {param1}"}
@app.get("/test3")
async def t3(param1: SimpleID, param2: str): # param2 is query param as expected, param1 is NOT
return {"message": f"Hello {param1} {param2}"}
Description
Simple types should be usable as query params. Pydantic provides RootModel
(instead of BaseModel
) precisely to implement types with rich validation based on native types like list
or str
(instead of the more typical object/dict). Types built with RootModel
do not seem to work as query params, even if it is functionally equivalent to a simple type like str
.
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.
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: https://github.com/tiangolo/fastapi/pull/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. Validation option 2 just validates the input with a simple function.
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}"}
These two alternative implementations also work:
Those don't produce proper OpenAPI specs, or don't allow the Pydantics model Configs?
These two alternative implementations also work:
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?
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.
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.