[BUG] python-fastapi: models break on forward type references
Created by: chludwig-haufe
Description
I gave the (beta) python-fastapi
generator a try on a PoC API. The API's response model contains a recursive data structure (some irrelevant attributes removed):
definitions:
# ...
SearchCategory:
properties:
query:
type: string
subcategories:
items:
$ref: '#/definitions/SearchCategory'
type: array
The generator python-fastapi
translates this into the following Python module :
# coding: utf-8
from datetime import date, datetime # noqa: F401
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401
class SearchCategory(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
SearchCategory - a model defined in OpenAPI
query: The query of this SearchCategory [Optional].
subcategories: The subcategories of this SearchCategory [Optional].
"""
query: Optional[str] = None
subcategories: Optional[List[SearchCategory]] = None
This module fails to import because of the forwarding type reference subcategories: Optional[List[SearchCategory]]
. This will be supported out of the box from Python 3.10 on only. Since Python 3.7, you can opt-in using a __future__ import
. Otherwise, the forward reference needs to be given as a string (i.e., subcategories: Optional[List["SearchCategory"]]
.
openapi-generator version
Head of master branch as of June 8, 2021 (c379f5bc)
Suggest a fix
Add from __future__ import annotations
to python-fastapi/model.mustache. This solves the issue at least for >= Python 3.7.
Figuring out in the template whether it's a forwarding reference and conditionally wrapping the reference into a string seems much harder.