from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Response(BaseModel):
a: str
b: int
class Config:
json_encoders = {
int: lambda x: '999',
}
@app.get("/")
async def root():
return Response(a='XXX', b=666)
Expected result is {"a": "XXX", "b": "999"} but insted of that i take {"a": "XXX", "b": 666}
It's not a FastAPI issue. FastAPI supports it since long time ago: https://github.com/tiangolo/fastapi/issues/18
I think json_encoders don't support some types (str, int, float and None). I spent some minutes investigating this issue and here is what I've found:
JSONABLE_OK = (str, int, float, type(None)), you can see more details on: https://gist.github.com/samuelcolvin/1647958c99cc59873f36400048d77ae2 json_encoders, but I still haven't find out where it ignores those types. (https://github.com/samuelcolvin/pydantic/blob/f1f944fbc1609450cc7638cdfc323e37298c01c5/pydantic/main.py#L291,Either way, it's not a FastAPI issue. It works with datetime for example (https://github.com/tiangolo/fastapi/issues/18).
Ok! i think it could be closed!
Thanks for the help here @Kludex ! :clap: :bow:
Thanks for reporting back and closing the issue :+1: