Problem: FastAPI doesn't accept JSON-encoded pydantic models in query strings. See #884.
Solution: Use json_param()
from the snippet below.
Usage example.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
@app.get("/")
def root(user: User = json_param("user", User, description="User object")):
return {"message": f"Hello, {user!r}"}
Request and response examples (with httpie)
Success:
$ http localhost:7000 user=='{"name": "Foo"}'
HTTP/1.1 200 OK
{
"message": "Hello, User(name='Foo')"
}
Validation error:
HTTP/1.1 400 Bad Request
{
"detail": [
{
"loc": [
"name"
],
"msg": "none is not an allowed value",
"type": "type_error.none.not_allowed"
}
]
}
I wrote a more type safe version of @cgbeutler's helper function here: https://github.com/kasir-barati/python/blob/0427aeb171f801b86f917a1584f07dc067394e77/src/utils/json_param_util.py
But I hate the fact that my OpenAPI is wrecked. Now the
filter
is shown as string in Swagger UI :/.