Skip to content

Instantly share code, notes, and snippets.

@a-recknagel
Last active June 29, 2021 08:32
Show Gist options
  • Save a-recknagel/f50de2e16cb2396090cff862b16a0303 to your computer and use it in GitHub Desktop.
Save a-recknagel/f50de2e16cb2396090cff862b16a0303 to your computer and use it in GitHub Desktop.
fastapi with custom classes in response
from fastapi import FastAPI
from pydantic import BaseModel, BaseConfig
app = FastAPI()
BaseConfig.arbitrary_types_allowed = True
class Foo:
def __init__(self, x: int):
self.x = x
class Response(BaseModel):
foo: Foo
@app.get("/", response_model=Response)
def root():
return Response(foo=Foo(1))
if __name__ == '__main__':
import uvicorn
uvicorn.run("main:app")
# route works and returns {"foo":{"x":1}}, OpenAPI crashes:
# ValueError: Value not declarable with JSON Schema,
# field: name='foo' type=Foo required=True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment