title: How to include non-pydantic classes in fastapi responses?
body: <p>I want to include a custom class into a route's response. I'm mostly using nested <code>pydantic.BaseModel</code>s in my application, so it would be nice to return the whole thing without writing a translation from the internal data representation to what the route returns.</p>
  <p>As long as <em>everything</em> inherits from <code>pydantic.BaseModel</code> this is trivial, but I'm using a class <code>Foo</code> in my backend which can't do that, and I can't subclass it for this purpose either. Can I somehow duck type that class's definition in a way that <code>fastapi</code> accepts it? What I have right now is essentially this:</p>
  <p><strong>main.py</strong></p>
  <pre class="lang-py prettyprint-override"><code>from fastapi import FastAPI
  from pydantic import BaseModel
  
  app = FastAPI()
  
  
  class Foo:
      &quot;&quot;&quot;Foo holds data and can't inherit from `pydantic.BaseModel`.&quot;&quot;&quot;
      def __init__(self, x: int):
          self.x = x
  
  
  class Response(BaseModel):
      foo: Foo
      # plus some more stuff that doesn't matter right now because it works
  
  
  @app.get(&quot;/&quot;, response_model=Response)
  def root():
      return Response(foo=Foo(1))
  
  
  if __name__ == '__main__':
      import uvicorn
      uvicorn.run(&quot;main:app&quot;)  # RuntimeError
  </code></pre>