Skip to content
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

Open
9 tasks done
Kludex opened this issue Feb 13, 2024 Discussed in #11101 · 2 comments · May be fixed by #11306
Open
9 tasks done

Use RootModel as query parameter #11134

Kludex opened this issue Feb 13, 2024 Discussed in #11101 · 2 comments · May be fixed by #11306
Labels
question Question or problem

Comments

@Kludex
Copy link
Sponsor Collaborator

Kludex commented Feb 13, 2024

Discussed in #11101

Originally posted by WarpedPixel February 6, 2024

First Check

  • I added a very descriptive title here.
  • I used the GitHub search to find a similar question and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • 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.

@Kludex Kludex added the question Question or problem label Feb 13, 2024
@Kludex Kludex changed the title Cannot use simple models derived from str (with Pydantic RootModel) as query params Use RootModel as query parameter Feb 13, 2024
@marianhlavac
Copy link

marianhlavac commented Mar 9, 2024

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()

@MarkusSintonen
Copy link

MarkusSintonen commented Mar 17, 2024

@Kludex, @marianhlavac adding support is easy so I did it here: #11306

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants