Skip to content

Use RootModel as query parameter #11134

@Kludex

Description

@Kludex

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionQuestion or problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions