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"
}
]
}
Really cool solution. I'm still learning FastAPI, can I ask some questions about your code:
RequestValidationError
instead ofHTTPException
and get the same result? (except for the response status code, I think it should be 422 for validation errors)model.parse_obj(value)
instead ofpydantic.parse_obj_as(mode, value)
in Pydantic v1?value: str
andmodel.parse_raw(value)
instead ofvalue: Json
andpydantic.parse_obj_as(model, value)
in Pydantic v1?