Last active
June 9, 2022 18:32
-
-
Save danielballan/1ead249ede75c1be665604fdba39cbef to your computer and use it in GitHub Desktop.
FastAPI, Pydantic, and OpenAPI with recursive models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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