openapi-python-generator 1.1.2.dev1734090594__tar.gz → 1.2.1.dev1757315625__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/PKG-INFO +5 -5
  2. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/pyproject.toml +29 -12
  3. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/setup.py +7 -5
  4. openapi_python_generator-1.2.1.dev1757315625/src/openapi_python_generator/__init__.py +17 -0
  5. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/__main__.py +21 -6
  6. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/common.py +16 -2
  7. openapi_python_generator-1.2.1.dev1757315625/src/openapi_python_generator/generate_data.py +235 -0
  8. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/api_config_generator.py +12 -8
  9. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/common.py +1 -2
  10. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/generator.py +9 -6
  11. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/jinja_config.py +1 -4
  12. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/model_generator.py +201 -63
  13. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/service_generator.py +186 -70
  14. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/templates/aiohttp.jinja2 +10 -9
  15. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/templates/httpx.jinja2 +8 -5
  16. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/templates/models.jinja2 +5 -3
  17. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/templates/models_pydantic_2.jinja2 +5 -3
  18. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/templates/requests.jinja2 +8 -5
  19. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/templates/service.jinja2 +2 -1
  20. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/models.py +25 -4
  21. openapi_python_generator-1.2.1.dev1757315625/src/openapi_python_generator/parsers/__init__.py +13 -0
  22. openapi_python_generator-1.2.1.dev1757315625/src/openapi_python_generator/parsers/openapi_30.py +65 -0
  23. openapi_python_generator-1.2.1.dev1757315625/src/openapi_python_generator/parsers/openapi_31.py +65 -0
  24. openapi_python_generator-1.2.1.dev1757315625/src/openapi_python_generator/py.typed +0 -0
  25. openapi_python_generator-1.2.1.dev1757315625/src/openapi_python_generator/version_detector.py +70 -0
  26. openapi_python_generator-1.1.2.dev1734090594/src/openapi_python_generator/__init__.py +0 -12
  27. openapi_python_generator-1.1.2.dev1734090594/src/openapi_python_generator/generate_data.py +0 -192
  28. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/LICENSE +0 -0
  29. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/README.md +0 -0
  30. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/__init__.py +0 -0
  31. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/__init__.py +0 -0
  32. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/templates/apiconfig.jinja2 +0 -0
  33. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/templates/apiconfig_pydantic_2.jinja2 +0 -0
  34. {openapi_python_generator-1.1.2.dev1734090594 → openapi_python_generator-1.2.1.dev1757315625}/src/openapi_python_generator/language_converters/python/templates/enum.jinja2 +0 -0
@@ -1,26 +1,26 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: openapi-python-generator
3
- Version: 1.1.2.dev1734090594
3
+ Version: 1.2.1.dev1757315625
4
4
  Summary: Openapi Python Generator
5
5
  Home-page: https://github.com/MarcoMuellner/openapi-python-generator
6
6
  License: MIT
7
7
  Keywords: OpenAPI,Generator,Python,async
8
8
  Author: Marco Müllner
9
9
  Author-email: muellnermarco@gmail.com
10
- Requires-Python: >=3.8,<4.0
10
+ Requires-Python: >=3.9,<4.0
11
11
  Classifier: Development Status :: 3 - Alpha
12
12
  Classifier: License :: OSI Approved :: MIT License
13
13
  Classifier: Programming Language :: Python :: 3
14
- Classifier: Programming Language :: Python :: 3.8
15
14
  Classifier: Programming Language :: Python :: 3.9
16
15
  Classifier: Programming Language :: Python :: 3.10
17
16
  Classifier: Programming Language :: Python :: 3.11
18
17
  Requires-Dist: Jinja2 (>=3.1.2,<4.0.0)
19
18
  Requires-Dist: black (>=21.10b0)
20
19
  Requires-Dist: click (>=8.1.3,<9.0.0)
21
- Requires-Dist: httpx[all] (>=0.23.0,<0.24.0)
20
+ Requires-Dist: httpx[all] (>=0.28.0,<0.29.0)
21
+ Requires-Dist: importlib-metadata (>=8.7.0,<9.0.0)
22
22
  Requires-Dist: isort (>=5.10.1)
23
- Requires-Dist: openapi-pydantic (>=0.5.0,<0.6.0)
23
+ Requires-Dist: openapi-pydantic (>=0.5.1,<0.6.0)
24
24
  Requires-Dist: orjson (>=3.9.15,<4.0.0)
25
25
  Requires-Dist: pydantic (>=2.10.2,<3.0.0)
26
26
  Requires-Dist: pyyaml (>=6.0.2,<7.0.0)
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "openapi-python-generator"
3
- version = "1.1.2.dev.1734090594"
3
+ version = "1.2.1.dev.1757315625"
4
4
  description = "Openapi Python Generator"
5
5
  authors = ["Marco Müllner <muellnermarco@gmail.com>"]
6
6
  license = "MIT"
@@ -17,28 +17,25 @@ keywords = ["OpenAPI", "Generator", "Python", "async"]
17
17
  Changelog = "https://github.com/MarcoMuellner/openapi-python-generator/releases"
18
18
 
19
19
  [tool.poetry.dependencies]
20
- python = "^3.8"
21
- httpx = {extras = ["all"], version = "^0.23.0"}
20
+ python = "^3.9"
21
+ httpx = {extras = ["all"], version = "^0.28.0"}
22
22
  pydantic = "^2.10.2"
23
23
  orjson = "^3.9.15"
24
24
  Jinja2 = "^3.1.2"
25
25
  click = "^8.1.3"
26
26
  black = ">=21.10b0"
27
27
  isort = ">=5.10.1"
28
- openapi-pydantic = "^0.5.0"
28
+ openapi-pydantic = "^0.5.1"
29
29
  pyyaml = "^6.0.2"
30
+ importlib-metadata = "^8.7.0"
30
31
 
31
- [tool.poetry.dev-dependencies]
32
+ [tool.poetry.group.dev.dependencies]
32
33
  Pygments = ">=2.10.0"
33
34
  coverage = {extras = ["toml"], version = "^6.4.1"}
34
35
  darglint = ">=1.8.1"
35
- flake8 = ">=3.0.1"
36
- flake8-bandit = ">=2.1.2"
37
- flake8-bugbear = ">=21.9.2"
38
- flake8-docstrings = ">=1.6.0"
39
- flake8-rst-docstrings = ">=0.2.5"
36
+ ruff = ">=0.12.12"
40
37
  furo = ">=2021.11.12"
41
- mypy = ">=0.930"
38
+ ty = "^0.0.1a20"
42
39
  pep8-naming = ">=0.10.1"
43
40
  pre-commit = ">=2.16.0"
44
41
  pre-commit-hooks = ">=4.1.0"
@@ -51,7 +48,7 @@ myst-parser = {version = ">=0.16.1"}
51
48
  pytest-cov = "^3.0.0"
52
49
  fastapi = "^0.115.5"
53
50
  uvicorn = "^0.18.1"
54
- respx = "^0.20.1"
51
+ respx = "^0.22.0"
55
52
  aiohttp = "^3.8.3"
56
53
 
57
54
  [tool.poetry.scripts]
@@ -86,3 +83,23 @@ show_error_context = true
86
83
  [build-system]
87
84
  requires = ["poetry-core>=1.0.0"]
88
85
  build-backend = "poetry.core.masonry.api"
86
+
87
+ [tool.ruff]
88
+ exclude = ["tests/*"]
89
+ line-length = 120
90
+
91
+ [tool.ruff.lint]
92
+ ignore = ["E501"]
93
+ select = [
94
+ "B",
95
+ "B9",
96
+ "C",
97
+ "E",
98
+ "F",
99
+ "I",
100
+ "S",
101
+ "W",
102
+ ]
103
+
104
+ [tool.ruff.lint.mccabe]
105
+ max-complexity = 25
@@ -7,7 +7,8 @@ package_dir = \
7
7
  packages = \
8
8
  ['openapi_python_generator',
9
9
  'openapi_python_generator.language_converters',
10
- 'openapi_python_generator.language_converters.python']
10
+ 'openapi_python_generator.language_converters.python',
11
+ 'openapi_python_generator.parsers']
11
12
 
12
13
  package_data = \
13
14
  {'': ['*'],
@@ -17,9 +18,10 @@ install_requires = \
17
18
  ['Jinja2>=3.1.2,<4.0.0',
18
19
  'black>=21.10b0',
19
20
  'click>=8.1.3,<9.0.0',
20
- 'httpx[all]>=0.23.0,<0.24.0',
21
+ 'httpx[all]>=0.28.0,<0.29.0',
22
+ 'importlib-metadata>=8.7.0,<9.0.0',
21
23
  'isort>=5.10.1',
22
- 'openapi-pydantic>=0.5.0,<0.6.0',
24
+ 'openapi-pydantic>=0.5.1,<0.6.0',
23
25
  'orjson>=3.9.15,<4.0.0',
24
26
  'pydantic>=2.10.2,<3.0.0',
25
27
  'pyyaml>=6.0.2,<7.0.0']
@@ -30,7 +32,7 @@ entry_points = \
30
32
 
31
33
  setup_kwargs = {
32
34
  'name': 'openapi-python-generator',
33
- 'version': '1.1.2.dev1734090594',
35
+ 'version': '1.2.1.dev1757315625',
34
36
  'description': 'Openapi Python Generator',
35
37
  'long_description': "# Openapi Python Generator\n\n[![PyPI](https://img.shields.io/pypi/v/openapi-python-generator.svg)][pypi_]\n[![Status](https://img.shields.io/pypi/status/openapi-python-generator.svg)][status]\n[![Python Version](https://img.shields.io/pypi/pyversions/openapi-python-generator)][python version]\n[![License](https://img.shields.io/pypi/l/openapi-python-generator)][license]\n\n[![](https://img.shields.io/static/v1?label=documentation&message=enabled&color=<COLOR>)][documentation]\n[![Tests](https://github.com/MarcoMuellner/openapi-python-generator/workflows/Tests/badge.svg)][tests]\n[![Codecov](https://codecov.io/gh/MarcoMuellner/openapi-python-generator/branch/main/graph/badge.svg)][codecov]\n\n[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)][pre-commit]\n[![Black](https://img.shields.io/badge/code%20style-black-000000.svg)][black]\n\n[pypi_]: https://pypi.org/project/openapi-python-generator/\n[status]: https://pypi.org/project/openapi-python-generator/\n[python version]: https://pypi.org/project/openapi-python-generator\n[documentation]: https://marcomuellner.github.io/openapi-python-generator/\n[tests]: https://github.com/MarcoMuellner/openapi-python-generator/actions?workflow=Tests\n[codecov]: https://app.codecov.io/gh/MarcoMuellner/openapi-python-generator\n[pre-commit]: https://github.com/pre-commit/pre-commit\n[black]: https://github.com/psf/black\n\n![](logo.png)\n\n---\n__Documentation:__ [here][documentation]\n\n---\n\n## Features\n\n- __Ease of use__. Provide input, output and the library, and the generator will do the rest.\n- __Type safety and type hinting.__ __OpenAPI python generator__ makes heavy use of pydantic models to provide type-safe data structures.\n- __Support for multiple rest frameworks.__ __OpenAPI python generator__ currently supports the following:\n - [httpx](https://pypi.org/project/httpx/)\n - [requests](https://pypi.org/project/requests/)\n - [aiohttp](https://pypi.org/project/aiohttp/)\n- __Async and sync code generation support__, depending on the framework. It will automatically create both for frameworks that support both.\n- __Easily extendable using Jinja2 templates__. The code is designed to be easily extendable and should support even more languages and frameworks in the future.\n- __Fully tested__. Every generated code is automatically tested against the OpenAPI spec and we have 100% coverage.\n- __Usage as CLI or as library__.\n\n## Requirements\n\n- Python 3.7+\n\n## Installation\n\nYou can install _Openapi Python Generator_ via [pip] from [PyPI]:\n\n```console\n$ pip install openapi-python-generator\n```\n\n## Usage\n\nPlease see the [Quick start page] for details.\n\n## Roadmap\n\n- Support for all commonly used http libraries in the python ecosystem (~~requests~~, urllib, ...)\n- Support for multiple languages\n- Support for multiple authentication schemes\n- Support custom themes\n\n## Contributing\n\nContributions are very welcome.\nTo learn more, see the [Contributor Guide].\n\n## License\n\nDistributed under the terms of the [MIT license][license],\n_Openapi Python Generator_ is free and open source software.\n\n## Issues\n\nIf you encounter any problems,\nplease [file an issue] along with a detailed description.\n\n## Credits\n\nSpecial thanks to the peeps from [openapi-schema-pydantic](https://github.com/kuimono/openapi-schema-pydantic),\nwhich already did a lot of the legwork by providing a pydantic schema for the OpenAPI 3.0.0+ specification.\n\nThis project was generated from [@cjolowicz]'s [Hypermodern Python Cookiecutter] template.\n\n[@cjolowicz]: https://github.com/cjolowicz\n[pypi]: https://pypi.org/\n[hypermodern python cookiecutter]: https://github.com/cjolowicz/cookiecutter-hypermodern-python\n[file an issue]: https://github.com/MarcoMuellner/openapi-python-generator/issues\n[pip]: https://pip.pypa.io/\n\n<!-- github-only -->\n\n[license]: https://github.com/MarcoMuellner/openapi-python-generator/blob/main/LICENSE\n[contributor guide]: https://github.com/MarcoMuellner/openapi-python-generator/blob/main/CONTRIBUTING.md\n[Quick start page]: https://marcomuellner.github.io/openapi-python-generator/quick_start/\n",
36
38
  'author': 'Marco Müllner',
@@ -43,7 +45,7 @@ setup_kwargs = {
43
45
  'package_data': package_data,
44
46
  'install_requires': install_requires,
45
47
  'entry_points': entry_points,
46
- 'python_requires': '>=3.8,<4.0',
48
+ 'python_requires': '>=3.9,<4.0',
47
49
  }
48
50
 
49
51
 
@@ -0,0 +1,17 @@
1
+ """Python client from an OPENAPI 3.0+ specification in seconds."""
2
+
3
+ try:
4
+ from importlib.metadata import (
5
+ PackageNotFoundError, # type: ignore
6
+ version,
7
+ )
8
+ except ImportError: # pragma: no cover
9
+ from importlib_metadata import (
10
+ PackageNotFoundError, # type: ignore
11
+ version, # type: ignore
12
+ )
13
+
14
+ try:
15
+ __version__ = version(__name__)
16
+ except PackageNotFoundError: # pragma: no cover
17
+ __version__ = "unknown"
@@ -1,12 +1,12 @@
1
1
  from typing import Optional
2
- from enum import Enum
3
2
 
4
3
  import click
5
4
 
6
5
  from openapi_python_generator import __version__
7
- from openapi_python_generator.common import HTTPLibrary, PydanticVersion
6
+ from openapi_python_generator.common import Formatter, HTTPLibrary, PydanticVersion
8
7
  from openapi_python_generator.generate_data import generate_data
9
8
 
9
+
10
10
  @click.command()
11
11
  @click.argument("source")
12
12
  @click.argument("output")
@@ -45,6 +45,13 @@ from openapi_python_generator.generate_data import generate_data
45
45
  show_default=True,
46
46
  help="Pydantic version to use for generated models.",
47
47
  )
48
+ @click.option(
49
+ "--formatter",
50
+ type=click.Choice(["black", "none"]),
51
+ default="black",
52
+ show_default=True,
53
+ help="Option to choose which auto formatter is applied.",
54
+ )
48
55
  @click.version_option(version=__version__)
49
56
  def main(
50
57
  source: str,
@@ -54,17 +61,25 @@ def main(
54
61
  use_orjson: bool = False,
55
62
  custom_template_path: Optional[str] = None,
56
63
  pydantic_version: PydanticVersion = PydanticVersion.V2,
64
+ formatter: Formatter = Formatter.BLACK,
57
65
  ) -> None:
58
66
  """
59
- Generate Python code from an OpenAPI 3.0 specification.
67
+ Generate Python code from an OpenAPI 3.0+ specification.
60
68
 
61
- Provide a SOURCE (file or URL) containing the OpenAPI 3 specification and
69
+ Provide a SOURCE (file or URL) containing the OpenAPI 3.0+ specification and
62
70
  an OUTPUT path, where the resulting client is created.
63
71
  """
64
72
  generate_data(
65
- source, output, library, env_token_name, use_orjson, custom_template_path,pydantic_version
73
+ source,
74
+ output,
75
+ library if library is not None else HTTPLibrary.httpx,
76
+ env_token_name,
77
+ use_orjson,
78
+ custom_template_path,
79
+ pydantic_version,
80
+ formatter,
66
81
  )
67
82
 
68
83
 
69
84
  if __name__ == "__main__": # pragma: no cover
70
- main()
85
+ main()
@@ -1,6 +1,5 @@
1
1
  from enum import Enum
2
- from typing import Dict
3
- from typing import Optional
2
+ from typing import Dict, Optional
4
3
 
5
4
  from openapi_python_generator.models import LibraryConfig
6
5
 
@@ -14,11 +13,26 @@ class HTTPLibrary(str, Enum):
14
13
  requests = "requests"
15
14
  aiohttp = "aiohttp"
16
15
 
16
+
17
17
  class PydanticVersion(str, Enum):
18
18
  V1 = "v1"
19
19
  V2 = "v2"
20
20
 
21
21
 
22
+ class Formatter(str, Enum):
23
+ """
24
+ Enum for the available code formatters.
25
+ """
26
+
27
+ BLACK = "black"
28
+ NONE = "none"
29
+
30
+
31
+ class FormatOptions:
32
+ skip_validation: bool = False
33
+ line_length: int = 120
34
+
35
+
22
36
  library_config_dict: Dict[Optional[HTTPLibrary], LibraryConfig] = {
23
37
  HTTPLibrary.httpx: LibraryConfig(
24
38
  name="httpx",
@@ -0,0 +1,235 @@
1
+ from pathlib import Path
2
+ from typing import List, Optional, Union
3
+
4
+ import black
5
+ import click
6
+ import httpx
7
+ import isort
8
+ import orjson
9
+ import yaml # type: ignore
10
+ from black.report import NothingChanged # type: ignore
11
+ from httpx import ConnectError, ConnectTimeout
12
+ from pydantic import ValidationError
13
+
14
+ from .common import FormatOptions, Formatter, HTTPLibrary, PydanticVersion
15
+ from .language_converters.python.jinja_config import SERVICE_TEMPLATE, create_jinja_env
16
+ from .models import ConversionResult
17
+ from .parsers import (
18
+ generate_code_3_0,
19
+ generate_code_3_1,
20
+ parse_openapi_3_0,
21
+ parse_openapi_3_1,
22
+ )
23
+ from .version_detector import detect_openapi_version
24
+
25
+
26
+ def write_code(path: Path, content: str, formatter: Formatter) -> None:
27
+ """
28
+ Write the content to the file at the given path.
29
+ :param path: The path to the file.
30
+ :param content: The content to write.
31
+ :param formatter: The formatter applied to the code written.
32
+ """
33
+ if formatter == Formatter.BLACK:
34
+ formatted_contend = format_using_black(content)
35
+ elif formatter == Formatter.NONE:
36
+ formatted_contend = content
37
+ else:
38
+ raise NotImplementedError(
39
+ f"Missing implementation for formatter {formatter!r}."
40
+ )
41
+ with open(path, "w") as f:
42
+ f.write(formatted_contend)
43
+
44
+
45
+ def format_using_black(content: str) -> str:
46
+ try:
47
+ formatted_contend = black.format_file_contents(
48
+ content,
49
+ fast=FormatOptions.skip_validation,
50
+ mode=black.FileMode(line_length=FormatOptions.line_length),
51
+ )
52
+ except NothingChanged:
53
+ return content
54
+ return isort.code(formatted_contend, line_length=FormatOptions.line_length)
55
+
56
+
57
+ def get_open_api(source: Union[str, Path]):
58
+ """
59
+ Tries to fetch the openapi specification file from the web or load from a local file.
60
+ Supports both JSON and YAML formats. Returns the according OpenAPI object.
61
+ Automatically supports OpenAPI 3.0 and 3.1 specifications with intelligent version detection.
62
+
63
+ Args:
64
+ source: URL or file path to the OpenAPI specification
65
+
66
+ Returns:
67
+ tuple: (OpenAPI object, version) where version is "3.0" or "3.1"
68
+
69
+ Raises:
70
+ FileNotFoundError: If the specified file cannot be found
71
+ ConnectError: If the URL cannot be accessed
72
+ ValidationError: If the specification is invalid
73
+ JSONDecodeError/YAMLError: If the file cannot be parsed
74
+ """
75
+ try:
76
+ # Handle remote files
77
+ if not isinstance(source, Path) and (
78
+ source.startswith("http://") or source.startswith("https://")
79
+ ):
80
+ content = httpx.get(source).text
81
+ # Try JSON first, then YAML for remote files
82
+ try:
83
+ data = orjson.loads(content)
84
+ except orjson.JSONDecodeError:
85
+ data = yaml.safe_load(content)
86
+ else:
87
+ # Handle local files
88
+ with open(source, "r") as f:
89
+ file_content = f.read()
90
+
91
+ # Try JSON first
92
+ try:
93
+ data = orjson.loads(file_content)
94
+ except orjson.JSONDecodeError:
95
+ # If JSON fails, try YAML
96
+ try:
97
+ data = yaml.safe_load(file_content)
98
+ except yaml.YAMLError as e:
99
+ click.echo(
100
+ f"File {source} is neither a valid JSON nor YAML file: {str(e)}"
101
+ )
102
+ raise
103
+
104
+ # Detect version and parse with appropriate parser
105
+ version = detect_openapi_version(data)
106
+
107
+ if version == "3.0":
108
+ openapi_obj = parse_openapi_3_0(data) # type: ignore[assignment]
109
+ elif version == "3.1":
110
+ openapi_obj = parse_openapi_3_1(data) # type: ignore[assignment]
111
+ else:
112
+ # Unsupported version detected (version detection already limited to 3.0 / 3.1)
113
+ raise ValueError(
114
+ f"Unsupported OpenAPI version: {version}. Only 3.0.x and 3.1.x are supported."
115
+ )
116
+
117
+ return openapi_obj, version
118
+
119
+ except FileNotFoundError:
120
+ click.echo(
121
+ f"File {source} not found. Please make sure to pass the path to the OpenAPI specification."
122
+ )
123
+ raise
124
+ except (ConnectError, ConnectTimeout):
125
+ click.echo(f"Could not connect to {source}.")
126
+ raise ConnectError(f"Could not connect to {source}.") from None
127
+ except ValidationError:
128
+ click.echo(f"File {source} is not a valid OpenAPI 3.0+ specification.")
129
+ raise
130
+
131
+
132
+ def write_data(
133
+ data: ConversionResult, output: Union[str, Path], formatter: Formatter
134
+ ) -> None:
135
+ """
136
+ This function will firstly create the folder structure of output, if it doesn't exist. Then it will create the
137
+ models from data.models into the models sub module of the output folder. After this, the services will be created
138
+ into the services sub module of the output folder.
139
+ :param data: The data to write.
140
+ :param output: The path to the output folder.
141
+ :param formatter: The formatter applied to the code written.
142
+ """
143
+
144
+ # Create the folder structure of the output folder.
145
+ Path(output).mkdir(parents=True, exist_ok=True)
146
+
147
+ # Create the models module.
148
+ models_path = Path(output) / "models"
149
+ models_path.mkdir(parents=True, exist_ok=True)
150
+
151
+ # Create the services module.
152
+ services_path = Path(output) / "services"
153
+ services_path.mkdir(parents=True, exist_ok=True)
154
+
155
+ files: List[str] = []
156
+
157
+ # Write the models.
158
+ for model in data.models:
159
+ files.append(model.file_name)
160
+ write_code(models_path / f"{model.file_name}.py", model.content, formatter)
161
+
162
+ # Create models.__init__.py file containing imports to all models.
163
+ write_code(
164
+ models_path / "__init__.py",
165
+ "\n".join([f"from .{file} import *" for file in files]),
166
+ formatter,
167
+ )
168
+
169
+ files = []
170
+
171
+ # Write the services.
172
+ jinja_env = create_jinja_env()
173
+ for service in data.services:
174
+ if len(service.operations) == 0:
175
+ continue
176
+ files.append(service.file_name)
177
+ write_code(
178
+ services_path / f"{service.file_name}.py",
179
+ jinja_env.get_template(SERVICE_TEMPLATE).render(**service.model_dump()),
180
+ formatter,
181
+ )
182
+
183
+ # Create services.__init__.py file containing imports to all services.
184
+ write_code(services_path / "__init__.py", "", formatter)
185
+
186
+ # Write the api_config.py file.
187
+ write_code(Path(output) / "api_config.py", data.api_config.content, formatter)
188
+
189
+ # Write the __init__.py file.
190
+ write_code(
191
+ Path(output) / "__init__.py",
192
+ "from .models import *\nfrom .services import *\nfrom .api_config import *",
193
+ formatter,
194
+ )
195
+
196
+
197
+ def generate_data(
198
+ source: Union[str, Path],
199
+ output: Union[str, Path],
200
+ library: HTTPLibrary = HTTPLibrary.httpx,
201
+ env_token_name: Optional[str] = None,
202
+ use_orjson: bool = False,
203
+ custom_template_path: Optional[str] = None,
204
+ pydantic_version: PydanticVersion = PydanticVersion.V2,
205
+ formatter: Formatter = Formatter.BLACK,
206
+ ) -> None:
207
+ """
208
+ Generate Python code from an OpenAPI 3.0+ specification.
209
+ """
210
+ openapi_obj, version = get_open_api(source)
211
+ click.echo(f"Generating data from {source} (OpenAPI {version})")
212
+
213
+ # Use version-specific generator
214
+ if version == "3.0":
215
+ result = generate_code_3_0(
216
+ openapi_obj, # type: ignore
217
+ library,
218
+ env_token_name,
219
+ use_orjson,
220
+ custom_template_path,
221
+ pydantic_version,
222
+ )
223
+ elif version == "3.1":
224
+ result = generate_code_3_1(
225
+ openapi_obj, # type: ignore
226
+ library,
227
+ env_token_name,
228
+ use_orjson,
229
+ custom_template_path,
230
+ pydantic_version,
231
+ )
232
+ else:
233
+ raise ValueError(f"Unsupported OpenAPI version: {version}")
234
+
235
+ write_data(result, output, formatter)
@@ -1,31 +1,35 @@
1
1
  from typing import Optional
2
2
 
3
- from openapi_pydantic.v3.v3_0 import OpenAPI
3
+ from openapi_pydantic.v3 import OpenAPI
4
4
 
5
5
  from openapi_python_generator.common import PydanticVersion
6
6
  from openapi_python_generator.language_converters.python.jinja_config import (
7
- API_CONFIG_TEMPLATE, API_CONFIG_TEMPLATE_PYDANTIC_V2,
8
- )
9
- from openapi_python_generator.language_converters.python.jinja_config import (
7
+ API_CONFIG_TEMPLATE,
8
+ API_CONFIG_TEMPLATE_PYDANTIC_V2,
10
9
  create_jinja_env,
11
10
  )
12
11
  from openapi_python_generator.models import APIConfig
13
12
 
14
13
 
15
14
  def generate_api_config(
16
- data: OpenAPI, env_token_name: Optional[str] = None,
17
- pydantic_version: PydanticVersion = PydanticVersion.V2,
15
+ data: OpenAPI,
16
+ env_token_name: Optional[str] = None,
17
+ pydantic_version: PydanticVersion = PydanticVersion.V2,
18
18
  ) -> APIConfig:
19
19
  """
20
20
  Generate the API model.
21
21
  """
22
22
 
23
- template_name = API_CONFIG_TEMPLATE_PYDANTIC_V2 if pydantic_version == PydanticVersion.V2 else API_CONFIG_TEMPLATE
23
+ template_name = (
24
+ API_CONFIG_TEMPLATE_PYDANTIC_V2
25
+ if pydantic_version == PydanticVersion.V2
26
+ else API_CONFIG_TEMPLATE
27
+ )
24
28
  jinja_env = create_jinja_env()
25
29
  return APIConfig(
26
30
  file_name="api_config",
27
31
  content=jinja_env.get_template(template_name).render(
28
- env_token_name=env_token_name, **data.dict()
32
+ env_token_name=env_token_name, **data.model_dump()
29
33
  ),
30
34
  base_url=data.servers[0].url if len(data.servers) > 0 else "NO SERVER",
31
35
  )
@@ -2,9 +2,8 @@ import keyword
2
2
  import re
3
3
  from typing import Optional
4
4
 
5
-
6
5
  _use_orjson: bool = False
7
- _custom_template_path: str = None
6
+ _custom_template_path: str | None = None
8
7
  _symbol_ascii_strip_re = re.compile(r"[^A-Za-z0-9_]")
9
8
 
10
9
 
@@ -1,6 +1,7 @@
1
- from typing import Optional
1
+ from typing import Optional, Union
2
2
 
3
- from openapi_pydantic.v3.v3_0 import OpenAPI
3
+ from openapi_pydantic.v3.v3_0 import OpenAPI as OpenAPI30
4
+ from openapi_pydantic.v3.v3_1 import OpenAPI as OpenAPI31
4
5
 
5
6
  from openapi_python_generator.common import PydanticVersion
6
7
  from openapi_python_generator.language_converters.python import common
@@ -13,12 +14,14 @@ from openapi_python_generator.language_converters.python.model_generator import
13
14
  from openapi_python_generator.language_converters.python.service_generator import (
14
15
  generate_services,
15
16
  )
16
- from openapi_python_generator.models import ConversionResult
17
- from openapi_python_generator.models import LibraryConfig
17
+ from openapi_python_generator.models import ConversionResult, LibraryConfig
18
+
19
+ # Type alias for both OpenAPI versions
20
+ OpenAPISpec = Union[OpenAPI30, OpenAPI31]
18
21
 
19
22
 
20
23
  def generator(
21
- data: OpenAPI,
24
+ data: OpenAPISpec,
22
25
  library_config: LibraryConfig,
23
26
  env_token_name: Optional[str] = None,
24
27
  use_orjson: bool = False,
@@ -26,7 +29,7 @@ def generator(
26
29
  pydantic_version: PydanticVersion = PydanticVersion.V2,
27
30
  ) -> ConversionResult:
28
31
  """
29
- Generate Python code from an OpenAPI 3.0 specification.
32
+ Generate Python code from an OpenAPI 3.0+ specification.
30
33
  """
31
34
 
32
35
  common.set_use_orjson(use_orjson)
@@ -1,12 +1,9 @@
1
1
  from pathlib import Path
2
2
 
3
- from jinja2 import ChoiceLoader
4
- from jinja2 import Environment
5
- from jinja2 import FileSystemLoader
3
+ from jinja2 import ChoiceLoader, Environment, FileSystemLoader
6
4
 
7
5
  from . import common
8
6
 
9
-
10
7
  ENUM_TEMPLATE = "enum.jinja2"
11
8
  MODELS_TEMPLATE = "models.jinja2"
12
9
  MODELS_TEMPLATE_PYDANTIC_V2 = "models_pydantic_2.jinja2"