Skip to content

Instantly share code, notes, and snippets.

@danielballan
Last active June 9, 2022 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danielballan/1ead249ede75c1be665604fdba39cbef to your computer and use it in GitHub Desktop.
Save danielballan/1ead249ede75c1be665604fdba39cbef to your computer and use it in GitHub Desktop.
FastAPI, Pydantic, and OpenAPI with recursive models
## Models
from __future__ import annotations
from dataclasses import dataclass
import pydantic
from typing import Optional
# @dataclass
# class Node:
# left: Optional[Node] = None
# right: Optional[Node] = None
#
#
# class Tree(pydantic.BaseModel): # This raises: Exception has occurred: RecursionError
# root_node: Node
#
#
# PydanticNode = pydantic.dataclasses.dataclass(Node) # This raises: Exception has occurred: RecursionError
class Node(pydantic.BaseModel):
left: Optional[Node] = None
right: Optional[Node] = None
class Tree(pydantic.BaseModel):
root_node: Node
## App
from fastapi import FastAPI
app = FastAPI()
@app.post("/")
def index(tree: Tree):
return tree
if __name__ == "__main__":
import uvicorn
uvicorn.run(app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment