Fastapi: FastApi ignore custom pydantic json_encoders

Created on 14 Jul 2020  路  3Comments  路  Source: tiangolo/fastapi

Example

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)

Description

Expected result is {"a": "XXX", "b": "999"} but insted of that i take {"a": "XXX", "b": 666}

Environment

  • OS: macOS:
  • FastAPI Version [e.g. 0.3.0]: 0.59.0
  • pydantic: 1.6
  • Python version: 3.7.6
question

All 3 comments

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:

  • There's a gist from 2 years ago from Samuel (pydantic creator) that states the variable JSONABLE_OK = (str, int, float, type(None)), you can see more details on: https://gist.github.com/samuelcolvin/1647958c99cc59873f36400048d77ae2
  • On the other hand, I was trying to find it in the current project, and here are the places where you can find information about the 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,
    https://github.com/samuelcolvin/pydantic/blob/f1f944fbc1609450cc7638cdfc323e37298c01c5/pydantic/json.py#L65)

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:

Was this page helpful?
0 / 5 - 0 ratings