OpenAPITools / OpenAPITools/openapi-generator

[Question][Python-fastapi] Implementing a singleton pattern for BaseApi subclasses to prevent initialization

Open
#16,763 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Issue: Bug
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

Description

With the current structure, every time an endpoint is called, a new instance of the BaseApi subclass is initialized. How can I implement a singleton to prevent this?

openapi-generator version

v7.0.1 and snapshot version.

OpenAPI declaration file content or url

Here is an example of the OpenAPI declaration file content:

https://gist.github.com/reyescabello/6cd965708fd0b03e8eadb9f3c0c0a899

Generation Details

Generated with jar:

java -jar openapi-generator-cli.jar generate -i openapi.yml -g python-fastapi -o openapi_server

Steps to reproduce

Generated files:

product_api.py
async def find_product_by_id(
    id: str = Path(None, description="ID of product to return", max_length=20),
) -> Product:
    """The user must have any permission in the application."""
    return BaseProductApi.subclasses[0]().find_product_by_id(id)
product_api_base.py
class BaseProductApi:
    subclasses: ClassVar[Tuple] = ()

    def __init_subclass__(cls, **kwargs):
        print(super().__init_subclass__(**kwargs))
        BaseProductApi.subclasses = BaseProductApi.subclasses + (cls,)

The BaseProductApi subclass that I have created. The singleton is not working:

class SubclassProductApi(BaseProductApi):
    __metaclass__ = Singleton

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the generated product_api.py and product_api_base.py examples, then run the reported Java generation command with the linked OpenAPI declaration. Check how BaseProductApi.subclasses is populated and how the endpoint instantiates its implementation. Done would require a clearly specified generator-supported approach that prevents repeated initialization without breaking generated server behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
fastapi, java, openapi, python
Domain
api, backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.