-
First Check
Commit to Help
Example Codeimport collections
import uvicorn
from fastapi import FastAPI
from pydantic import RootModel
class Strings(RootModel[list[str]], collections.abc.Sequence):
def __getitem__(self, index):
return self.root[index]
def __len__(self):
return len(self.root)
def __iter__(self):
yield from self.root
app = FastAPI()
@app.post('/post-strings')
async def post_strings(strings: Strings):
return strings
uvicorn.run(
app, # type: ignore
host='127.0.0.1',
port=8088,
)Description
curl -X POST http://127.0.0.1:8088/post-strings -d '["foo","bar","baz"]' -H "Content-Type: application/json"
...
< HTTP/1.1 422 Unprocessable Entity
{"detail":[{"type":"missing","loc":["body","strings"],"msg":"Field required","input":null}]}The reason for this behavior is incorrect implementation of the Related PR: #10393 Operating SystemLinux Operating System DetailsNo response FastAPI Version0.111.0 Pydantic Version2.8.2 Python Version3.12.3 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
|
@rigens while I'm not certain if this is intended behavior, this seems to be a result of the Bit of a partial solution, but I'd omit that sequence subclasses and if you need to for type checking, simply pass around the |
Beta Was this translation helpful? Give feedback.
-
|
@ecly, this is a BUG as described here #10393
thanks, but we need this subclassing |
Beta Was this translation helpful? Give feedback.
-
|
Clearly this is a BUG. |
Beta Was this translation helpful? Give feedback.
-
|
Hello @rigens, you can achieve the same with: from fastapi import FastAPI
app = FastAPI()
@app.post("/post-strings")
async def post_strings(strings: list[str]):
return stringsAs FastAPI allows you to use types used for Pydantic fields, there's no need to use If you need to modify things further, you can also use additional Pydantic validators: https://docs.pydantic.dev/latest/concepts/validators/ |
Beta Was this translation helpful? Give feedback.
-
It's not the same... We need the custom pydantic model (not list[str]) for some other purposes dictated by our application logic (not only for FastAPI request validation)
Really? @tiangolo, I have clearly pointed out the BUG that is causing the incorrect behavior, and instead of fixing it, you suggest that I use some workarounds |
Beta Was this translation helpful? Give feedback.
Hello @rigens, you can achieve the same with:
As FastAPI allows you to use types used for Pydantic fields, there's no need to use
RootModel, it's not officially supported, because you can achieve the same in better and simpler ways.If you need to modify things further, you can also use additional Pydantic validators: https://docs.pydantic.dev/latest/concepts/validators/