From b0bae52001821dbd91735098f012e03f41c8364d Mon Sep 17 00:00:00 2001 From: Artem Khromov Date: Thu, 9 Jan 2025 04:30:25 +0300 Subject: [PATCH 1/5] Better --- chaotic-openapi/chaotic_openapi/_parser.py | 16 + .../chaotic_openapi/front/__init__.py | 361 ++ chaotic-openapi/chaotic_openapi/front/cli.py | 49 + .../chaotic_openapi/front/config.py | 123 + .../chaotic_openapi/front/opa.yaml | 176 + .../chaotic_openapi/front/parser/__init__.py | 5 + .../chaotic_openapi/front/parser/bodies.py | 146 + .../chaotic_openapi/front/parser/errors.py | 46 + .../chaotic_openapi/front/parser/openapi.py | 541 +++ .../front/parser/properties/__init__.py | 459 +++ .../front/parser/properties/any.py | 51 + .../front/parser/properties/boolean.py | 67 + .../front/parser/properties/const.py | 118 + .../front/parser/properties/date.py | 73 + .../front/parser/properties/datetime.py | 75 + .../front/parser/properties/enum_property.py | 209 + .../front/parser/properties/file.py | 67 + .../front/parser/properties/float.py | 71 + .../front/parser/properties/int.py | 73 + .../front/parser/properties/list_property.py | 160 + .../properties/literal_enum_property.py | 191 + .../parser/properties/merge_properties.py | 198 + .../front/parser/properties/model_property.py | 444 +++ .../front/parser/properties/none.py | 61 + .../front/parser/properties/property.py | 41 + .../front/parser/properties/protocol.py | 187 + .../front/parser/properties/schemas.py | 242 ++ .../front/parser/properties/string.py | 68 + .../front/parser/properties/union.py | 191 + .../front/parser/properties/uuid.py | 80 + .../chaotic_openapi/front/parser/responses.py | 150 + .../chaotic_openapi/front/schema/3.0.3.md | 3454 ++++++++++++++++ .../chaotic_openapi/front/schema/3.1.0.md | 3468 +++++++++++++++++ .../chaotic_openapi/front/schema/__init__.py | 31 + .../chaotic_openapi/front/schema/data_type.py | 18 + .../schema/openapi_schema_pydantic/LICENSE | 21 + .../schema/openapi_schema_pydantic/README.md | 42 + .../openapi_schema_pydantic/__init__.py | 83 + .../openapi_schema_pydantic/callback.py | 15 + .../openapi_schema_pydantic/components.py | 103 + .../schema/openapi_schema_pydantic/contact.py | 24 + .../openapi_schema_pydantic/discriminator.py | 36 + .../openapi_schema_pydantic/encoding.py | 41 + .../schema/openapi_schema_pydantic/example.py | 30 + .../external_documentation.py | 18 + .../schema/openapi_schema_pydantic/header.py | 33 + .../schema/openapi_schema_pydantic/info.py | 44 + .../schema/openapi_schema_pydantic/license.py | 21 + .../schema/openapi_schema_pydantic/link.py | 43 + .../openapi_schema_pydantic/media_type.py | 57 + .../openapi_schema_pydantic/oauth_flow.py | 34 + .../openapi_schema_pydantic/oauth_flows.py | 21 + .../openapi_schema_pydantic/open_api.py | 49 + .../openapi_schema_pydantic/operation.py | 89 + .../openapi_schema_pydantic/parameter.py | 89 + .../openapi_schema_pydantic/path_item.py | 76 + .../schema/openapi_schema_pydantic/paths.py | 14 + .../openapi_schema_pydantic/reference.py | 26 + .../openapi_schema_pydantic/request_body.py | 70 + .../openapi_schema_pydantic/response.py | 61 + .../openapi_schema_pydantic/responses.py | 23 + .../schema/openapi_schema_pydantic/schema.py | 208 + .../security_requirement.py | 20 + .../security_scheme.py | 49 + .../schema/openapi_schema_pydantic/server.py | 39 + .../server_variable.py | 17 + .../schema/openapi_schema_pydantic/tag.py | 23 + .../schema/openapi_schema_pydantic/xml.py | 32 + .../front/schema/parameter_location.py | 25 + .../chaotic_openapi/front/utils.py | 122 + 70 files changed, 13408 insertions(+) create mode 100644 chaotic-openapi/chaotic_openapi/_parser.py create mode 100644 chaotic-openapi/chaotic_openapi/front/__init__.py create mode 100644 chaotic-openapi/chaotic_openapi/front/cli.py create mode 100644 chaotic-openapi/chaotic_openapi/front/config.py create mode 100644 chaotic-openapi/chaotic_openapi/front/opa.yaml create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/__init__.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/bodies.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/errors.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/openapi.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/any.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/const.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/date.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/file.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/float.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/int.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/none.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/property.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/string.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/union.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py create mode 100644 chaotic-openapi/chaotic_openapi/front/parser/responses.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/3.0.3.md create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/3.1.0.md create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/__init__.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/data_type.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/LICENSE create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/__init__.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/contact.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/example.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/external_documentation.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/header.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/info.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/license.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flows.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/reference.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_scheme.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/tag.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/xml.py create mode 100644 chaotic-openapi/chaotic_openapi/front/schema/parameter_location.py create mode 100644 chaotic-openapi/chaotic_openapi/front/utils.py diff --git a/chaotic-openapi/chaotic_openapi/_parser.py b/chaotic-openapi/chaotic_openapi/_parser.py new file mode 100644 index 000000000000..66828ccedf2c --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/_parser.py @@ -0,0 +1,16 @@ +from typing import Any, Union, Dict +from front.parser import GeneratorData +from front.config import Config, ConfigFile, MetaType +from pathlib import Path + +def parse(data_dict: Dict[str, Any], config: Config): + return GeneratorData.from_dict(data_dict, config=config) + +def config(): + return Config.from_sources(ConfigFile(), MetaType.NONE, Path("opa.yaml"), 'utf-8', False, None) + +from front import _get_document + +conf = config() + +print(parse(_get_document(conf.document_source), conf)) diff --git a/chaotic-openapi/chaotic_openapi/front/__init__.py b/chaotic-openapi/chaotic_openapi/front/__init__.py new file mode 100644 index 000000000000..3823906156a3 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/__init__.py @@ -0,0 +1,361 @@ +"""Generate modern Python clients from OpenAPI""" + +import json +import mimetypes +import shutil +import subprocess +from collections.abc import Sequence +from importlib.metadata import version +from pathlib import Path +from subprocess import CalledProcessError +from typing import Any, Optional, Union, List, Dict + +import httpcore +import httpx +from jinja2 import BaseLoader, ChoiceLoader, Environment, FileSystemLoader, PackageLoader +from ruamel.yaml import YAML +from ruamel.yaml.error import YAMLError + +from openapi_python_client import utils + +from .config import Config, MetaType +from .parser import GeneratorData, import_string_from_class +from .parser.errors import ErrorLevel, GeneratorError +from .parser.properties import LiteralEnumProperty + +__version__ = version(__package__) + + +TEMPLATE_FILTERS = { + "snakecase": utils.snake_case, + "kebabcase": utils.kebab_case, + "pascalcase": utils.pascal_case, + "any": any, +} + + +class Project: + """Represents a Python project (the top level file-tree) to generate""" + + def __init__( + self, + *, + openapi: GeneratorData, + config: Config, + custom_template_path: Optional[Path] = None, + ) -> None: + self.openapi: GeneratorData = openapi + self.config = config + + package_loader = PackageLoader(__package__) + loader: BaseLoader + if custom_template_path is not None: + loader = ChoiceLoader( + [ + FileSystemLoader(str(custom_template_path)), + package_loader, + ] + ) + else: + loader = package_loader + self.env: Environment = Environment( + loader=loader, + trim_blocks=True, + lstrip_blocks=True, + extensions=["jinja2.ext.loopcontrols"], + keep_trailing_newline=True, + ) + + self.project_name: str = config.project_name_override or f"{utils.kebab_case(openapi.title).lower()}-client" + self.package_name: str = config.package_name_override or self.project_name.replace("-", "_") + self.project_dir: Path # Where the generated code will be placed + self.package_dir: Path # Where the generated Python module will be placed (same as project_dir if no meta) + + if config.output_path is not None: + self.project_dir = config.output_path + elif config.meta_type == MetaType.NONE: + self.project_dir = Path.cwd() / self.package_name + else: + self.project_dir = Path.cwd() / self.project_name + + if config.meta_type == MetaType.NONE: + self.package_dir = self.project_dir + else: + self.package_dir = self.project_dir / self.package_name + + self.package_description: str = utils.remove_string_escapes( + f"A client library for accessing {self.openapi.title}" + ) + self.version: str = config.package_version_override or openapi.version + + self.env.filters.update(TEMPLATE_FILTERS) + self.env.globals.update( + utils=utils, + python_identifier=lambda x: utils.PythonIdentifier(x, config.field_prefix), + class_name=lambda x: utils.ClassName(x, config.field_prefix), + package_name=self.package_name, + package_dir=self.package_dir, + package_description=self.package_description, + package_version=self.version, + project_name=self.project_name, + project_dir=self.project_dir, + openapi=self.openapi, + endpoint_collections_by_tag=self.openapi.endpoint_collections_by_tag, + ) + self.errors: List[GeneratorError] = [] + + def build(self) -> Sequence[GeneratorError]: + """Create the project from templates""" + + print(f"Generating {self.project_dir}") + try: + self.project_dir.mkdir() + except FileExistsError: + if not self.config.overwrite: + return [GeneratorError(detail="Directory already exists. Delete it or use the --overwrite option.")] + self._create_package() + self._build_metadata() + self._build_models() + self._build_api() + self._run_post_hooks() + return self._get_errors() + + def _run_post_hooks(self) -> None: + for command in self.config.post_hooks: + self._run_command(command) + + def _run_command(self, cmd: str) -> None: + cmd_name = cmd.split(" ")[0] + command_exists = shutil.which(cmd_name) + if not command_exists: + self.errors.append( + GeneratorError( + level=ErrorLevel.WARNING, header="Skipping Integration", detail=f"{cmd_name} is not in PATH" + ) + ) + return + try: + cwd = self.project_dir + subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, check=True) + except CalledProcessError as err: + self.errors.append( + GeneratorError( + level=ErrorLevel.ERROR, + header=f"{cmd_name} failed", + detail=err.stderr.decode() or err.output.decode(), + ) + ) + + def _get_errors(self) -> List[GeneratorError]: + errors: List[GeneratorError] = [] + for collection in self.openapi.endpoint_collections_by_tag.values(): + errors.extend(collection.parse_errors) + errors.extend(self.openapi.errors) + errors.extend(self.errors) + return errors + + def _create_package(self) -> None: + if self.package_dir != self.project_dir: + self.package_dir.mkdir(exist_ok=True) + # Package __init__.py + package_init = self.package_dir / "__init__.py" + + package_init_template = self.env.get_template("package_init.py.jinja") + package_init.write_text(package_init_template.render(), encoding=self.config.file_encoding) + + if self.config.meta_type != MetaType.NONE: + pytyped = self.package_dir / "py.typed" + pytyped.write_text("# Marker file for PEP 561", encoding=self.config.file_encoding) + + types_template = self.env.get_template("types.py.jinja") + types_path = self.package_dir / "types.py" + types_path.write_text(types_template.render(), encoding=self.config.file_encoding) + + def _build_metadata(self) -> None: + if self.config.meta_type == MetaType.NONE: + return + + self._build_pyproject_toml() + if self.config.meta_type == MetaType.SETUP: + self._build_setup_py() + + # README.md + readme = self.project_dir / "README.md" + readme_template = self.env.get_template("README.md.jinja") + readme.write_text( + readme_template.render(poetry=self.config.meta_type == MetaType.POETRY), + encoding=self.config.file_encoding, + ) + + # .gitignore + git_ignore_path = self.project_dir / ".gitignore" + git_ignore_template = self.env.get_template(".gitignore.jinja") + git_ignore_path.write_text(git_ignore_template.render(), encoding=self.config.file_encoding) + + def _build_pyproject_toml(self) -> None: + template = "pyproject.toml.jinja" + pyproject_template = self.env.get_template(template) + pyproject_path = self.project_dir / "pyproject.toml" + pyproject_path.write_text( + pyproject_template.render(meta=self.config.meta_type), + encoding=self.config.file_encoding, + ) + + def _build_setup_py(self) -> None: + template = self.env.get_template("setup.py.jinja") + path = self.project_dir / "setup.py" + path.write_text( + template.render(), + encoding=self.config.file_encoding, + ) + + def _build_models(self) -> None: + # Generate models + models_dir = self.package_dir / "models" + shutil.rmtree(models_dir, ignore_errors=True) + models_dir.mkdir() + models_init = models_dir / "__init__.py" + imports = [] + alls = [] + + model_template = self.env.get_template("model.py.jinja") + for model in self.openapi.models: + module_path = models_dir / f"{model.class_info.module_name}.py" + module_path.write_text(model_template.render(model=model), encoding=self.config.file_encoding) + imports.append(import_string_from_class(model.class_info)) + alls.append(model.class_info.name) + + # Generate enums + str_enum_template = self.env.get_template("str_enum.py.jinja") + int_enum_template = self.env.get_template("int_enum.py.jinja") + literal_enum_template = self.env.get_template("literal_enum.py.jinja") + for enum in self.openapi.enums: + module_path = models_dir / f"{enum.class_info.module_name}.py" + if isinstance(enum, LiteralEnumProperty): + module_path.write_text(literal_enum_template.render(enum=enum), encoding=self.config.file_encoding) + elif enum.value_type is int: + module_path.write_text(int_enum_template.render(enum=enum), encoding=self.config.file_encoding) + else: + module_path.write_text(str_enum_template.render(enum=enum), encoding=self.config.file_encoding) + imports.append(import_string_from_class(enum.class_info)) + alls.append(enum.class_info.name) + + models_init_template = self.env.get_template("models_init.py.jinja") + models_init.write_text( + models_init_template.render(imports=imports, alls=alls), encoding=self.config.file_encoding + ) + + def _build_api(self) -> None: + # Generate Client + client_path = self.package_dir / "client.py" + client_template = self.env.get_template("client.py.jinja") + client_path.write_text(client_template.render(), encoding=self.config.file_encoding) + + # Generate included Errors + errors_path = self.package_dir / "errors.py" + errors_template = self.env.get_template("errors.py.jinja") + errors_path.write_text(errors_template.render(), encoding=self.config.file_encoding) + + # Generate endpoints + api_dir = self.package_dir / "api" + shutil.rmtree(api_dir, ignore_errors=True) + api_dir.mkdir() + api_init_path = api_dir / "__init__.py" + api_init_template = self.env.get_template("api_init.py.jinja") + api_init_path.write_text(api_init_template.render(), encoding=self.config.file_encoding) + + endpoint_collections_by_tag = self.openapi.endpoint_collections_by_tag + endpoint_template = self.env.get_template( + "endpoint_module.py.jinja", globals={"isbool": lambda obj: obj.get_base_type_string() == "bool"} + ) + for tag, collection in endpoint_collections_by_tag.items(): + tag_dir = api_dir / tag + tag_dir.mkdir() + + endpoint_init_path = tag_dir / "__init__.py" + endpoint_init_template = self.env.get_template("endpoint_init.py.jinja") + endpoint_init_path.write_text( + endpoint_init_template.render(endpoint_collection=collection), + encoding=self.config.file_encoding, + ) + + for endpoint in collection.endpoints: + module_path = tag_dir / f"{utils.PythonIdentifier(endpoint.name, self.config.field_prefix)}.py" + module_path.write_text( + endpoint_template.render( + endpoint=endpoint, + ), + encoding=self.config.file_encoding, + ) + + +def _get_project_for_url_or_path( + config: Config, + custom_template_path: Optional[Path] = None, +) -> Union[Project, GeneratorError]: + data_dict = _get_document(source=config.document_source, timeout=config.http_timeout) + if isinstance(data_dict, GeneratorError): + return data_dict + openapi = GeneratorData.from_dict(data_dict, config=config) + if isinstance(openapi, GeneratorError): + return openapi + return Project( + openapi=openapi, + custom_template_path=custom_template_path, + config=config, + ) + + +def generate( + *, + config: Config, + custom_template_path: Optional[Path] = None, +) -> Sequence[GeneratorError]: + """ + Generate the client library + + Returns: + A list containing any errors encountered when generating. + """ + project = _get_project_for_url_or_path( + custom_template_path=custom_template_path, + config=config, + ) + if isinstance(project, GeneratorError): + return [project] + return project.build() + + +def _load_yaml_or_json(data: bytes, content_type: Optional[str]) -> Union[Dict[str, Any], GeneratorError]: + if content_type == "application/json": + try: + return json.loads(data.decode()) + except ValueError as err: + return GeneratorError(header=f"Invalid JSON from provided source: {err}") + else: + try: + yaml = YAML(typ="safe") + return yaml.load(data) + except YAMLError as err: + return GeneratorError(header=f"Invalid YAML from provided source: {err}") + + +def _get_document(*, source: Union[str, Path], timeout: int) -> Union[Dict[str, Any], GeneratorError]: + yaml_bytes: bytes + content_type: Optional[str] + if isinstance(source, str): + try: + response = httpx.get(source, timeout=timeout) + yaml_bytes = response.content + if "content-type" in response.headers: + content_type = response.headers["content-type"].split(";")[0] + else: # pragma: no cover + content_type = mimetypes.guess_type(source, strict=True)[0] + + except (httpx.HTTPError, httpcore.NetworkError): + return GeneratorError(header="Could not get OpenAPI document from provided URL") + else: + yaml_bytes = source.read_bytes() + content_type = mimetypes.guess_type(source.absolute().as_uri(), strict=True)[0] + + return _load_yaml_or_json(yaml_bytes, content_type) diff --git a/chaotic-openapi/chaotic_openapi/front/cli.py b/chaotic-openapi/chaotic_openapi/front/cli.py new file mode 100644 index 000000000000..6cfe3ba68bf1 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/cli.py @@ -0,0 +1,49 @@ +import codecs +from collections.abc import Sequence +from pathlib import Path +from pprint import pformat +from typing import Optional, Union + +import typer + +from openapi_python_client import MetaType +from openapi_python_client.config import Config, ConfigFile +from openapi_python_client.parser.errors import ErrorLevel, GeneratorError, ParseError + +def _process_config( + *, + url: Optional[str], + path: Optional[Path], + config_path: Optional[Path], + meta_type: MetaType, + file_encoding: str, + overwrite: bool, + output_path: Optional[Path], +) -> Config: + source: Union[Path, str] + if url and not path: + source = url + elif path and not url: + source = path + elif url and path: + typer.secho("Provide either --url or --path, not both", fg=typer.colors.RED) + raise typer.Exit(code=1) + else: + typer.secho("You must either provide --url or --path", fg=typer.colors.RED) + raise typer.Exit(code=1) + + try: + codecs.getencoder(file_encoding) + except LookupError as err: + typer.secho(f"Unknown encoding : {file_encoding}", fg=typer.colors.RED) + raise typer.Exit(code=1) from err + + if not config_path: + config_file = ConfigFile() + else: + try: + config_file = ConfigFile.load_from_path(path=config_path) + except Exception as err: + raise typer.BadParameter("Unable to parse config") from err + + return Config.from_sources(config_file, meta_type, source, file_encoding, overwrite, output_path=output_path) diff --git a/chaotic-openapi/chaotic_openapi/front/config.py b/chaotic-openapi/chaotic_openapi/front/config.py new file mode 100644 index 000000000000..82b4e05640a5 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/config.py @@ -0,0 +1,123 @@ +import json +import mimetypes +from enum import Enum +from pathlib import Path +from typing import Optional, Union, Dict, List + +from attr import define +from pydantic import BaseModel +from ruamel.yaml import YAML + + +class ClassOverride(BaseModel): + """An override of a single generated class. + + See https://github.com/openapi-generators/openapi-python-client#class_overrides + """ + + class_name: Optional[str] = None + module_name: Optional[str] = None + + +class MetaType(str, Enum): + """The types of metadata supported for project generation.""" + + NONE = "none" + POETRY = "poetry" + SETUP = "setup" + PDM = "pdm" + + +class ConfigFile(BaseModel): + """Contains any configurable values passed via a config file. + + See https://github.com/openapi-generators/openapi-python-client#configuration + """ + + class_overrides: Optional[Dict[str, ClassOverride]] = None + content_type_overrides: Optional[Dict[str, str]] = None + project_name_override: Optional[str] = None + package_name_override: Optional[str] = None + package_version_override: Optional[str] = None + use_path_prefixes_for_title_model_names: bool = True + post_hooks: Optional[List[str]] = None + field_prefix: str = "field_" + generate_all_tags: bool = False + http_timeout: int = 5 + literal_enums: bool = False + + @staticmethod + def load_from_path(path: Path) -> "ConfigFile": + """Creates a Config from provided JSON or YAML file and sets a bunch of globals from it""" + mime = mimetypes.guess_type(path.absolute().as_uri(), strict=True)[0] + if mime == "application/json": + config_data = json.loads(path.read_text()) + else: + yaml = YAML(typ="safe") + config_data = yaml.load(path) + config = ConfigFile(**config_data) + return config + + +@define +class Config: + """Contains all the config values for the generator, from files, defaults, and CLI arguments.""" + + meta_type: MetaType + class_overrides: Dict[str, ClassOverride] + project_name_override: Optional[str] + package_name_override: Optional[str] + package_version_override: Optional[str] + use_path_prefixes_for_title_model_names: bool + post_hooks: List[str] + field_prefix: str + generate_all_tags: bool + http_timeout: int + literal_enums: bool + document_source: Union[Path, str] + file_encoding: str + content_type_overrides: Dict[str, str] + overwrite: bool + output_path: Optional[Path] + + @staticmethod + def from_sources( + config_file: ConfigFile, + meta_type: MetaType, + document_source: Union[Path, str], + file_encoding: str, + overwrite: bool, + output_path: Optional[Path], + ) -> "Config": + if config_file.post_hooks is not None: + post_hooks = config_file.post_hooks + elif meta_type == MetaType.NONE: + post_hooks = [ + "ruff check . --fix --extend-select=I", + "ruff format .", + ] + else: + post_hooks = [ + "ruff check --fix .", + "ruff format .", + ] + + config = Config( + meta_type=meta_type, + class_overrides=config_file.class_overrides or {}, + content_type_overrides=config_file.content_type_overrides or {}, + project_name_override=config_file.project_name_override, + package_name_override=config_file.package_name_override, + package_version_override=config_file.package_version_override, + use_path_prefixes_for_title_model_names=config_file.use_path_prefixes_for_title_model_names, + post_hooks=post_hooks, + field_prefix=config_file.field_prefix, + generate_all_tags=config_file.generate_all_tags, + http_timeout=config_file.http_timeout, + literal_enums=config_file.literal_enums, + document_source=document_source, + file_encoding=file_encoding, + overwrite=overwrite, + output_path=output_path, + ) + return config diff --git a/chaotic-openapi/chaotic_openapi/front/opa.yaml b/chaotic-openapi/chaotic_openapi/front/opa.yaml new file mode 100644 index 000000000000..ab1ac6ddb376 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/opa.yaml @@ -0,0 +1,176 @@ +openapi: 3.0.3 +info: + title: Key-Value Storage API + description: An API to manage a key-value store with CRUD operations and basic authentication. + version: 1.0.0 +servers: + - url: https://api.kvstore.example.com/v1 + description: Production server + - url: http://localhost:3000/v1 + description: Development server +components: + securitySchemes: + BasicAuth: + type: http + scheme: basic + schemas: + KeyValuePair: + type: object + properties: + key: + type: string + description: Unique key for the item + value: + type: string + description: Value associated with the key + required: + - key + - value + ErrorResponse: + type: object + properties: + error: + type: string + description: Error message +paths: + /kv: + get: + summary: Get all key-value pairs + description: Retrieve all key-value pairs in the store. + security: + - BasicAuth: [] + responses: + '200': + description: A list of key-value pairs + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/KeyValuePair' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + post: + summary: Create a new key-value pair + description: Add a new key-value pair to the store. + security: + - BasicAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/KeyValuePair' + responses: + '201': + description: Key-value pair created successfully + '400': + description: Bad request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /kv/{key}: + get: + summary: Get a key-value pair + description: Retrieve a value by its key. + security: + - BasicAuth: [] + parameters: + - name: key + in: path + required: true + schema: + type: string + description: The key to retrieve + responses: + '200': + description: Key-value pair retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/KeyValuePair' + '404': + description: Key not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + put: + summary: Update a key-value pair + description: Update the value associated with a specific key. + security: + - BasicAuth: [] + parameters: + - name: key + in: path + required: true + schema: + type: string + description: The key to update + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/KeyValuePair' + responses: + '200': + description: Key-value pair updated successfully + '404': + description: Key not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + delete: + summary: Delete a key-value pair + description: Remove a key-value pair from the store. + security: + - BasicAuth: [] + parameters: + - name: key + in: path + required: true + schema: + type: string + description: The key to delete + responses: + '204': + description: Key-value pair deleted successfully + '404': + description: Key not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +security: + - BasicAuth: [] \ No newline at end of file diff --git a/chaotic-openapi/chaotic_openapi/front/parser/__init__.py b/chaotic-openapi/chaotic_openapi/front/parser/__init__.py new file mode 100644 index 000000000000..9cdeb36fd76f --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/__init__.py @@ -0,0 +1,5 @@ +"""Classes representing the data in the OpenAPI schema""" + +__all__ = ["GeneratorData", "import_string_from_class"] + +from .openapi import GeneratorData, import_string_from_class diff --git a/chaotic-openapi/chaotic_openapi/front/parser/bodies.py b/chaotic-openapi/chaotic_openapi/front/parser/bodies.py new file mode 100644 index 000000000000..bf4c05c4da07 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/bodies.py @@ -0,0 +1,146 @@ +import sys +from typing import Union, Dict, List, Tuple + +import attr + +from openapi_python_client.parser.properties import ( + ModelProperty, + Property, + Schemas, + property_from_data, +) + +from .. import schema as oai +from ..config import Config +from ..utils import get_content_type +from .errors import ErrorLevel, ParseError + +if sys.version_info >= (3, 11): + from enum import StrEnum + + class BodyType(StrEnum): + JSON = "json" + DATA = "data" + FILES = "files" + CONTENT = "content" +else: + from enum import Enum + + class BodyType(str, Enum): + JSON = "json" + DATA = "data" + FILES = "files" + CONTENT = "content" + + +@attr.define +class Body: + content_type: str + prop: Property + body_type: BodyType + + +def body_from_data( + *, + data: oai.Operation, + schemas: Schemas, + request_bodies: Dict[str, Union[oai.RequestBody, oai.Reference]], + config: Config, + endpoint_name: str, +) -> Tuple[List[Union[Body, ParseError]], Schemas]: + """Adds form or JSON body to Endpoint if included in data""" + body = _resolve_reference(data.request_body, request_bodies) + if isinstance(body, ParseError): + return [body], schemas + if body is None: + return [], schemas + + bodies: List[Union[Body, ParseError]] = [] + body_content = body.content + prefix_type_names = len(body_content) > 1 + + for content_type, media_type in body_content.items(): + simplified_content_type = get_content_type(content_type, config) + if simplified_content_type is None: + bodies.append( + ParseError( + detail="Invalid content type", + data=body, + level=ErrorLevel.WARNING, + ) + ) + continue + media_type_schema = media_type.media_type_schema + if media_type_schema is None: + bodies.append( + ParseError( + detail="Missing schema", + data=body, + level=ErrorLevel.WARNING, + ) + ) + continue + if simplified_content_type == "application/x-www-form-urlencoded": + body_type = BodyType.DATA + elif simplified_content_type == "multipart/form-data": + body_type = BodyType.FILES + elif simplified_content_type == "application/octet-stream": + body_type = BodyType.CONTENT + elif simplified_content_type == "application/json" or simplified_content_type.endswith("+json"): + body_type = BodyType.JSON + else: + bodies.append( + ParseError( + detail=f"Unsupported content type {simplified_content_type}", + data=body, + level=ErrorLevel.WARNING, + ) + ) + continue + prop, schemas = property_from_data( + name="body", + required=True, + data=media_type_schema, + schemas=schemas, + parent_name=f"{endpoint_name}_{body_type}" if prefix_type_names else endpoint_name, + config=config, + ) + if isinstance(prop, ParseError): + bodies.append(prop) + continue + if isinstance(prop, ModelProperty) and body_type == BodyType.FILES: + # Regardless of if we just made this property or found it, it now needs the `to_multipart` method + prop = attr.evolve(prop, is_multipart_body=True) + schemas = attr.evolve( + schemas, + classes_by_name={ + **schemas.classes_by_name, + prop.class_info.name: prop, + }, + models_to_process=[*schemas.models_to_process, prop], + ) + bodies.append( + Body( + content_type=content_type, + prop=prop, + body_type=body_type, + ) + ) + + return bodies, schemas + + +def _resolve_reference( + body: Union[oai.RequestBody, oai.Reference, None], request_bodies: Dict[str, Union[oai.RequestBody, oai.Reference]] +) -> Union[oai.RequestBody, ParseError, None]: + if body is None: + return None + references_seen = [] + while isinstance(body, oai.Reference) and body.ref not in references_seen: + references_seen.append(body.ref) + body = request_bodies.get(body.ref.split("/")[-1]) + if isinstance(body, oai.Reference): + return ParseError(detail="Circular $ref in request body", data=body) + if body is None and references_seen: + return ParseError(detail=f"Could not resolve $ref {references_seen[-1]} in request body") + return body diff --git a/chaotic-openapi/chaotic_openapi/front/parser/errors.py b/chaotic-openapi/chaotic_openapi/front/parser/errors.py new file mode 100644 index 000000000000..36322f0cfbc5 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/errors.py @@ -0,0 +1,46 @@ +from dataclasses import dataclass +from enum import Enum +from typing import Optional + +__all__ = ["ErrorLevel", "GeneratorError", "ParameterError", "ParseError", "PropertyError"] + +from pydantic import BaseModel + + +class ErrorLevel(Enum): + """The level of an error""" + + WARNING = "WARNING" # Client is still generated but missing some pieces + ERROR = "ERROR" # Client could not be generated + + +@dataclass +class GeneratorError: + """Base data struct containing info on an error that occurred""" + + detail: Optional[str] = None + level: ErrorLevel = ErrorLevel.ERROR + header: str = "Unable to generate the client" + + +@dataclass +class ParseError(GeneratorError): + """An error raised when there's a problem parsing an OpenAPI document""" + + level: ErrorLevel = ErrorLevel.WARNING + data: Optional[BaseModel] = None + header: str = "Unable to parse this part of your OpenAPI document: " + + +@dataclass +class PropertyError(ParseError): + """Error raised when there's a problem creating a Property""" + + header = "Problem creating a Property: " + + +@dataclass +class ParameterError(ParseError): + """Error raised when there's a problem creating a Parameter.""" + + header = "Problem creating a Parameter: " diff --git a/chaotic-openapi/chaotic_openapi/front/parser/openapi.py b/chaotic-openapi/chaotic_openapi/front/parser/openapi.py new file mode 100644 index 000000000000..cd3056eb6930 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/openapi.py @@ -0,0 +1,541 @@ +import re +from typing import Iterator +from copy import deepcopy +from dataclasses import dataclass, field +from http import HTTPStatus +from typing import Any, Optional, Protocol, Union, List, Dict, Tuple, Set + +from pydantic import ValidationError + +from .. import schema as oai +from .. import utils +from ..config import Config +from ..utils import PythonIdentifier +from .bodies import Body, body_from_data +from .errors import GeneratorError, ParseError, PropertyError +from .properties import ( + Class, + EnumProperty, + LiteralEnumProperty, + ModelProperty, + Parameters, + Property, + Schemas, + build_parameters, + build_schemas, + property_from_data, +) +from .properties.schemas import parameter_from_reference +from .responses import Response, response_from_data + +_PATH_PARAM_REGEX = re.compile("{([a-zA-Z_-][a-zA-Z0-9_-]*)}") + + +def import_string_from_class(class_: Class, prefix: str = "") -> str: + """Create a string which is used to import a reference""" + return f"from {prefix}.{class_.module_name} import {class_.name}" + + +@dataclass +class EndpointCollection: + """A bunch of endpoints grouped under a tag that will become a module""" + + tag: str + endpoints: List["Endpoint"] = field(default_factory=list) + parse_errors: List[ParseError] = field(default_factory=list) + + @staticmethod + def from_data( + *, + data: Dict[str, oai.PathItem], + schemas: Schemas, + parameters: Parameters, + request_bodies: Dict[str, Union[oai.RequestBody, oai.Reference]], + config: Config, + ) -> Tuple[Dict[utils.PythonIdentifier, "EndpointCollection"], Schemas, Parameters]: + """Parse the openapi paths data to get EndpointCollections by tag""" + endpoints_by_tag: Dict[utils.PythonIdentifier, EndpointCollection] = {} + + methods = ["get", "put", "post", "delete", "options", "head", "patch", "trace"] + + for path, path_data in data.items(): + for method in methods: + operation: Optional[oai.Operation] = getattr(path_data, method) + if operation is None: + continue + + tags = [utils.PythonIdentifier(value=tag, prefix="tag") for tag in operation.tags or ["default"]] + if not config.generate_all_tags: + tags = tags[:1] + + collections = [endpoints_by_tag.setdefault(tag, EndpointCollection(tag=tag)) for tag in tags] + + endpoint, schemas, parameters = Endpoint.from_data( + data=operation, + path=path, + method=method, + tags=tags, + schemas=schemas, + parameters=parameters, + request_bodies=request_bodies, + config=config, + ) + # Add `PathItem` parameters + if not isinstance(endpoint, ParseError): + endpoint, schemas, parameters = Endpoint.add_parameters( + endpoint=endpoint, + data=path_data, + schemas=schemas, + parameters=parameters, + config=config, + ) + if not isinstance(endpoint, ParseError): + endpoint = Endpoint.sort_parameters(endpoint=endpoint) + if isinstance(endpoint, ParseError): + endpoint.header = f"WARNING parsing {method.upper()} {path} within {'/'.join(tags)}. Endpoint will not be generated." + for collection in collections: + collection.parse_errors.append(endpoint) + continue + for error in endpoint.errors: + error.header = f"WARNING parsing {method.upper()} {path} within {'/'.join(tags)}." + for collection in collections: + collection.parse_errors.append(error) + for collection in collections: + collection.endpoints.append(endpoint) + + return endpoints_by_tag, schemas, parameters + + +def generate_operation_id(*, path: str, method: str) -> str: + """Generate an operationId from a path""" + clean_path = path.replace("{", "").replace("}", "").replace("/", "_") + if clean_path.startswith("_"): + clean_path = clean_path[1:] + if clean_path.endswith("_"): + clean_path = clean_path[:-1] + return f"{method}_{clean_path}" + + +models_relative_prefix: str = "..." + + +class RequestBodyParser(Protocol): + __name__: str = "RequestBodyParser" + + def __call__( + self, *, body: oai.RequestBody, schemas: Schemas, parent_name: str, config: Config + ) -> Tuple[Union[Property, PropertyError, None], Schemas]: ... # pragma: no cover + + +@dataclass +class Endpoint: + """ + Describes a single endpoint on the server + """ + + path: str + method: str + description: Optional[str] + name: str + requires_security: bool + tags: List[PythonIdentifier] + summary: Optional[str] = "" + relative_imports: Set[str] = field(default_factory=set) + query_parameters: List[Property] = field(default_factory=list) + path_parameters: List[Property] = field(default_factory=list) + header_parameters: List[Property] = field(default_factory=list) + cookie_parameters: List[Property] = field(default_factory=list) + responses: List[Response] = field(default_factory=list) + bodies: List[Body] = field(default_factory=list) + errors: List[ParseError] = field(default_factory=list) + + @staticmethod + def _add_responses( + *, endpoint: "Endpoint", data: oai.Responses, schemas: Schemas, config: Config + ) -> Tuple["Endpoint", Schemas]: + endpoint = deepcopy(endpoint) + for code, response_data in data.items(): + status_code: HTTPStatus + try: + status_code = HTTPStatus(int(code)) + except ValueError: + endpoint.errors.append( + ParseError( + detail=( + f"Invalid response status code {code} (not a valid HTTP " + f"status code), response will be omitted from generated " + f"client" + ) + ) + ) + continue + + response, schemas = response_from_data( + status_code=status_code, + data=response_data, + schemas=schemas, + parent_name=endpoint.name, + config=config, + ) + if isinstance(response, ParseError): + detail_suffix = "" if response.detail is None else f" ({response.detail})" + endpoint.errors.append( + ParseError( + detail=( + f"Cannot parse response for status code {status_code}{detail_suffix}, " + f"response will be omitted from generated client" + ), + data=response.data, + ) + ) + continue + + # No reasons to use lazy imports in endpoints, so add lazy imports to relative here. + endpoint.relative_imports |= response.prop.get_lazy_imports(prefix=models_relative_prefix) + endpoint.relative_imports |= response.prop.get_imports(prefix=models_relative_prefix) + endpoint.responses.append(response) + return endpoint, schemas + + @staticmethod + def add_parameters( + *, + endpoint: "Endpoint", + data: Union[oai.Operation, oai.PathItem], + schemas: Schemas, + parameters: Parameters, + config: Config, + ) -> Tuple[Union["Endpoint", ParseError], Schemas, Parameters]: + """Process the defined `parameters` for an Endpoint. + + Any existing parameters will be ignored, so earlier instances of a parameter take precedence. PathItem + parameters should therefore be added __after__ operation parameters. + + Args: + endpoint: The endpoint to add parameters to. + data: The Operation or PathItem to add parameters from. + schemas: The cumulative Schemas of processing so far which should contain details for any references. + parameters: The cumulative Parameters of processing so far which should contain details for any references. + config: User-provided config for overrides within parameters. + + Returns: + `(result, schemas, parameters)` where `result` is either an updated Endpoint containing the parameters or a + ParseError describing what went wrong. `schemas` is an updated version of the `schemas` input, adding any + new enums or classes. `parameters` is an updated version of the `parameters` input, adding new parameters. + + See Also: + - https://swagger.io/docs/specification/describing-parameters/ + - https://swagger.io/docs/specification/paths-and-operations/ + """ + # There isn't much value in breaking down this function further other than to satisfy the linter. + + if data.parameters is None: + return endpoint, schemas, parameters + + endpoint = deepcopy(endpoint) + + unique_parameters: Set[Tuple[str, oai.ParameterLocation]] = set() + parameters_by_location: Dict[str, List[Property]] = { + oai.ParameterLocation.QUERY: endpoint.query_parameters, + oai.ParameterLocation.PATH: endpoint.path_parameters, + oai.ParameterLocation.HEADER: endpoint.header_parameters, + oai.ParameterLocation.COOKIE: endpoint.cookie_parameters, + } + + for param in data.parameters: + # Obtain the parameter from the reference or just the parameter itself + param_or_error = parameter_from_reference(param=param, parameters=parameters) + if isinstance(param_or_error, ParseError): + return param_or_error, schemas, parameters + param = param_or_error # noqa: PLW2901 + + if param.param_schema is None: + continue + + unique_param = (param.name, param.param_in) + if unique_param in unique_parameters: + return ( + ParseError( + data=data, + detail=( + "Parameters MUST NOT contain duplicates. " + "A unique parameter is defined by a combination of a name and location. " + f"Duplicated parameters named `{param.name}` detected in `{param.param_in}`." + ), + ), + schemas, + parameters, + ) + + unique_parameters.add(unique_param) + + if any( + other_param for other_param in parameters_by_location[param.param_in] if other_param.name == param.name + ): + # Defined at the operation level, ignore it here + continue + + prop, new_schemas = property_from_data( + name=param.name, + required=param.required, + data=param.param_schema, + schemas=schemas, + parent_name=endpoint.name, + config=config, + ) + + if isinstance(prop, ParseError): + return ( + ParseError( + detail=f"cannot parse parameter of endpoint {endpoint.name}: {prop.detail}", + data=prop.data, + ), + schemas, + parameters, + ) + + schemas = new_schemas + + location_error = prop.validate_location(param.param_in) + if location_error is not None: + location_error.data = param + return location_error, schemas, parameters + + # No reasons to use lazy imports in endpoints, so add lazy imports to relative here. + endpoint.relative_imports.update(prop.get_lazy_imports(prefix=models_relative_prefix)) + endpoint.relative_imports.update(prop.get_imports(prefix=models_relative_prefix)) + parameters_by_location[param.param_in].append(prop) + + return endpoint._check_parameters_for_conflicts(config=config), schemas, parameters + + def _check_parameters_for_conflicts( + self, + *, + config: Config, + previously_modified_params: Optional[Set[Tuple[oai.ParameterLocation, str]]] = None, + ) -> Union["Endpoint", ParseError]: + """Check for conflicting parameters + + For parameters that have the same python_name but are in different locations, append the location to the + python_name. For parameters that have the same name but are in the same location, use their raw name without + snake casing instead. + + Function stops when there's a conflict that can't be resolved or all parameters are guaranteed to have a + unique python_name. + """ + modified_params = previously_modified_params or set() + used_python_names: Dict[PythonIdentifier, Tuple[oai.ParameterLocation, Property]] = {} + reserved_names = ["client", "url"] + for parameter in self.iter_all_parameters(): + location, prop = parameter + + if prop.python_name in reserved_names: + prop.set_python_name(new_name=f"{prop.python_name}_{location}", config=config) + modified_params.add((location, prop.name)) + continue + + conflicting = used_python_names.pop(prop.python_name, None) + if conflicting is None: + used_python_names[prop.python_name] = parameter + continue + conflicting_location, conflicting_prop = conflicting + if (conflicting_location, conflicting_prop.name) in modified_params or ( + location, + prop.name, + ) in modified_params: + return ParseError( + detail=f"Parameters with same Python identifier {conflicting_prop.python_name} detected", + ) + + if location != conflicting_location: + conflicting_prop.set_python_name( + new_name=f"{conflicting_prop.python_name}_{conflicting_location}", config=config + ) + prop.set_python_name(new_name=f"{prop.python_name}_{location}", config=config) + elif conflicting_prop.name != prop.name: # Use the name to differentiate + conflicting_prop.set_python_name(new_name=conflicting_prop.name, config=config, skip_snake_case=True) + prop.set_python_name(new_name=prop.name, config=config, skip_snake_case=True) + + modified_params.add((location, conflicting_prop.name)) + modified_params.add((conflicting_location, conflicting_prop.name)) + used_python_names[prop.python_name] = parameter + used_python_names[conflicting_prop.python_name] = conflicting + + if len(modified_params) > 0 and modified_params != previously_modified_params: + return self._check_parameters_for_conflicts(config=config, previously_modified_params=modified_params) + return self + + @staticmethod + def sort_parameters(*, endpoint: "Endpoint") -> Union["Endpoint", ParseError]: + """ + Sorts the path parameters of an `endpoint` so that they match the order declared in `endpoint.path`. + + Args: + endpoint: The endpoint to sort the parameters of. + + Returns: + Either an updated `endpoint` with sorted path parameters or a `ParseError` if something was wrong with + the path parameters and they could not be sorted. + """ + endpoint = deepcopy(endpoint) + parameters_from_path = re.findall(_PATH_PARAM_REGEX, endpoint.path) + try: + endpoint.path_parameters.sort( + key=lambda param: parameters_from_path.index(param.name), + ) + except ValueError: + pass # We're going to catch the difference down below + + if parameters_from_path != [param.name for param in endpoint.path_parameters]: + return ParseError( + detail=f"Incorrect path templating for {endpoint.path} (Path parameters do not match with path)", + ) + for parameter in endpoint.path_parameters: + endpoint.path = endpoint.path.replace(f"{{{parameter.name}}}", f"{{{parameter.python_name}}}") + return endpoint + + @staticmethod + def from_data( + *, + data: oai.Operation, + path: str, + method: str, + tags: List[PythonIdentifier], + schemas: Schemas, + parameters: Parameters, + request_bodies: Dict[str, Union[oai.RequestBody, oai.Reference]], + config: Config, + ) -> Tuple[Union["Endpoint", ParseError], Schemas, Parameters]: + """Construct an endpoint from the OpenAPI data""" + + if data.operationId is None: + name = generate_operation_id(path=path, method=method) + else: + name = data.operationId + + endpoint = Endpoint( + path=path, + method=method, + summary=utils.remove_string_escapes(data.summary) if data.summary else "", + description=utils.remove_string_escapes(data.description) if data.description else "", + name=name, + requires_security=bool(data.security), + tags=tags, + ) + + result, schemas, parameters = Endpoint.add_parameters( + endpoint=endpoint, + data=data, + schemas=schemas, + parameters=parameters, + config=config, + ) + if isinstance(result, ParseError): + return result, schemas, parameters + result, schemas = Endpoint._add_responses(endpoint=result, data=data.responses, schemas=schemas, config=config) + if isinstance(result, ParseError): + return result, schemas, parameters + bodies, schemas = body_from_data( + data=data, schemas=schemas, config=config, endpoint_name=result.name, request_bodies=request_bodies + ) + body_errors = [] + for body in bodies: + if isinstance(body, ParseError): + body_errors.append(body) + continue + result.bodies.append(body) + result.relative_imports.update(body.prop.get_imports(prefix=models_relative_prefix)) + result.relative_imports.update(body.prop.get_lazy_imports(prefix=models_relative_prefix)) + if len(result.bodies) > 0: + result.errors.extend(body_errors) + elif len(body_errors) > 0: + return ( + ParseError( + header="Endpoint requires a body, but none were parseable.", + detail="\n".join(error.detail or "" for error in body_errors), + ), + schemas, + parameters, + ) + + return result, schemas, parameters + + def response_type(self) -> str: + """Get the Python type of any response from this endpoint""" + types = sorted({response.prop.get_type_string(quoted=False) for response in self.responses}) + if len(types) == 0: + return "Any" + if len(types) == 1: + return self.responses[0].prop.get_type_string(quoted=False) + return f"Union[{', '.join(types)}]" + + def iter_all_parameters(self) -> Iterator[Tuple[oai.ParameterLocation, Property]]: + """Iterate through all the parameters of this endpoint""" + yield from ((oai.ParameterLocation.PATH, param) for param in self.path_parameters) + yield from ((oai.ParameterLocation.QUERY, param) for param in self.query_parameters) + yield from ((oai.ParameterLocation.HEADER, param) for param in self.header_parameters) + yield from ((oai.ParameterLocation.COOKIE, param) for param in self.cookie_parameters) + + def list_all_parameters(self) -> List[Property]: + """Return a list of all the parameters of this endpoint""" + return ( + self.path_parameters + + self.query_parameters + + self.header_parameters + + self.cookie_parameters + + [body.prop for body in self.bodies] + ) + + +@dataclass +class GeneratorData: + """All the data needed to generate a client""" + + title: str + description: Optional[str] + version: str + models: Iterator[ModelProperty] + errors: List[ParseError] + endpoint_collections_by_tag: Dict[utils.PythonIdentifier, EndpointCollection] + enums: Iterator[Union[EnumProperty, LiteralEnumProperty]] + + @staticmethod + def from_dict(data: Dict[str, Any], *, config: Config) -> Union["GeneratorData", GeneratorError]: + """Create an OpenAPI from dict""" + try: + openapi = oai.OpenAPI.model_validate(data) + except ValidationError as err: + detail = str(err) + if "swagger" in data: + detail = ( + "You may be trying to use a Swagger document; this is not supported by this project.\n\n" + detail + ) + return GeneratorError(header="Failed to parse OpenAPI document", detail=detail) + schemas = Schemas() + parameters = Parameters() + if openapi.components and openapi.components.schemas: + schemas = build_schemas(components=openapi.components.schemas, schemas=schemas, config=config) + if openapi.components and openapi.components.parameters: + parameters = build_parameters( + components=openapi.components.parameters, + parameters=parameters, + config=config, + ) + request_bodies = (openapi.components and openapi.components.requestBodies) or {} + endpoint_collections_by_tag, schemas, parameters = EndpointCollection.from_data( + data=openapi.paths, schemas=schemas, parameters=parameters, request_bodies=request_bodies, config=config + ) + + enums = ( + prop for prop in schemas.classes_by_name.values() if isinstance(prop, (EnumProperty, LiteralEnumProperty)) + ) + models = (prop for prop in schemas.classes_by_name.values() if isinstance(prop, ModelProperty)) + + return GeneratorData( + title=openapi.info.title, + description=openapi.info.description, + version=openapi.info.version, + endpoint_collections_by_tag=endpoint_collections_by_tag, + models=models, + errors=schemas.errors + parameters.errors, + enums=enums, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py new file mode 100644 index 000000000000..ec4212d9af23 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py @@ -0,0 +1,459 @@ +from __future__ import annotations + +__all__ = [ + "AnyProperty", + "Class", + "EnumProperty", + "LiteralEnumProperty", + "ModelProperty", + "Parameters", + "Property", + "Schemas", + "build_parameters", + "build_schemas", + "property_from_data", +] + +from collections.abc import Iterable + +from attrs import evolve + +from ... import Config, utils +from ... import schema as oai +from ..errors import ParameterError, ParseError, PropertyError +from .any import AnyProperty +from .boolean import BooleanProperty +from .const import ConstProperty +from .date import DateProperty +from .datetime import DateTimeProperty +from .enum_property import EnumProperty +from .file import FileProperty +from .float import FloatProperty +from .int import IntProperty +from .list_property import ListProperty +from .literal_enum_property import LiteralEnumProperty +from .model_property import ModelProperty, process_model +from .none import NoneProperty +from .property import Property +from .schemas import ( + Class, + Parameters, + ReferencePath, + Schemas, + parse_reference_path, + update_parameters_with_data, + update_schemas_with_data, +) +from .string import StringProperty +from .union import UnionProperty +from .uuid import UuidProperty + + +def _string_based_property( + name: str, required: bool, data: oai.Schema, config: Config +) -> StringProperty | DateProperty | DateTimeProperty | FileProperty | UuidProperty | PropertyError: + """Construct a Property from the type "string" """ + string_format = data.schema_format + python_name = utils.PythonIdentifier(value=name, prefix=config.field_prefix) + if string_format == "date-time": + return DateTimeProperty.build( + name=name, + required=required, + default=data.default, + python_name=python_name, + description=data.description, + example=data.example, + ) + if string_format == "date": + return DateProperty.build( + name=name, + required=required, + default=data.default, + python_name=python_name, + description=data.description, + example=data.example, + ) + if string_format == "binary": + return FileProperty.build( + name=name, + required=required, + default=None, + python_name=python_name, + description=data.description, + example=data.example, + ) + if string_format == "uuid": + return UuidProperty.build( + name=name, + required=required, + default=data.default, + python_name=python_name, + description=data.description, + example=data.example, + ) + return StringProperty.build( + name=name, + default=data.default, + required=required, + python_name=python_name, + description=data.description, + example=data.example, + ) + + +def _property_from_ref( + name: str, + required: bool, + parent: oai.Schema | None, + data: oai.Reference, + schemas: Schemas, + config: Config, + roots: Set[ReferencePath | utils.ClassName], +) -> Tuple[Property | PropertyError, Schemas]: + ref_path = parse_reference_path(data.ref) + if isinstance(ref_path, ParseError): + return PropertyError(data=data, detail=ref_path.detail), schemas + existing = schemas.classes_by_reference.get(ref_path) + if not existing: + return ( + PropertyError(data=data, detail="Could not find reference in parsed models or enums"), + schemas, + ) + + default = existing.convert_value(parent.default) if parent is not None else None + if isinstance(default, PropertyError): + default.data = parent or data + return default, schemas + + prop = evolve( + existing, + required=required, + name=name, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + default=default, # type: ignore # mypy can't tell that default comes from the same class... + ) + + schemas.add_dependencies(ref_path=ref_path, roots=roots) + return prop, schemas + + +def property_from_data( # noqa: PLR0911, PLR0912 + name: str, + required: bool, + data: oai.Reference | oai.Schema, + schemas: Schemas, + parent_name: str, + config: Config, + process_properties: bool = True, + roots: Set[ReferencePath | utils.ClassName] | None = None, +) -> Tuple[Property | PropertyError, Schemas]: + """Generate a Property from the OpenAPI dictionary representation of it""" + roots = roots or set() + name = utils.remove_string_escapes(name) + if isinstance(data, oai.Reference): + return _property_from_ref( + name=name, + required=required, + parent=None, + data=data, + schemas=schemas, + config=config, + roots=roots, + ) + + sub_data: List[oai.Schema | oai.Reference] = data.allOf + data.anyOf + data.oneOf + # A union of a single reference should just be passed through to that reference (don't create copy class) + if len(sub_data) == 1 and isinstance(sub_data[0], oai.Reference): + prop, schemas = _property_from_ref( + name=name, + required=required, + parent=data, + data=sub_data[0], + schemas=schemas, + config=config, + roots=roots, + ) + # We won't be generating a separate Python class for this schema - references to it will just use + # the class for the schema it's referencing - so we don't add it to classes_by_name; but we do + # add it to models_to_process, if it's a model, because its properties still need to be resolved. + if isinstance(prop, ModelProperty): + schemas = evolve( + schemas, + models_to_process=[*schemas.models_to_process, prop], + ) + return prop, schemas + + if data.type == oai.DataType.BOOLEAN: + return ( + BooleanProperty.build( + name=name, + required=required, + default=data.default, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ), + schemas, + ) + if data.enum: + if config.literal_enums: + return LiteralEnumProperty.build( + data=data, + name=name, + required=required, + schemas=schemas, + parent_name=parent_name, + config=config, + ) + return EnumProperty.build( + data=data, + name=name, + required=required, + schemas=schemas, + parent_name=parent_name, + config=config, + ) + if data.anyOf or data.oneOf or isinstance(data.type, list): + return UnionProperty.build( + data=data, + name=name, + required=required, + schemas=schemas, + parent_name=parent_name, + config=config, + ) + if data.const is not None: + return ( + ConstProperty.build( + name=name, + required=required, + default=data.default, + const=data.const, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + ), + schemas, + ) + if data.type == oai.DataType.STRING: + return ( + _string_based_property(name=name, required=required, data=data, config=config), + schemas, + ) + if data.type == oai.DataType.NUMBER: + return ( + FloatProperty.build( + name=name, + default=data.default, + required=required, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ), + schemas, + ) + if data.type == oai.DataType.INTEGER: + return ( + IntProperty.build( + name=name, + default=data.default, + required=required, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ), + schemas, + ) + if data.type == oai.DataType.NULL: + return ( + NoneProperty( + name=name, + required=required, + default=None, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ), + schemas, + ) + if data.type == oai.DataType.ARRAY: + return ListProperty.build( + data=data, + name=name, + required=required, + schemas=schemas, + parent_name=parent_name, + config=config, + process_properties=process_properties, + roots=roots, + ) + if data.type == oai.DataType.OBJECT or data.allOf or (data.type is None and data.properties): + return ModelProperty.build( + data=data, + name=name, + schemas=schemas, + required=required, + parent_name=parent_name, + config=config, + process_properties=process_properties, + roots=roots, + ) + return ( + AnyProperty.build( + name=name, + required=required, + default=data.default, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ), + schemas, + ) + + +def _create_schemas( + *, + components: Dict[str, oai.Reference | oai.Schema], + schemas: Schemas, + config: Config, +) -> Schemas: + to_process: Iterable[Tuple[str, oai.Reference | oai.Schema]] = components.items() + still_making_progress = True + errors: List[PropertyError] = [] + + # References could have forward References so keep going as long as we are making progress + while still_making_progress: + still_making_progress = False + errors = [] + next_round = [] + # Only accumulate errors from the last round, since we might fix some along the way + for name, data in to_process: + if isinstance(data, oai.Reference): + schemas.errors.append(PropertyError(data=data, detail="Reference schemas are not supported.")) + continue + ref_path = parse_reference_path(f"#/components/schemas/{name}") + if isinstance(ref_path, ParseError): + schemas.errors.append(PropertyError(detail=ref_path.detail, data=data)) + continue + schemas_or_err = update_schemas_with_data(ref_path=ref_path, data=data, schemas=schemas, config=config) + if isinstance(schemas_or_err, PropertyError): + next_round.append((name, data)) + errors.append(schemas_or_err) + continue + schemas = schemas_or_err + still_making_progress = True + to_process = next_round + + schemas.errors.extend(errors) + return schemas + + +def _propogate_removal(*, root: ReferencePath | utils.ClassName, schemas: Schemas, error: PropertyError) -> None: + if isinstance(root, utils.ClassName): + schemas.classes_by_name.pop(root, None) + return + if root in schemas.classes_by_reference: + error.detail = error.detail or "" + error.detail += f"\n{root}" + del schemas.classes_by_reference[root] + for child in schemas.dependencies.get(root, set()): + _propogate_removal(root=child, schemas=schemas, error=error) + + +def _process_model_errors( + model_errors: List[Tuple[ModelProperty, PropertyError]], *, schemas: Schemas +) -> List[PropertyError]: + for model, error in model_errors: + error.detail = error.detail or "" + error.detail += "\n\nFailure to process schema has resulted in the removal of:" + for root in model.roots: + _propogate_removal(root=root, schemas=schemas, error=error) + return [error for _, error in model_errors] + + +def _process_models(*, schemas: Schemas, config: Config) -> Schemas: + to_process = schemas.models_to_process + still_making_progress = True + final_model_errors: List[Tuple[ModelProperty, PropertyError]] = [] + latest_model_errors: List[Tuple[ModelProperty, PropertyError]] = [] + + # Models which refer to other models in their allOf must be processed after their referenced models + while still_making_progress: + still_making_progress = False + # Only accumulate errors from the last round, since we might fix some along the way + latest_model_errors = [] + next_round = [] + for model_prop in to_process: + schemas_or_err = process_model(model_prop, schemas=schemas, config=config) + if isinstance(schemas_or_err, PropertyError): + schemas_or_err.header = f"\nUnable to process schema {model_prop.name}:" + if isinstance(schemas_or_err.data, oai.Reference) and schemas_or_err.data.ref.endswith( + f"/{model_prop.class_info.name}" + ): + schemas_or_err.detail = schemas_or_err.detail or "" + schemas_or_err.detail += "\n\nRecursive allOf reference found" + final_model_errors.append((model_prop, schemas_or_err)) + continue + latest_model_errors.append((model_prop, schemas_or_err)) + next_round.append(model_prop) + continue + schemas = schemas_or_err + still_making_progress = True + to_process = next_round + + final_model_errors.extend(latest_model_errors) + errors = _process_model_errors(final_model_errors, schemas=schemas) + return evolve(schemas, errors=[*schemas.errors, *errors], models_to_process=to_process) + + +def build_schemas( + *, + components: Dict[str, oai.Reference | oai.Schema], + schemas: Schemas, + config: Config, +) -> Schemas: + """Get a list of Schemas from an OpenAPI dict""" + schemas = _create_schemas(components=components, schemas=schemas, config=config) + schemas = _process_models(schemas=schemas, config=config) + return schemas + + +def build_parameters( + *, + components: Dict[str, oai.Reference | oai.Parameter], + parameters: Parameters, + config: Config, +) -> Parameters: + """Get a list of Parameters from an OpenAPI dict""" + to_process: Iterable[Tuple[str, oai.Reference | oai.Parameter]] = [] + if components is not None: + to_process = components.items() + still_making_progress = True + errors: List[ParameterError] = [] + + # References could have forward References so keep going as long as we are making progress + while still_making_progress: + still_making_progress = False + errors = [] + next_round = [] + # Only accumulate errors from the last round, since we might fix some along the way + for name, data in to_process: + if isinstance(data, oai.Reference): + parameters.errors.append(ParameterError(data=data, detail="Reference parameters are not supported.")) + continue + ref_path = parse_reference_path(f"#/components/parameters/{name}") + if isinstance(ref_path, ParseError): + parameters.errors.append(ParameterError(detail=ref_path.detail, data=data)) + continue + parameters_or_err = update_parameters_with_data( + ref_path=ref_path, data=data, parameters=parameters, config=config + ) + if isinstance(parameters_or_err, ParameterError): + next_round.append((name, data)) + errors.append(parameters_or_err) + continue + parameters = parameters_or_err + still_making_progress = True + to_process = next_round + + parameters.errors.extend(errors) + return parameters diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/any.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/any.py new file mode 100644 index 000000000000..b760a156868e --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/any.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ...utils import PythonIdentifier +from .protocol import PropertyProtocol, Value + + +@define +class AnyProperty(PropertyProtocol): + """A property that can be any type (used for empty schemas)""" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> AnyProperty: + return cls( + name=name, + required=required, + default=AnyProperty.convert_value(default), + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None: + from .string import StringProperty + + if value is None: + return value + if isinstance(value, str): + return StringProperty.convert_value(value) + return Value(python_code=str(value), raw_value=value) + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + _type_string: ClassVar[str] = "Any" + _json_type_string: ClassVar[str] = "Any" diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py new file mode 100644 index 000000000000..882d9f6b7894 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class BooleanProperty(PropertyProtocol): + """Property for bool""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "bool" + _json_type_string: ClassVar[str] = "bool" + _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + template: ClassVar[str] = "boolean_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> BooleanProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if isinstance(value, Value) or value is None: + return value + if isinstance(value, str): + if value.lower() == "true": + return Value(python_code="True", raw_value=value) + elif value.lower() == "false": + return Value(python_code="False", raw_value=value) + if isinstance(value, bool): + return Value(python_code=str(value), raw_value=value) + return PropertyError(f"Invalid boolean value: {value}") diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/const.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/const.py new file mode 100644 index 000000000000..f4d9b5b758ff --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/const.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +from typing import Any, ClassVar, overload + +from attr import define + +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value +from .string import StringProperty + + +@define +class ConstProperty(PropertyProtocol): + """A property representing a const value""" + + name: str + required: bool + value: Value + default: Value | None + python_name: PythonIdentifier + description: str | None + example: None + template: ClassVar[str] = "const_property.py.jinja" + + @classmethod + def build( + cls, + *, + const: str | int | float | bool, + default: Any, + name: str, + python_name: PythonIdentifier, + required: bool, + description: str | None, + ) -> ConstProperty | PropertyError: + """ + Create a `ConstProperty` the right way. + + Args: + const: The `const` value of the schema, indicating the literal value this represents + default: The default value of this property, if any. Must be equal to `const` if set. + name: The name of the property where it appears in the OpenAPI document. + required: Whether this property is required where it's being used. + python_name: The name used to represent this variable/property in generated Python code + description: The description of this property, used for docstrings + """ + value = cls._convert_value(const) + + prop = cls( + value=value, + python_name=python_name, + name=name, + required=required, + default=None, + description=description, + example=None, + ) + converted_default = prop.convert_value(default) + if isinstance(converted_default, PropertyError): + return converted_default + prop.default = converted_default + return prop + + def convert_value(self, value: Any) -> Value | None | PropertyError: + value = self._convert_value(value) + if value is None: + return value + if value != self.value: + return PropertyError( + detail=f"Invalid value for const {self.name}; {value.raw_value} != {self.value.raw_value}" + ) + return value + + @staticmethod + @overload + def _convert_value(value: None) -> None: # type: ignore[misc] + ... # pragma: no cover + + @staticmethod + @overload + def _convert_value(value: Any) -> Value: ... # pragma: no cover + + @staticmethod + def _convert_value(value: Any) -> Value | None: + if value is None or isinstance(value, Value): + return value + if isinstance(value, str): + return StringProperty.convert_value(value) + return Value(python_code=str(value), raw_value=value) + + def get_type_string( + self, + no_optional: bool = False, + json: bool = False, + *, + multipart: bool = False, + quoted: bool = False, + ) -> str: + lit = f"Literal[{self.value.python_code}]" + if not no_optional and not self.required: + return f"Union[{lit}, Unset]" + return lit + + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + if self.required: + return {"from typing import Literal, cast"} + return { + "from typing import Literal, Union, cast", + f"from {prefix}types import UNSET, Unset", + } diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/date.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/date.py new file mode 100644 index 000000000000..b5c3ca997c27 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/date.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define +from dateutil.parser import isoparse + +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class DateProperty(PropertyProtocol): + """A property of type datetime.date""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "datetime.date" + _json_type_string: ClassVar[str] = "str" + template: ClassVar[str] = "date_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> DateProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + + return DateProperty( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if isinstance(value, Value) or value is None: + return value + if isinstance(value, str): + try: + isoparse(value).date() # make sure it's a valid value + except ValueError as e: + return PropertyError(f"Invalid date: {e}") + return Value(python_code=f"isoparse({value!r}).date()", raw_value=value) + return PropertyError(f"Cannot convert {value} to a date") + + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.update({"import datetime", "from typing import cast", "from dateutil.parser import isoparse"}) + return imports diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py new file mode 100644 index 000000000000..0556228d0742 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define +from dateutil.parser import isoparse + +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class DateTimeProperty(PropertyProtocol): + """ + A property of type datetime.datetime + """ + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "datetime.datetime" + _json_type_string: ClassVar[str] = "str" + template: ClassVar[str] = "datetime_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> DateTimeProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + + return DateTimeProperty( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if value is None or isinstance(value, Value): + return value + if isinstance(value, str): + try: + isoparse(value) # make sure it's a valid value + except ValueError as e: + return PropertyError(f"Invalid datetime: {e}") + return Value(python_code=f"isoparse({value!r})", raw_value=value) + return PropertyError(f"Cannot convert {value} to a datetime") + + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.update({"import datetime", "from typing import cast", "from dateutil.parser import isoparse"}) + return imports diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py new file mode 100644 index 000000000000..b5bf1e79553f --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py @@ -0,0 +1,209 @@ +from __future__ import annotations + +__all__ = ["EnumProperty", "ValueType"] + +from typing import Any, ClassVar, Union, cast + +from attr import evolve +from attrs import define + +from ... import Config, utils +from ... import schema as oai +from ...schema import DataType +from ..errors import PropertyError +from .none import NoneProperty +from .protocol import PropertyProtocol, Value +from .schemas import Class, Schemas +from .union import UnionProperty + +ValueType = Union[str, int] + + +@define +class EnumProperty(PropertyProtocol): + """A property that should use an enum""" + + name: str + required: bool + default: Value | None + python_name: utils.PythonIdentifier + description: str | None + example: str | None + values: Dict[str, ValueType] + class_info: Class + value_type: type[ValueType] + + template: ClassVar[str] = "enum_property.py.jinja" + + _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + + @classmethod + def build( # noqa: PLR0911 + cls, + *, + data: oai.Schema, + name: str, + required: bool, + schemas: Schemas, + parent_name: str, + config: Config, + ) -> Tuple[EnumProperty | NoneProperty | UnionProperty | PropertyError, Schemas]: + """ + Create an EnumProperty from schema data. + + Args: + data: The OpenAPI Schema which defines this enum. + name: The name to use for variables which receive this Enum's value (e.g. model property name) + required: Whether or not this Property is required in the calling context + schemas: The Schemas which have been defined so far (used to prevent naming collisions) + enum: The enum from the provided data. Required separately here to prevent extra type checking. + parent_name: The context in which this EnumProperty is defined, used to create more specific class names. + config: The global config for this run of the generator + + Returns: + A tuple containing either the created property or a PropertyError AND update schemas. + """ + + enum = data.enum or [] # The outer function checks for this, but mypy doesn't know that + + # OpenAPI allows for null as an enum value, but it doesn't make sense with how enums are constructed in Python. + # So instead, if null is a possible value, make the property nullable. + # Mypy is not smart enough to know that the type is right though + unchecked_value_list = [value for value in enum if value is not None] # type: ignore + + # It's legal to have an enum that only contains null as a value, we don't bother constructing an enum for that + if len(unchecked_value_list) == 0: + return ( + NoneProperty.build( + name=name, + required=required, + default="None", + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=None, + example=None, + ), + schemas, + ) + + value_types = {type(value) for value in unchecked_value_list} + if len(value_types) > 1: + return PropertyError( + header="Enum values must all be the same type", detail=f"Got {value_types}", data=data + ), schemas + value_type = next(iter(value_types)) + if value_type not in (str, int): + return PropertyError(header=f"Unsupported enum type {value_type}", data=data), schemas + value_list = cast( + Union[List[int], list[str]], unchecked_value_list + ) # We checked this with all the value_types stuff + + if len(value_list) < len(enum): # Only one of the values was None, that becomes a union + data.oneOf = [ + oai.Schema(type=DataType.NULL), + data.model_copy(update={"enum": value_list, "default": data.default}), + ] + data.enum = None + return UnionProperty.build( + data=data, + name=name, + required=required, + schemas=schemas, + parent_name=parent_name, + config=config, + ) + + class_name = data.title or name + if parent_name: + class_name = f"{utils.pascal_case(parent_name)}{utils.pascal_case(class_name)}" + class_info = Class.from_string(string=class_name, config=config) + values = EnumProperty.values_from_list(value_list, class_info) + + if class_info.name in schemas.classes_by_name: + existing = schemas.classes_by_name[class_info.name] + if not isinstance(existing, EnumProperty) or values != existing.values: + return ( + PropertyError( + detail=f"Found conflicting enums named {class_info.name} with incompatible values.", data=data + ), + schemas, + ) + + prop = EnumProperty( + name=name, + required=required, + class_info=class_info, + values=values, + value_type=value_type, + default=None, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ) + checked_default = prop.convert_value(data.default) + if isinstance(checked_default, PropertyError): + checked_default.data = data + return checked_default, schemas + prop = evolve(prop, default=checked_default) + + schemas = evolve(schemas, classes_by_name={**schemas.classes_by_name, class_info.name: prop}) + return prop, schemas + + def convert_value(self, value: Any) -> Value | PropertyError | None: + if value is None or isinstance(value, Value): + return value + if isinstance(value, self.value_type): + inverse_values = {v: k for k, v in self.values.items()} + try: + return Value(python_code=f"{self.class_info.name}.{inverse_values[value]}", raw_value=value) + except KeyError: + return PropertyError(detail=f"Value {value} is not valid for enum {self.name}") + return PropertyError(detail=f"Cannot convert {value} to enum {self.name} of type {self.value_type}") + + def get_base_type_string(self, *, quoted: bool = False) -> str: + return self.class_info.name + + def get_base_json_type_string(self, *, quoted: bool = False) -> str: + return self.value_type.__name__ + + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.add(f"from {prefix}models.{self.class_info.module_name} import {self.class_info.name}") + return imports + + @staticmethod + def values_from_list(values: List[str] | list[int], class_info: Class) -> Dict[str, ValueType]: + """Convert a list of values into dict of {name: value}, where value can sometimes be None""" + output: Dict[str, ValueType] = {} + + for i, value in enumerate(values): + value = cast(Union[str, int], value) + if isinstance(value, int): + if value < 0: + output[f"VALUE_NEGATIVE_{-value}"] = value + else: + output[f"VALUE_{value}"] = value + continue + if value and value[0].isalpha(): + key = value.upper() + else: + key = f"VALUE_{i}" + if key in output: + raise ValueError( + f"Duplicate key {key} in enum {class_info.module_name}.{class_info.name}; " + f"consider setting literal_enums in your config" + ) + sanitized_key = utils.snake_case(key).upper() + output[sanitized_key] = utils.remove_string_escapes(value) + return output diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/file.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/file.py new file mode 100644 index 000000000000..f8a5baa711fa --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/file.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol + + +@define +class FileProperty(PropertyProtocol): + """A property used for uploading files""" + + name: str + required: bool + default: None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "File" + # Return type of File.to_tuple() + _json_type_string: ClassVar[str] = "FileJsonType" + template: ClassVar[str] = "file_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> FileProperty | PropertyError: + default_or_err = cls.convert_value(default) + if isinstance(default_or_err, PropertyError): + return default_or_err + + return cls( + name=name, + required=required, + default=default_or_err, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> None | PropertyError: + if value is not None: + return PropertyError(detail="File properties cannot have a default value") + return value + + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.update({f"from {prefix}types import File, FileJsonType", "from io import BytesIO"}) + return imports diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/float.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/float.py new file mode 100644 index 000000000000..d8cfe62f96be --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/float.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class FloatProperty(PropertyProtocol): + """A property of type float""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "float" + _json_type_string: ClassVar[str] = "float" + _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + template: ClassVar[str] = "float_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> FloatProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if isinstance(value, Value) or value is None: + return value + if isinstance(value, str): + try: + parsed = float(value) + return Value(python_code=str(parsed), raw_value=value) + except ValueError: + return PropertyError(f"Invalid float value: {value}") + if isinstance(value, float): + return Value(python_code=str(value), raw_value=value) + if isinstance(value, int) and not isinstance(value, bool): + return Value(python_code=str(float(value)), raw_value=value) + return PropertyError(f"Cannot convert {value} to a float") diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/int.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/int.py new file mode 100644 index 000000000000..44b1f91d6473 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/int.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class IntProperty(PropertyProtocol): + """A property of type int""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "int" + _json_type_string: ClassVar[str] = "int" + _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + template: ClassVar[str] = "int_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> IntProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if value is None or isinstance(value, Value): + return value + converted = value + if isinstance(converted, str): + try: + converted = float(converted) + except ValueError: + return PropertyError(f"Invalid int value: {converted}") + if isinstance(converted, float): + as_int = int(converted) + if converted == as_int: + converted = as_int + if isinstance(converted, int) and not isinstance(converted, bool): + return Value(python_code=str(converted), raw_value=value) + return PropertyError(f"Invalid int value: {value}") diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py new file mode 100644 index 000000000000..f0a77754b992 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py @@ -0,0 +1,160 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ... import Config, utils +from ... import schema as oai +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value +from .schemas import ReferencePath, Schemas + + +@define +class ListProperty(PropertyProtocol): + """A property representing a list (array) of other properties""" + + name: str + required: bool + default: Value | None + python_name: utils.PythonIdentifier + description: str | None + example: str | None + inner_property: PropertyProtocol + template: ClassVar[str] = "list_property.py.jinja" + + @classmethod + def build( + cls, + *, + data: oai.Schema, + name: str, + required: bool, + schemas: Schemas, + parent_name: str, + config: Config, + process_properties: bool, + roots: Set[ReferencePath | utils.ClassName], + ) -> Tuple[ListProperty | PropertyError, Schemas]: + """ + Build a ListProperty the right way, use this instead of the normal constructor. + + Args: + data: `oai.Schema` representing this `ListProperty`. + name: The name of this property where it's used. + required: Whether this `ListProperty` can be `Unset` where it's used. + schemas: Collected `Schemas` so far containing any classes or references. + parent_name: The name of the thing containing this property (used for naming inner classes). + config: User-provided config for overriding default behaviors. + process_properties: If the new property is a ModelProperty, determines whether it will be initialized with + property data + roots: The set of `ReferencePath`s and `ClassName`s to remove from the schemas if a child reference becomes + invalid + + Returns: + `(result, schemas)` where `schemas` is an updated version of the input named the same including any inner + classes that were defined and `result` is either the `ListProperty` or a `PropertyError`. + """ + from . import property_from_data + + if data.items is None and not data.prefixItems: + return ( + PropertyError( + data=data, + detail="type array must have items or prefixItems defined", + ), + schemas, + ) + + items = data.prefixItems or [] + if data.items: + items.append(data.items) + + if len(items) == 1: + inner_schema = items[0] + else: + inner_schema = oai.Schema(anyOf=items) + + inner_prop, schemas = property_from_data( + name=f"{name}_item", + required=True, + data=inner_schema, + schemas=schemas, + parent_name=parent_name, + config=config, + process_properties=process_properties, + roots=roots, + ) + if isinstance(inner_prop, PropertyError): + inner_prop.header = f'invalid data in items of array named "{name}"' + return inner_prop, schemas + return ( + ListProperty( + name=name, + required=required, + default=None, + inner_property=inner_prop, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ), + schemas, + ) + + def convert_value(self, value: Any) -> Value | None | PropertyError: + return None # pragma: no cover + + def get_base_type_string(self, *, quoted: bool = False) -> str: + return f"List[{self.inner_property.get_type_string(quoted=not self.inner_property.is_base_type)}]" + + def get_base_json_type_string(self, *, quoted: bool = False) -> str: + return f"List[{self.inner_property.get_type_string(json=True, quoted=not self.inner_property.is_base_type)}]" + + def get_instance_type_string(self) -> str: + """Get a string representation of runtime type that should be used for `isinstance` checks""" + return "list" + + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.update(self.inner_property.get_imports(prefix=prefix)) + imports.add("from typing import cast") + return imports + + def get_lazy_imports(self, *, prefix: str) -> Set[str]: + lazy_imports = super().get_lazy_imports(prefix=prefix) + lazy_imports.update(self.inner_property.get_lazy_imports(prefix=prefix)) + return lazy_imports + + def get_type_string( + self, + no_optional: bool = False, + json: bool = False, + *, + multipart: bool = False, + quoted: bool = False, + ) -> str: + """ + Get a string representation of type that should be used when declaring this property + + Args: + no_optional: Do not include Optional or Unset even if the value is optional (needed for isinstance checks) + json: True if the type refers to the property after JSON serialization + """ + if json: + type_string = self.get_base_json_type_string() + elif multipart: + type_string = "Tuple[None, bytes, str]" + else: + type_string = self.get_base_type_string() + + if no_optional or self.required: + return type_string + return f"Union[Unset, {type_string}]" diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py new file mode 100644 index 000000000000..549d81912a29 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +__all__ = ["LiteralEnumProperty"] + +from typing import Any, ClassVar, Union, cast + +from attr import evolve +from attrs import define + +from ... import Config, utils +from ... import schema as oai +from ...schema import DataType +from ..errors import PropertyError +from .none import NoneProperty +from .protocol import PropertyProtocol, Value +from .schemas import Class, Schemas +from .union import UnionProperty + +ValueType = Union[str, int] + + +@define +class LiteralEnumProperty(PropertyProtocol): + """A property that should use a literal enum""" + + name: str + required: bool + default: Value | None + python_name: utils.PythonIdentifier + description: str | None + example: str | None + values: Set[ValueType] + class_info: Class + value_type: type[ValueType] + + template: ClassVar[str] = "literal_enum_property.py.jinja" + + _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + + @classmethod + def build( # noqa: PLR0911 + cls, + *, + data: oai.Schema, + name: str, + required: bool, + schemas: Schemas, + parent_name: str, + config: Config, + ) -> Tuple[LiteralEnumProperty | NoneProperty | UnionProperty | PropertyError, Schemas]: + """ + Create a LiteralEnumProperty from schema data. + + Args: + data: The OpenAPI Schema which defines this enum. + name: The name to use for variables which receive this Enum's value (e.g. model property name) + required: Whether or not this Property is required in the calling context + schemas: The Schemas which have been defined so far (used to prevent naming collisions) + parent_name: The context in which this LiteralEnumProperty is defined, used to create more specific class names. + config: The global config for this run of the generator + + Returns: + A tuple containing either the created property or a PropertyError AND update schemas. + """ + + enum = data.enum or [] # The outer function checks for this, but mypy doesn't know that + + # OpenAPI allows for null as an enum value, but it doesn't make sense with how enums are constructed in Python. + # So instead, if null is a possible value, make the property nullable. + # Mypy is not smart enough to know that the type is right though + unchecked_value_list = [value for value in enum if value is not None] # type: ignore + + # It's legal to have an enum that only contains null as a value, we don't bother constructing an enum for that + if len(unchecked_value_list) == 0: + return ( + NoneProperty.build( + name=name, + required=required, + default="None", + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=None, + example=None, + ), + schemas, + ) + + value_types = {type(value) for value in unchecked_value_list} + if len(value_types) > 1: + return PropertyError( + header="Enum values must all be the same type", detail=f"Got {value_types}", data=data + ), schemas + value_type = next(iter(value_types)) + if value_type not in (str, int): + return PropertyError(header=f"Unsupported enum type {value_type}", data=data), schemas + value_list = cast( + Union[List[int], list[str]], unchecked_value_list + ) # We checked this with all the value_types stuff + + if len(value_list) < len(enum): # Only one of the values was None, that becomes a union + data.oneOf = [ + oai.Schema(type=DataType.NULL), + data.model_copy(update={"enum": value_list, "default": data.default}), + ] + data.enum = None + return UnionProperty.build( + data=data, + name=name, + required=required, + schemas=schemas, + parent_name=parent_name, + config=config, + ) + + class_name = data.title or name + if parent_name: + class_name = f"{utils.pascal_case(parent_name)}{utils.pascal_case(class_name)}" + class_info = Class.from_string(string=class_name, config=config) + values: Set[str | int] = set(value_list) + + if class_info.name in schemas.classes_by_name: + existing = schemas.classes_by_name[class_info.name] + if not isinstance(existing, LiteralEnumProperty) or values != existing.values: + return ( + PropertyError( + detail=f"Found conflicting enums named {class_info.name} with incompatible values.", data=data + ), + schemas, + ) + + prop = LiteralEnumProperty( + name=name, + required=required, + class_info=class_info, + values=values, + value_type=value_type, + default=None, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ) + checked_default = prop.convert_value(data.default) + if isinstance(checked_default, PropertyError): + checked_default.data = data + return checked_default, schemas + prop = evolve(prop, default=checked_default) + + schemas = evolve(schemas, classes_by_name={**schemas.classes_by_name, class_info.name: prop}) + return prop, schemas + + def convert_value(self, value: Any) -> Value | PropertyError | None: + if value is None or isinstance(value, Value): + return value + if isinstance(value, self.value_type): + if value in self.values: + return Value(python_code=repr(value), raw_value=value) + else: + return PropertyError(detail=f"Value {value} is not valid for enum {self.name}") + return PropertyError(detail=f"Cannot convert {value} to enum {self.name} of type {self.value_type}") + + def get_base_type_string(self, *, quoted: bool = False) -> str: + return self.class_info.name + + def get_base_json_type_string(self, *, quoted: bool = False) -> str: + return self.value_type.__name__ + + def get_instance_type_string(self) -> str: + return self.value_type.__name__ + + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.add("from typing import cast") + imports.add(f"from {prefix}models.{self.class_info.module_name} import {self.class_info.name}") + imports.add( + f"from {prefix}models.{self.class_info.module_name} import check_{self.get_class_name_snake_case()}" + ) + return imports + + def get_class_name_snake_case(self) -> str: + return utils.snake_case(self.class_info.name) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py new file mode 100644 index 000000000000..db6424a7c631 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +from openapi_python_client.parser.properties.date import DateProperty +from openapi_python_client.parser.properties.datetime import DateTimeProperty +from openapi_python_client.parser.properties.file import FileProperty +from openapi_python_client.parser.properties.literal_enum_property import LiteralEnumProperty + +__all__ = ["merge_properties"] + +from typing import TypeVar, cast + +from attr import evolve + +from ..errors import PropertyError +from . import FloatProperty +from .any import AnyProperty +from .enum_property import EnumProperty +from .int import IntProperty +from .list_property import ListProperty +from .property import Property +from .protocol import PropertyProtocol +from .string import StringProperty + +PropertyT = TypeVar("PropertyT", bound=PropertyProtocol) + + +STRING_WITH_FORMAT_TYPES = (DateProperty, DateTimeProperty, FileProperty) + + +def merge_properties(prop1: Property, prop2: Property) -> Property | PropertyError: # noqa: PLR0911 + """Attempt to create a new property that incorporates the behavior of both. + + This is used when merging schemas with allOf, when two schemas define a property with the same name. + + OpenAPI defines allOf in terms of validation behavior: the input must pass the validation rules + defined in all the listed schemas. Our task here is slightly more difficult, since we must end + up with a single Property object that will be used to generate a single class property in the + generated code. Due to limitations of our internal model, this may not be possible for some + combinations of property attributes that OpenAPI supports (for instance, we have no way to represent + a string property that must match two different regexes). + + Properties can also have attributes that do not represent validation rules, such as "description" + and "example". OpenAPI does not define any overriding/aggregation rules for these in allOf. The + implementation here is, assuming prop1 and prop2 are in the same order that the schemas were in the + allOf, any such attributes that prop2 specifies will override the ones from prop1. + """ + if isinstance(prop2, AnyProperty): + return _merge_common_attributes(prop1, prop2) + + if isinstance(prop1, AnyProperty): + # Use the base type of `prop2`, but keep the override order + return _merge_common_attributes(prop2, prop1, prop2) + + if isinstance(prop1, EnumProperty) or isinstance(prop2, EnumProperty): + return _merge_with_enum(prop1, prop2) + + if isinstance(prop1, LiteralEnumProperty) or isinstance(prop2, LiteralEnumProperty): + return _merge_with_literal_enum(prop1, prop2) + + if (merged := _merge_same_type(prop1, prop2)) is not None: + return merged + + if (merged := _merge_numeric(prop1, prop2)) is not None: + return merged + + if (merged := _merge_string_with_format(prop1, prop2)) is not None: + return merged + + return PropertyError( + detail=f"{prop1.get_type_string(no_optional=True)} can't be merged with {prop2.get_type_string(no_optional=True)}" + ) + + +def _merge_same_type(prop1: Property, prop2: Property) -> Property | None | PropertyError: + if type(prop1) is not type(prop2): + return None + + if prop1 == prop2: + # It's always OK to redefine a property with everything exactly the same + return prop1 + + if isinstance(prop1, ListProperty) and isinstance(prop2, ListProperty): + inner_property = merge_properties(prop1.inner_property, prop2.inner_property) # type: ignore + if isinstance(inner_property, PropertyError): + return PropertyError(detail=f"can't merge list properties: {inner_property.detail}") + prop1.inner_property = inner_property + + # For all other property types, there aren't any special attributes that affect validation, so just + # apply the rules for common attributes like "description". + return _merge_common_attributes(prop1, prop2) + + +def _merge_string_with_format(prop1: Property, prop2: Property) -> Property | None | PropertyError: + """Merge a string that has no format with a string that has a format""" + # Here we need to use the DateProperty/DateTimeProperty/FileProperty as the base so that we preserve + # its class, but keep the correct override order for merging the attributes. + if isinstance(prop1, StringProperty) and isinstance(prop2, STRING_WITH_FORMAT_TYPES): + # Use the more specific class as a base, but keep the correct override order + return _merge_common_attributes(prop2, prop1, prop2) + elif isinstance(prop2, StringProperty) and isinstance(prop1, STRING_WITH_FORMAT_TYPES): + return _merge_common_attributes(prop1, prop2) + else: + return None + + +def _merge_numeric(prop1: Property, prop2: Property) -> IntProperty | None | PropertyError: + """Merge IntProperty with FloatProperty""" + if isinstance(prop1, IntProperty) and isinstance(prop2, (IntProperty, FloatProperty)): + return _merge_common_attributes(prop1, prop2) + elif isinstance(prop2, IntProperty) and isinstance(prop1, (IntProperty, FloatProperty)): + # Use the IntProperty as a base since it's more restrictive, but keep the correct override order + return _merge_common_attributes(prop2, prop1, prop2) + else: + return None + + +def _merge_with_enum(prop1: PropertyProtocol, prop2: PropertyProtocol) -> EnumProperty | PropertyError: + if isinstance(prop1, EnumProperty) and isinstance(prop2, EnumProperty): + # We want the narrowest validation rules that fit both, so use whichever values list is a + # subset of the other. + if _values_are_subset(prop1, prop2): + values = prop1.values + class_info = prop1.class_info + elif _values_are_subset(prop2, prop1): + values = prop2.values + class_info = prop2.class_info + else: + return PropertyError(detail="can't redefine an enum property with incompatible lists of values") + return _merge_common_attributes(evolve(prop1, values=values, class_info=class_info), prop2) + + # If enum values were specified for just one of the properties, use those. + enum_prop = prop1 if isinstance(prop1, EnumProperty) else cast(EnumProperty, prop2) + non_enum_prop = prop2 if isinstance(prop1, EnumProperty) else prop1 + if (isinstance(non_enum_prop, IntProperty) and enum_prop.value_type is int) or ( + isinstance(non_enum_prop, StringProperty) and enum_prop.value_type is str + ): + return _merge_common_attributes(enum_prop, prop1, prop2) + return PropertyError( + detail=f"can't combine enum of type {enum_prop.value_type} with {non_enum_prop.get_type_string(no_optional=True)}" + ) + + +def _merge_with_literal_enum(prop1: PropertyProtocol, prop2: PropertyProtocol) -> LiteralEnumProperty | PropertyError: + if isinstance(prop1, LiteralEnumProperty) and isinstance(prop2, LiteralEnumProperty): + # We want the narrowest validation rules that fit both, so use whichever values list is a + # subset of the other. + if prop1.values <= prop2.values: + values = prop1.values + class_info = prop1.class_info + elif prop2.values <= prop1.values: + values = prop2.values + class_info = prop2.class_info + else: + return PropertyError(detail="can't redefine a literal enum property with incompatible lists of values") + return _merge_common_attributes(evolve(prop1, values=values, class_info=class_info), prop2) + + # If enum values were specified for just one of the properties, use those. + enum_prop = prop1 if isinstance(prop1, LiteralEnumProperty) else cast(LiteralEnumProperty, prop2) + non_enum_prop = prop2 if isinstance(prop1, LiteralEnumProperty) else prop1 + if (isinstance(non_enum_prop, IntProperty) and enum_prop.value_type is int) or ( + isinstance(non_enum_prop, StringProperty) and enum_prop.value_type is str + ): + return _merge_common_attributes(enum_prop, prop1, prop2) + return PropertyError( + detail=f"can't combine literal enum of type {enum_prop.value_type} with {non_enum_prop.get_type_string(no_optional=True)}" + ) + + +def _merge_common_attributes(base: PropertyT, *extend_with: PropertyProtocol) -> PropertyT | PropertyError: + """Create a new instance based on base, overriding basic attributes with values from extend_with, in order. + + For "default", "description", and "example", a non-None value overrides any value from a previously + specified property. The behavior is similar to using the spread operator with dictionaries, except + that None means "not specified". + + For "required", any True value overrides all other values (a property that was previously required + cannot become optional). + """ + current = base + for override in extend_with: + if override.default is not None: + override_default = current.convert_value(override.default.raw_value) + else: + override_default = None + if isinstance(override_default, PropertyError): + return override_default + current = evolve( + current, # type: ignore # can't prove that every property type is an attrs class, but it is + required=current.required or override.required, + default=override_default or current.default, + description=override.description or current.description, + example=override.example or current.example, + ) + return current + + +def _values_are_subset(prop1: EnumProperty, prop2: EnumProperty) -> bool: + return set(prop1.values.items()) <= set(prop2.values.items()) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py new file mode 100644 index 000000000000..73bc56ae0519 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py @@ -0,0 +1,444 @@ +from __future__ import annotations + +from itertools import chain +from typing import Any, ClassVar, NamedTuple + +from attrs import define, evolve + +from ... import Config, utils +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import ParseError, PropertyError +from .any import AnyProperty +from .protocol import PropertyProtocol, Value +from .schemas import Class, ReferencePath, Schemas, parse_reference_path + + +@define +class ModelProperty(PropertyProtocol): + """A property which refers to another Schema""" + + name: str + required: bool + default: Value | None + python_name: utils.PythonIdentifier + example: str | None + class_info: Class + data: oai.Schema + description: str + roots: Set[ReferencePath | utils.ClassName] + required_properties: List[Property] | None + optional_properties: List[Property] | None + relative_imports: Set[str] | None + lazy_imports: Set[str] | None + additional_properties: Property | None + _json_type_string: ClassVar[str] = "Dict[str, Any]" + + template: ClassVar[str] = "model_property.py.jinja" + json_is_dict: ClassVar[bool] = True + is_multipart_body: bool = False + + @classmethod + def build( + cls, + *, + data: oai.Schema, + name: str, + schemas: Schemas, + required: bool, + parent_name: str | None, + config: Config, + process_properties: bool, + roots: Set[ReferencePath | utils.ClassName], + ) -> Tuple[ModelProperty | PropertyError, Schemas]: + """ + A single ModelProperty from its OAI data + + Args: + data: Data of a single Schema + name: Name by which the schema is referenced, such as a model name. + Used to infer the type name if a `title` property is not available. + schemas: Existing Schemas which have already been processed (to check name conflicts) + required: Whether or not this property is required by the parent (affects typing) + parent_name: The name of the property that this property is inside of (affects class naming) + config: Config data for this run of the generator, used to modifying names + roots: Set of strings that identify schema objects on which the new ModelProperty will depend + process_properties: Determines whether the new ModelProperty will be initialized with property data + """ + if not config.use_path_prefixes_for_title_model_names and data.title: + class_string = data.title + else: + title = data.title or name + if parent_name: + class_string = f"{utils.pascal_case(parent_name)}{utils.pascal_case(title)}" + else: + class_string = title + class_info = Class.from_string(string=class_string, config=config) + model_roots = {*roots, class_info.name} + required_properties: List[Property] | None = None + optional_properties: List[Property] | None = None + relative_imports: Set[str] | None = None + lazy_imports: Set[str] | None = None + additional_properties: Property | None = None + if process_properties: + data_or_err, schemas = _process_property_data( + data=data, schemas=schemas, class_info=class_info, config=config, roots=model_roots + ) + if isinstance(data_or_err, PropertyError): + return data_or_err, schemas + property_data, additional_properties = data_or_err + required_properties = property_data.required_props + optional_properties = property_data.optional_props + relative_imports = property_data.relative_imports + lazy_imports = property_data.lazy_imports + for root in roots: + if isinstance(root, utils.ClassName): + continue + schemas.add_dependencies(root, {class_info.name}) + + prop = ModelProperty( + class_info=class_info, + data=data, + roots=model_roots, + required_properties=required_properties, + optional_properties=optional_properties, + relative_imports=relative_imports, + lazy_imports=lazy_imports, + additional_properties=additional_properties, + description=data.description or "", + default=None, + required=required, + name=name, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + example=data.example, + ) + if class_info.name in schemas.classes_by_name: + error = PropertyError( + data=data, detail=f'Attempted to generate duplicate models with name "{class_info.name}"' + ) + return error, schemas + + schemas = evolve( + schemas, + classes_by_name={**schemas.classes_by_name, class_info.name: prop}, + models_to_process=[*schemas.models_to_process, prop], + ) + return prop, schemas + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if value is not None: + return PropertyError(detail="ModelProperty cannot have a default value") # pragma: no cover + return None + + def __attrs_post_init__(self) -> None: + if self.relative_imports: + self.set_relative_imports(self.relative_imports) + + @property + def self_import(self) -> str: + """Constructs a self import statement from this ModelProperty's attributes""" + return f"models.{self.class_info.module_name} import {self.class_info.name}" + + def get_base_type_string(self, *, quoted: bool = False) -> str: + return f'"{self.class_info.name}"' if quoted else self.class_info.name + + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.update( + { + "from typing import cast", + } + ) + return imports + + def get_lazy_imports(self, *, prefix: str) -> Set[str]: + """Get a set of lazy import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + return {f"from {prefix}{self.self_import}"} + + def set_relative_imports(self, relative_imports: Set[str]) -> None: + """Set the relative imports set for this ModelProperty, filtering out self imports + + Args: + relative_imports: The set of relative import strings + """ + object.__setattr__(self, "relative_imports", {ri for ri in relative_imports if self.self_import not in ri}) + + def set_lazy_imports(self, lazy_imports: Set[str]) -> None: + """Set the lazy imports set for this ModelProperty, filtering out self imports + + Args: + lazy_imports: The set of lazy import strings + """ + object.__setattr__(self, "lazy_imports", {li for li in lazy_imports if self.self_import not in li}) + + def get_type_string( + self, + no_optional: bool = False, + json: bool = False, + *, + multipart: bool = False, + quoted: bool = False, + ) -> str: + """ + Get a string representation of type that should be used when declaring this property + + Args: + no_optional: Do not include Optional or Unset even if the value is optional (needed for isinstance checks) + json: True if the type refers to the property after JSON serialization + """ + if json: + type_string = self.get_base_json_type_string() + elif multipart: + type_string = "Tuple[None, bytes, str]" + else: + type_string = self.get_base_type_string() + + if quoted: + if type_string == self.class_info.name: + type_string = f"'{type_string}'" + + if no_optional or self.required: + return type_string + return f"Union[Unset, {type_string}]" + + +from .property import Property # noqa: E402 + + +def _resolve_naming_conflict(first: Property, second: Property, config: Config) -> PropertyError | None: + first.set_python_name(first.name, config=config, skip_snake_case=True) + second.set_python_name(second.name, config=config, skip_snake_case=True) + if first.python_name == second.python_name: + return PropertyError( + header="Conflicting property names", + detail=f"Properties {first.name} and {second.name} have the same python_name", + ) + return None + + +class _PropertyData(NamedTuple): + optional_props: List[Property] + required_props: List[Property] + relative_imports: Set[str] + lazy_imports: Set[str] + schemas: Schemas + + +def _process_properties( # noqa: PLR0912, PLR0911 + *, + data: oai.Schema, + schemas: Schemas, + class_name: utils.ClassName, + config: Config, + roots: Set[ReferencePath | utils.ClassName], +) -> _PropertyData | PropertyError: + from . import property_from_data + from .merge_properties import merge_properties + + properties: Dict[str, Property] = {} + relative_imports: Set[str] = set() + lazy_imports: Set[str] = set() + required_set = set(data.required or []) + + def _add_if_no_conflict(new_prop: Property) -> PropertyError | None: + nonlocal properties + + name_conflict = properties.get(new_prop.name) + merged_prop = merge_properties(name_conflict, new_prop) if name_conflict else new_prop + if isinstance(merged_prop, PropertyError): + merged_prop.header = f"Found conflicting properties named {new_prop.name} when creating {class_name}" + return merged_prop + + for other_prop in properties.values(): + if other_prop.name == merged_prop.name: + continue # Same property, probably just got merged + if other_prop.python_name != merged_prop.python_name: + continue + naming_error = _resolve_naming_conflict(merged_prop, other_prop, config) + if naming_error is not None: + return naming_error + + properties[merged_prop.name] = merged_prop + return None + + unprocessed_props: List[Tuple[str, oai.Reference | oai.Schema]] = ( + list(data.properties.items()) if data.properties else [] + ) + for sub_prop in data.allOf: + if isinstance(sub_prop, oai.Reference): + ref_path = parse_reference_path(sub_prop.ref) + if isinstance(ref_path, ParseError): + return PropertyError(detail=ref_path.detail, data=sub_prop) + sub_model = schemas.classes_by_reference.get(ref_path) + if sub_model is None: + return PropertyError(f"Reference {sub_prop.ref} not found") + if not isinstance(sub_model, ModelProperty): + return PropertyError("Cannot take allOf a non-object") + # Properties of allOf references first should be processed first + if not ( + isinstance(sub_model.required_properties, list) and isinstance(sub_model.optional_properties, list) + ): + return PropertyError(f"Reference {sub_model.name} in allOf was not processed", data=sub_prop) + for prop in chain(sub_model.required_properties, sub_model.optional_properties): + err = _add_if_no_conflict(prop) + if err is not None: + return err + schemas.add_dependencies(ref_path=ref_path, roots=roots) + else: + unprocessed_props.extend(sub_prop.properties.items() if sub_prop.properties else []) + required_set.update(sub_prop.required or []) + + for key, value in unprocessed_props: + prop_required = key in required_set + prop_or_error: Property | (PropertyError | None) + prop_or_error, schemas = property_from_data( + name=key, + required=prop_required, + data=value, + schemas=schemas, + parent_name=class_name, + config=config, + roots=roots, + ) + if not isinstance(prop_or_error, PropertyError): + prop_or_error = _add_if_no_conflict(prop_or_error) + if isinstance(prop_or_error, PropertyError): + return prop_or_error + + required_properties = [] + optional_properties = [] + for prop in properties.values(): + if prop.required: + required_properties.append(prop) + else: + optional_properties.append(prop) + + lazy_imports.update(prop.get_lazy_imports(prefix="..")) + relative_imports.update(prop.get_imports(prefix="..")) + + return _PropertyData( + optional_props=optional_properties, + required_props=required_properties, + relative_imports=relative_imports, + lazy_imports=lazy_imports, + schemas=schemas, + ) + + +ANY_ADDITIONAL_PROPERTY = AnyProperty.build( + name="additional", + required=True, + default=None, + description="", + python_name=PythonIdentifier(value="additional", prefix=""), + example=None, +) + + +def _get_additional_properties( + *, + schema_additional: None | (bool | (oai.Reference | oai.Schema)), + schemas: Schemas, + class_name: utils.ClassName, + config: Config, + roots: Set[ReferencePath | utils.ClassName], +) -> Tuple[Property | None | PropertyError, Schemas]: + from . import property_from_data + + if schema_additional is None: + return ANY_ADDITIONAL_PROPERTY, schemas + + if isinstance(schema_additional, bool): + if schema_additional: + return ANY_ADDITIONAL_PROPERTY, schemas + return None, schemas + + if isinstance(schema_additional, oai.Schema) and not any(schema_additional.model_dump().values()): + # An empty schema + return ANY_ADDITIONAL_PROPERTY, schemas + + additional_properties, schemas = property_from_data( + name="AdditionalProperty", + required=True, # in the sense that if present in the dict will not be None + data=schema_additional, + schemas=schemas, + parent_name=class_name, + config=config, + roots=roots, + ) + return additional_properties, schemas + + +def _process_property_data( + *, + data: oai.Schema, + schemas: Schemas, + class_info: Class, + config: Config, + roots: Set[ReferencePath | utils.ClassName], +) -> Tuple[tuple[_PropertyData, Property | None] | PropertyError, Schemas]: + property_data = _process_properties( + data=data, schemas=schemas, class_name=class_info.name, config=config, roots=roots + ) + if isinstance(property_data, PropertyError): + return property_data, schemas + schemas = property_data.schemas + + additional_properties, schemas = _get_additional_properties( + schema_additional=data.additionalProperties, + schemas=schemas, + class_name=class_info.name, + config=config, + roots=roots, + ) + if isinstance(additional_properties, PropertyError): + return additional_properties, schemas + elif additional_properties is None: + pass + else: + property_data.relative_imports.update(additional_properties.get_imports(prefix="..")) + property_data.lazy_imports.update(additional_properties.get_lazy_imports(prefix="..")) + + return (property_data, additional_properties), schemas + + +def process_model(model_prop: ModelProperty, *, schemas: Schemas, config: Config) -> Schemas | PropertyError: + """Populate a ModelProperty instance's property data + Args: + model_prop: The ModelProperty to build property data for + schemas: Existing Schemas + config: Config data for this run of the generator, used to modifying names + Returns: + Either the updated `schemas` input or a `PropertyError` if something went wrong. + """ + data_or_err, schemas = _process_property_data( + data=model_prop.data, + schemas=schemas, + class_info=model_prop.class_info, + config=config, + roots=model_prop.roots, + ) + if isinstance(data_or_err, PropertyError): + return data_or_err + + property_data, additional_properties = data_or_err + + object.__setattr__(model_prop, "required_properties", property_data.required_props) + object.__setattr__(model_prop, "optional_properties", property_data.optional_props) + model_prop.set_relative_imports(property_data.relative_imports) + model_prop.set_lazy_imports(property_data.lazy_imports) + object.__setattr__(model_prop, "additional_properties", additional_properties) + return schemas diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/none.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/none.py new file mode 100644 index 000000000000..ab493fc65836 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/none.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class NoneProperty(PropertyProtocol): + """A property that can only be None""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + _type_string: ClassVar[str] = "None" + _json_type_string: ClassVar[str] = "None" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> NoneProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if value is None or isinstance(value, Value): + return value + if isinstance(value, str): + if value == "None": + return Value(python_code=value, raw_value=value) + return PropertyError(f"Value {value} is not valid, only None is allowed") diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/property.py new file mode 100644 index 000000000000..6e73a01ae425 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/property.py @@ -0,0 +1,41 @@ +__all__ = ["Property"] + +from typing import Union + +from typing_extensions import TypeAlias + +from .any import AnyProperty +from .boolean import BooleanProperty +from .const import ConstProperty +from .date import DateProperty +from .datetime import DateTimeProperty +from .enum_property import EnumProperty +from .file import FileProperty +from .float import FloatProperty +from .int import IntProperty +from .list_property import ListProperty +from .literal_enum_property import LiteralEnumProperty +from .model_property import ModelProperty +from .none import NoneProperty +from .string import StringProperty +from .union import UnionProperty +from .uuid import UuidProperty + +Property: TypeAlias = Union[ + AnyProperty, + BooleanProperty, + ConstProperty, + DateProperty, + DateTimeProperty, + EnumProperty, + LiteralEnumProperty, + FileProperty, + FloatProperty, + IntProperty, + ListProperty, + ModelProperty, + NoneProperty, + StringProperty, + UnionProperty, + UuidProperty, +] diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py new file mode 100644 index 000000000000..280b0e8ade6c --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py @@ -0,0 +1,187 @@ +from __future__ import annotations + +__all__ = ["PropertyProtocol", "Value"] + +from abc import abstractmethod +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, ClassVar, Protocol, TypeVar + +from ... import Config +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import ParseError, PropertyError + +if TYPE_CHECKING: # pragma: no cover + from .model_property import ModelProperty +else: + ModelProperty = "ModelProperty" + + +@dataclass +class Value: + """ + Some literal values in OpenAPI documents (like defaults) have to be converted into Python code safely + (with string escaping, for example). We still keep the `raw_value` around for merging `allOf`. + """ + + python_code: str + raw_value: Any + + +PropertyType = TypeVar("PropertyType", bound="PropertyProtocol") + + +class PropertyProtocol(Protocol): + """ + Describes a single property for a schema + + Attributes: + template: Name of the template file (if any) to use for this property. Must be stored in + templates/property_templates and must contain two macros: construct and transform. Construct will be used to + build this property from JSON data (a response from an API). Transform will be used to convert this property + to JSON data (when sending a request to the API). + + Raises: + ValidationError: Raised when the default value fails to be converted to the expected type + """ + + name: str + required: bool + _type_string: ClassVar[str] = "" + _json_type_string: ClassVar[str] = "" # Type of the property after JSON serialization + _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + } + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + template: ClassVar[str] = "any_property.py.jinja" + json_is_dict: ClassVar[bool] = False + + @abstractmethod + def convert_value(self, value: Any) -> Value | None | PropertyError: + """Convert a string value to a Value object""" + raise NotImplementedError() # pragma: no cover + + def validate_location(self, location: oai.ParameterLocation) -> ParseError | None: + """Returns an error if this type of property is not allowed in the given location""" + if location not in self._allowed_locations: + return ParseError(detail=f"{self.get_type_string()} is not allowed in {location}") + if location == oai.ParameterLocation.PATH and not self.required: + return ParseError(detail="Path parameter must be required") + return None + + def set_python_name(self, new_name: str, config: Config, skip_snake_case: bool = False) -> None: + """Mutates this Property to set a new python_name. + + Required to mutate due to how Properties are stored and the difficulty of updating them in-dict. + `new_name` will be validated before it is set, so `python_name` is not guaranteed to equal `new_name` after + calling this. + """ + object.__setattr__( + self, + "python_name", + PythonIdentifier(value=new_name, prefix=config.field_prefix, skip_snake_case=skip_snake_case), + ) + + def get_base_type_string(self, *, quoted: bool = False) -> str: + """Get the string describing the Python type of this property. Base types no require quoting.""" + return f'"{self._type_string}"' if not self.is_base_type and quoted else self._type_string + + def get_base_json_type_string(self, *, quoted: bool = False) -> str: + """Get the string describing the JSON type of this property. Base types no require quoting.""" + return f'"{self._json_type_string}"' if not self.is_base_type and quoted else self._json_type_string + + def get_type_string( + self, + no_optional: bool = False, + json: bool = False, + *, + multipart: bool = False, + quoted: bool = False, + ) -> str: + """ + Get a string representation of type that should be used when declaring this property + + Args: + no_optional: Do not include Optional or Unset even if the value is optional (needed for isinstance checks) + json: True if the type refers to the property after JSON serialization + multipart: True if the type should be used in a multipart request + quoted: True if the type should be wrapped in quotes (if not a base type) + """ + if json: + type_string = self.get_base_json_type_string(quoted=quoted) + elif multipart: + type_string = "Tuple[None, bytes, str]" + else: + type_string = self.get_base_type_string(quoted=quoted) + + if no_optional or self.required: + return type_string + return f"Union[Unset, {type_string}]" + + def get_instance_type_string(self) -> str: + """Get a string representation of runtime type that should be used for `isinstance` checks""" + return self.get_type_string(no_optional=True, quoted=False) + + # noinspection PyUnusedLocal + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = set() + if not self.required: + imports.add("from typing import Union") + imports.add(f"from {prefix}types import UNSET, Unset") + return imports + + def get_lazy_imports(self, *, prefix: str) -> Set[str]: + """Get a set of lazy import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + return set() + + def to_string(self) -> str: + """How this should be declared in a dataclass""" + default: str | None + if self.default is not None: + default = self.default.python_code + elif not self.required: + default = "UNSET" + else: + default = None + + if default is not None: + return f"{self.python_name}: {self.get_type_string(quoted=True)} = {default}" + return f"{self.python_name}: {self.get_type_string(quoted=True)}" + + def to_docstring(self) -> str: + """Returns property docstring""" + doc = f"{self.python_name} ({self.get_type_string()}): {self.description or ''}" + if self.default: + doc += f" Default: {self.default.python_code}." + if self.example: + doc += f" Example: {self.example}." + return doc + + @property + def is_base_type(self) -> bool: + """Base types, represented by any other of `Property` than `ModelProperty` should not be quoted.""" + from . import ListProperty, ModelProperty, UnionProperty + + return self.__class__.__name__ not in { + ModelProperty.__name__, + ListProperty.__name__, + UnionProperty.__name__, + } diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py new file mode 100644 index 000000000000..c31455ade372 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py @@ -0,0 +1,242 @@ +__all__ = [ + "Class", + "Parameters", + "ReferencePath", + "Schemas", + "parameter_from_data", + "parameter_from_reference", + "parse_reference_path", + "update_parameters_with_data", + "update_schemas_with_data", +] + +from typing import TYPE_CHECKING, NewType, Union, cast, Dict, Set, List, Tuple +from urllib.parse import urlparse + +from attrs import define, evolve, field + +from ... import Config +from ... import schema as oai +from ...schema.openapi_schema_pydantic import Parameter +from ...utils import ClassName, PythonIdentifier +from ..errors import ParameterError, ParseError, PropertyError + +if TYPE_CHECKING: # pragma: no cover + from .model_property import ModelProperty + from .property import Property +else: + ModelProperty = "ModelProperty" + Property = "Property" + + +ReferencePath = NewType("ReferencePath", str) + + +def parse_reference_path(ref_path_raw: str) -> Union[ReferencePath, ParseError]: + """ + Takes a raw string provided in a `$ref` and turns it into a validated `_ReferencePath` or a `ParseError` if + validation fails. + + See Also: + - https://swagger.io/docs/specification/using-ref/ + """ + parsed = urlparse(ref_path_raw) + if parsed.scheme or parsed.path: + return ParseError(detail=f"Remote references such as {ref_path_raw} are not supported yet.") + return cast(ReferencePath, parsed.fragment) + + +@define +class Class: + """Represents Python class which will be generated from an OpenAPI schema""" + + name: ClassName + module_name: PythonIdentifier + + @staticmethod + def from_string(*, string: str, config: Config) -> "Class": + """Get a Class from an arbitrary string""" + class_name = string.split("/")[-1] # Get rid of ref path stuff + class_name = ClassName(class_name, config.field_prefix) + override = config.class_overrides.get(class_name) + + if override is not None and override.class_name is not None: + class_name = ClassName(override.class_name, config.field_prefix) + + if override is not None and override.module_name is not None: + module_name = override.module_name + else: + module_name = class_name + module_name = PythonIdentifier(module_name, config.field_prefix) + + return Class(name=class_name, module_name=module_name) + + +@define +class Schemas: + """Structure for containing all defined, shareable, and reusable schemas (attr classes and Enums)""" + + classes_by_reference: Dict[ReferencePath, Property] = field(factory=dict) + dependencies: Dict[ReferencePath, Set[Union[ReferencePath, ClassName]]] = field(factory=dict) + classes_by_name: Dict[ClassName, Property] = field(factory=dict) + models_to_process: List[ModelProperty] = field(factory=list) + errors: List[ParseError] = field(factory=list) + + def add_dependencies(self, ref_path: ReferencePath, roots: Set[Union[ReferencePath, ClassName]]) -> None: + """Record new dependencies on the given ReferencePath + + Args: + ref_path: The ReferencePath being referenced + roots: A set of identifiers for the objects dependent on the object corresponding to `ref_path` + """ + self.dependencies.setdefault(ref_path, set()) + self.dependencies[ref_path].update(roots) + + +def update_schemas_with_data( + *, ref_path: ReferencePath, data: oai.Schema, schemas: Schemas, config: Config +) -> Union[Schemas, PropertyError]: + """ + Update a `Schemas` using some new reference. + + Args: + ref_path: The output of `parse_reference_path` (validated $ref). + data: The schema of the thing to add to Schemas. + schemas: `Schemas` up until now. + config: User-provided config for overriding default behavior. + + Returns: + Either the updated `schemas` input or a `PropertyError` if something went wrong. + + See Also: + - https://swagger.io/docs/specification/using-ref/ + """ + from . import property_from_data + + prop: Union[PropertyError, Property] + prop, schemas = property_from_data( + data=data, + name=ref_path, + schemas=schemas, + required=True, + parent_name="", + config=config, + # Don't process ModelProperty properties because schemas are still being created + process_properties=False, + roots={ref_path}, + ) + + if isinstance(prop, PropertyError): + prop.detail = f"{prop.header}: {prop.detail}" + prop.header = f"Unable to parse schema {ref_path}" + if isinstance(prop.data, oai.Reference) and prop.data.ref.endswith(ref_path): # pragma: nocover + prop.detail += ( + "\n\nRecursive and circular references are not supported directly in an array schema's 'items' section" + ) + return prop + + schemas = evolve(schemas, classes_by_reference={ref_path: prop, **schemas.classes_by_reference}) + return schemas + + +@define +class Parameters: + """Structure for containing all defined, shareable, and reusable parameters""" + + classes_by_reference: Dict[ReferencePath, Parameter] = field(factory=dict) + classes_by_name: Dict[ClassName, Parameter] = field(factory=dict) + errors: List[ParseError] = field(factory=list) + + +def parameter_from_data( + *, + name: str, + data: Union[oai.Reference, oai.Parameter], + parameters: Parameters, + config: Config, +) -> Tuple[Union[Parameter, ParameterError], Parameters]: + """Generates parameters from an OpenAPI Parameter spec.""" + + if isinstance(data, oai.Reference): + return ParameterError("Unable to resolve another reference"), parameters + + if data.param_schema is None: + return ParameterError("Parameter has no schema"), parameters + + new_param = Parameter( + name=name, + required=data.required, + explode=data.explode, + style=data.style, + param_schema=data.param_schema, + param_in=data.param_in, + ) + parameters = evolve( + parameters, classes_by_name={**parameters.classes_by_name, ClassName(name, config.field_prefix): new_param} + ) + return new_param, parameters + + +def update_parameters_with_data( + *, ref_path: ReferencePath, data: oai.Parameter, parameters: Parameters, config: Config +) -> Union[Parameters, ParameterError]: + """ + Update a `Parameters` using some new reference. + + Args: + ref_path: The output of `parse_reference_path` (validated $ref). + data: The schema of the thing to add to Schemas. + parameters: `Parameters` up until now. + + Returns: + Either the updated `parameters` input or a `PropertyError` if something went wrong. + + See Also: + - https://swagger.io/docs/specification/using-ref/ + """ + param, parameters = parameter_from_data(data=data, name=data.name, parameters=parameters, config=config) + + if isinstance(param, ParameterError): + param.detail = f"{param.header}: {param.detail}" + param.header = f"Unable to parse parameter {ref_path}" + if isinstance(param.data, oai.Reference) and param.data.ref.endswith(ref_path): # pragma: nocover + param.detail += ( + "\n\nRecursive and circular references are not supported. " + "See https://github.com/openapi-generators/openapi-python-client/issues/466" + ) + return param + + parameters = evolve(parameters, classes_by_reference={ref_path: param, **parameters.classes_by_reference}) + return parameters + + +def parameter_from_reference( + *, + param: Union[oai.Reference, Parameter], + parameters: Parameters, +) -> Union[Parameter, ParameterError]: + """ + Returns a Parameter from a Reference or the Parameter itself if one was provided. + + Args: + param: A parameter by `Reference`. + parameters: `Parameters` up until now. + + Returns: + Either the updated `schemas` input or a `PropertyError` if something went wrong. + + See Also: + - https://swagger.io/docs/specification/using-ref/ + """ + if isinstance(param, Parameter): + return param + + ref_path = parse_reference_path(param.ref) + + if isinstance(ref_path, ParseError): + return ParameterError(detail=ref_path.detail) + + _resolved_parameter_class = parameters.classes_by_reference.get(ref_path, None) + if _resolved_parameter_class is None: + return ParameterError(detail=f"Reference `{ref_path}` not found.") + return _resolved_parameter_class diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/string.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/string.py new file mode 100644 index 000000000000..7595398c5653 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/string.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from typing import Any, ClassVar, overload + +from attr import define + +from ... import schema as oai +from ... import utils +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class StringProperty(PropertyProtocol): + """A property of type str""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + _type_string: ClassVar[str] = "str" + _json_type_string: ClassVar[str] = "str" + _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> StringProperty | PropertyError: + checked_default = cls.convert_value(default) + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + @overload + def convert_value(cls, value: None) -> None: # type: ignore[misc] + ... # pragma: no cover + + @classmethod + @overload + def convert_value(cls, value: Any) -> Value: ... # pragma: no cover + + @classmethod + def convert_value(cls, value: Any) -> Value | None: + if value is None or isinstance(value, Value): + return value + if not isinstance(value, str): + value = str(value) + return Value(python_code=repr(utils.remove_string_escapes(value)), raw_value=value) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/union.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/union.py new file mode 100644 index 000000000000..407c089f8a79 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/union.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +from itertools import chain +from typing import Any, ClassVar, cast + +from attr import define, evolve + +from ... import Config +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import ParseError, PropertyError +from .protocol import PropertyProtocol, Value +from .schemas import Schemas + + +@define +class UnionProperty(PropertyProtocol): + """A property representing a Union (anyOf) of other properties""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + inner_properties: List[PropertyProtocol] + template: ClassVar[str] = "union_property.py.jinja" + + @classmethod + def build( + cls, *, data: oai.Schema, name: str, required: bool, schemas: Schemas, parent_name: str, config: Config + ) -> Tuple[UnionProperty | PropertyError, Schemas]: + """ + Create a `UnionProperty` the right way. + + Args: + data: The `Schema` describing the `UnionProperty`. + name: The name of the property where it appears in the OpenAPI document. + required: Whether this property is required where it's being used. + schemas: The `Schemas` so far describing existing classes / references. + parent_name: The name of the thing which holds this property (used for renaming inner classes). + config: User-defined config values for modifying inner properties. + + Returns: + `(result, schemas)` where `schemas` is the updated version of the input `schemas` and `result` is the + constructed `UnionProperty` or a `PropertyError` describing what went wrong. + """ + from . import property_from_data + + sub_properties: List[PropertyProtocol] = [] + + type_list_data = [] + if isinstance(data.type, list): + for _type in data.type: + type_list_data.append(data.model_copy(update={"type": _type, "default": None})) + + for i, sub_prop_data in enumerate(chain(data.anyOf, data.oneOf, type_list_data)): + sub_prop, schemas = property_from_data( + name=f"{name}_type_{i}", + required=True, + data=sub_prop_data, + schemas=schemas, + parent_name=parent_name, + config=config, + ) + if isinstance(sub_prop, PropertyError): + return PropertyError(detail=f"Invalid property in union {name}", data=sub_prop_data), schemas + sub_properties.append(sub_prop) + + def flatten_union_properties(sub_properties: List[PropertyProtocol]) -> list[PropertyProtocol]: + flattened = [] + for sub_prop in sub_properties: + if isinstance(sub_prop, UnionProperty): + flattened.extend(flatten_union_properties(sub_prop.inner_properties)) + else: + flattened.append(sub_prop) + return flattened + + sub_properties = flatten_union_properties(sub_properties) + + prop = UnionProperty( + name=name, + required=required, + default=None, + inner_properties=sub_properties, + python_name=PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ) + default_or_error = prop.convert_value(data.default) + if isinstance(default_or_error, PropertyError): + default_or_error.data = data + return default_or_error, schemas + prop = evolve(prop, default=default_or_error) + return prop, schemas + + def convert_value(self, value: Any) -> Value | None | PropertyError: + if value is None or isinstance(value, Value): + return None + value_or_error: Value | PropertyError | None = PropertyError( + detail=f"Invalid default value for union {self.name}" + ) + for sub_prop in self.inner_properties: + value_or_error = sub_prop.convert_value(value) + if not isinstance(value_or_error, PropertyError): + return value_or_error + return value_or_error + + def _get_inner_type_strings(self, json: bool, multipart: bool) -> Set[str]: + return { + p.get_type_string(no_optional=True, json=json, multipart=multipart, quoted=not p.is_base_type) + for p in self.inner_properties + } + + @staticmethod + def _get_type_string_from_inner_type_strings(inner_types: Set[str]) -> str: + if len(inner_types) == 1: + return inner_types.pop() + return f"Union[{', '.join(sorted(inner_types))}]" + + def get_base_type_string(self, *, quoted: bool = False) -> str: + return self._get_type_string_from_inner_type_strings(self._get_inner_type_strings(json=False, multipart=False)) + + def get_base_json_type_string(self, *, quoted: bool = False) -> str: + return self._get_type_string_from_inner_type_strings(self._get_inner_type_strings(json=True, multipart=False)) + + def get_type_strings_in_union(self, *, no_optional: bool = False, json: bool, multipart: bool) -> Set[str]: + """ + Get the set of all the types that should appear within the `Union` representing this property. + + This function is called from the union property macros, thus the public visibility. + + Args: + no_optional: Do not include `None` or `Unset` in this set. + json: If True, this returns the JSON types, not the Python types, of this property. + multipart: If True, this returns the multipart types, not the Python types, of this property. + + Returns: + A set of strings containing the types that should appear within `Union`. + """ + type_strings = self._get_inner_type_strings(json=json, multipart=multipart) + if no_optional: + return type_strings + if not self.required: + type_strings.add("Unset") + return type_strings + + def get_type_string( + self, + no_optional: bool = False, + json: bool = False, + *, + multipart: bool = False, + quoted: bool = False, + ) -> str: + """ + Get a string representation of type that should be used when declaring this property. + This implementation differs slightly from `Property.get_type_string` in order to collapse + nested union types. + """ + type_strings_in_union = self.get_type_strings_in_union(no_optional=no_optional, json=json, multipart=multipart) + return self._get_type_string_from_inner_type_strings(type_strings_in_union) + + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + for inner_prop in self.inner_properties: + imports.update(inner_prop.get_imports(prefix=prefix)) + imports.add("from typing import cast, Union") + return imports + + def get_lazy_imports(self, *, prefix: str) -> Set[str]: + lazy_imports = super().get_lazy_imports(prefix=prefix) + for inner_prop in self.inner_properties: + lazy_imports.update(inner_prop.get_lazy_imports(prefix=prefix)) + return lazy_imports + + def validate_location(self, location: oai.ParameterLocation) -> ParseError | None: + """Returns an error if this type of property is not allowed in the given location""" + from ..properties import Property + + for inner_prop in self.inner_properties: + if evolve(cast(Property, inner_prop), required=self.required).validate_location(location) is not None: + return ParseError(detail=f"{self.get_type_string()} is not allowed in {location}") + return None diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py new file mode 100644 index 000000000000..6b344c3bf745 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from typing import Any, ClassVar +from uuid import UUID + +from attr import define + +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class UuidProperty(PropertyProtocol): + """A property of type uuid.UUID""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "UUID" + _json_type_string: ClassVar[str] = "str" + _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + template: ClassVar[str] = "uuid_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> UuidProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if value is None or isinstance(value, Value): + return value + if isinstance(value, str): + try: + UUID(value) + except ValueError: + return PropertyError(f"Invalid UUID value: {value}") + return Value(python_code=f"UUID('{value}')", raw_value=value) + return PropertyError(f"Invalid UUID value: {value}") + + def get_imports(self, *, prefix: str) -> Set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.update({"from uuid import UUID"}) + return imports diff --git a/chaotic-openapi/chaotic_openapi/front/parser/responses.py b/chaotic-openapi/chaotic_openapi/front/parser/responses.py new file mode 100644 index 000000000000..26ebfa4af742 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/parser/responses.py @@ -0,0 +1,150 @@ +__all__ = ["Response", "response_from_data"] + +from http import HTTPStatus +from typing import Optional, TypedDict, Union, Tuple + +from attrs import define + +from openapi_python_client import utils + +from .. import Config +from .. import schema as oai +from ..utils import PythonIdentifier +from .errors import ParseError, PropertyError +from .properties import AnyProperty, Property, Schemas, property_from_data + + +class _ResponseSource(TypedDict): + """What data should be pulled from the httpx Response object""" + + attribute: str + return_type: str + + +JSON_SOURCE = _ResponseSource(attribute="response.json()", return_type="Any") +BYTES_SOURCE = _ResponseSource(attribute="response.content", return_type="bytes") +TEXT_SOURCE = _ResponseSource(attribute="response.text", return_type="str") +NONE_SOURCE = _ResponseSource(attribute="None", return_type="None") + + +@define +class Response: + """Describes a single response for an endpoint""" + + status_code: HTTPStatus + prop: Property + source: _ResponseSource + data: Union[oai.Response, oai.Reference] # Original data which created this response, useful for custom templates + + +def _source_by_content_type(content_type: str, config: Config) -> Optional[_ResponseSource]: + parsed_content_type = utils.get_content_type(content_type, config) + if parsed_content_type is None: + return None + + if parsed_content_type.startswith("text/"): + return TEXT_SOURCE + + known_content_types = { + "application/json": JSON_SOURCE, + "application/octet-stream": BYTES_SOURCE, + } + source = known_content_types.get(parsed_content_type) + if source is None and parsed_content_type.endswith("+json"): + # Implements https://www.rfc-editor.org/rfc/rfc6838#section-4.2.8 for the +json suffix + source = JSON_SOURCE + return source + + +def empty_response( + *, + status_code: HTTPStatus, + response_name: str, + config: Config, + data: Union[oai.Response, oai.Reference], +) -> Response: + """Return an untyped response, for when no response type is defined""" + return Response( + data=data, + status_code=status_code, + prop=AnyProperty( + name=response_name, + default=None, + required=True, + python_name=PythonIdentifier(value=response_name, prefix=config.field_prefix), + description=data.description if isinstance(data, oai.Response) else None, + example=None, + ), + source=NONE_SOURCE, + ) + + +def response_from_data( + *, + status_code: HTTPStatus, + data: Union[oai.Response, oai.Reference], + schemas: Schemas, + parent_name: str, + config: Config, +) -> Tuple[Union[Response, ParseError], Schemas]: + """Generate a Response from the OpenAPI dictionary representation of it""" + + response_name = f"response_{status_code}" + if isinstance(data, oai.Reference): + return ( + empty_response( + status_code=status_code, + response_name=response_name, + config=config, + data=data, + ), + schemas, + ) + + content = data.content + if not content: + return ( + empty_response( + status_code=status_code, + response_name=response_name, + config=config, + data=data, + ), + schemas, + ) + + for content_type, media_type in content.items(): + source = _source_by_content_type(content_type, config) + if source is not None: + schema_data = media_type.media_type_schema + break + else: + return ( + ParseError(data=data, detail=f"Unsupported content_type {content}"), + schemas, + ) + + if schema_data is None: + return ( + empty_response( + status_code=status_code, + response_name=response_name, + config=config, + data=data, + ), + schemas, + ) + + prop, schemas = property_from_data( + name=response_name, + required=True, + data=schema_data, + schemas=schemas, + parent_name=parent_name, + config=config, + ) + + if isinstance(prop, PropertyError): + return prop, schemas + + return Response(status_code=status_code, prop=prop, source=source, data=data), schemas diff --git a/chaotic-openapi/chaotic_openapi/front/schema/3.0.3.md b/chaotic-openapi/chaotic_openapi/front/schema/3.0.3.md new file mode 100644 index 000000000000..e21aa4655495 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/3.0.3.md @@ -0,0 +1,3454 @@ +# OpenAPI Specification + +#### Version 3.0.3 + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://tools.ietf.org/html/bcp14) [RFC2119](https://tools.ietf.org/html/rfc2119) [RFC8174](https://tools.ietf.org/html/rfc8174) when, and only when, they appear in all capitals, as shown here. + +This document is licensed under [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). + +## Introduction + +The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. + +An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases. + +## Table of Contents + + +- [Definitions](#definitions) + - [OpenAPI Document](#oasDocument) + - [Path Templating](#pathTemplating) + - [Media Types](#mediaTypes) + - [HTTP Status Codes](#httpCodes) +- [Specification](#specification) + - [Versions](#versions) + - [Format](#format) + - [Document Structure](#documentStructure) + - [Data Types](#dataTypes) + - [Rich Text Formatting](#richText) + - [Relative References In URLs](#relativeReferences) + - [Schema](#schema) + - [OpenAPI Object](#oasObject) + - [Info Object](#infoObject) + - [Contact Object](#contactObject) + - [License Object](#licenseObject) + - [Server Object](#serverObject) + - [Server Variable Object](#serverVariableObject) + - [Components Object](#componentsObject) + - [Paths Object](#pathsObject) + - [Path Item Object](#pathItemObject) + - [Operation Object](#operationObject) + - [External Documentation Object](#externalDocumentationObject) + - [Parameter Object](#parameterObject) + - [Request Body Object](#requestBodyObject) + - [Media Type Object](#mediaTypeObject) + - [Encoding Object](#encodingObject) + - [Responses Object](#responsesObject) + - [Response Object](#responseObject) + - [Callback Object](#callbackObject) + - [Example Object](#exampleObject) + - [Link Object](#linkObject) + - [Header Object](#headerObject) + - [Tag Object](#tagObject) + - [Reference Object](#referenceObject) + - [Schema Object](#schemaObject) + - [Discriminator Object](#discriminatorObject) + - [XML Object](#xmlObject) + - [Security Scheme Object](#securitySchemeObject) + - [OAuth Flows Object](#oauthFlowsObject) + - [OAuth Flow Object](#oauthFlowObject) + - [Security Requirement Object](#securityRequirementObject) + - [Specification Extensions](#specificationExtensions) + - [Security Filtering](#securityFiltering) +- [Appendix A: Revision History](#revisionHistory) + + + + +## Definitions + +##### OpenAPI Document +A document (or set of documents) that defines or describes an API. An OpenAPI definition uses and conforms to the OpenAPI Specification. + +##### Path Templating +Path templating refers to the usage of template expressions, delimited by curly braces ({}), to mark a section of a URL path as replaceable using path parameters. + +Each template expression in the path MUST correspond to a path parameter that is included in the [Path Item](#path-item-object) itself and/or in each of the Path Item's [Operations](#operation-object). + +##### Media Types +Media type definitions are spread across several resources. +The media type definitions SHOULD be in compliance with [RFC6838](https://tools.ietf.org/html/rfc6838). + +Some examples of possible media type definitions: +``` + text/plain; charset=utf-8 + application/json + application/vnd.github+json + application/vnd.github.v3+json + application/vnd.github.v3.raw+json + application/vnd.github.v3.text+json + application/vnd.github.v3.html+json + application/vnd.github.v3.full+json + application/vnd.github.v3.diff + application/vnd.github.v3.patch +``` +##### HTTP Status Codes +The HTTP Status Codes are used to indicate the status of the executed operation. +The available status codes are defined by [RFC7231](https://tools.ietf.org/html/rfc7231#section-6) and registered status codes are listed in the [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml). + +## Specification + +### Versions + +The OpenAPI Specification is versioned using [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html) (semver) and follows the semver specification. + +The `major`.`minor` portion of the semver (for example `3.0`) SHALL designate the OAS feature set. Typically, *`.patch`* versions address errors in this document, not the feature set. Tooling which supports OAS 3.0 SHOULD be compatible with all OAS 3.0.\* versions. The patch version SHOULD NOT be considered by tooling, making no distinction between `3.0.0` and `3.0.1` for example. + +Each new minor version of the OpenAPI Specification SHALL allow any OpenAPI document that is valid against any previous minor version of the Specification, within the same major version, to be updated to the new Specification version with equivalent semantics. Such an update MUST only require changing the `openapi` property to the new minor version. + +For example, a valid OpenAPI 3.0.2 document, upon changing its `openapi` property to `3.1.0`, SHALL be a valid OpenAPI 3.1.0 document, semantically equivalent to the original OpenAPI 3.0.2 document. New minor versions of the OpenAPI Specification MUST be written to ensure this form of backward compatibility. + +An OpenAPI document compatible with OAS 3.\*.\* contains a required [`openapi`](#oasVersion) field which designates the semantic version of the OAS that it uses. (OAS 2.0 documents contain a top-level version field named [`swagger`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swaggerObject) and value `"2.0"`.) + +### Format + +An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either in JSON or YAML format. + +For example, if a field has an array value, the JSON array representation will be used: + +```json +{ + "field": [ 1, 2, 3 ] +} +``` +All field names in the specification are **case sensitive**. +This includes all fields that are used as keys in a map, except where explicitly noted that keys are **case insensitive**. + +The schema exposes two types of fields: Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name. + +Patterned fields MUST have unique names within the containing object. + +In order to preserve the ability to round-trip between YAML and JSON formats, YAML version [1.2](https://yaml.org/spec/1.2/spec.html) is RECOMMENDED along with some additional constraints: + +- Tags MUST be limited to those allowed by the [JSON Schema ruleset](https://yaml.org/spec/1.2/spec.html#id2803231). +- Keys used in YAML maps MUST be limited to a scalar string, as defined by the [YAML Failsafe schema ruleset](https://yaml.org/spec/1.2/spec.html#id2802346). + +**Note:** While APIs may be defined by OpenAPI documents in either YAML or JSON format, the API request and response bodies and other content are not required to be JSON or YAML. + +### Document Structure + +An OpenAPI document MAY be made up of a single document or be divided into multiple, connected parts at the discretion of the user. In the latter case, `$ref` fields MUST be used in the specification to reference those parts as follows from the [JSON Schema](https://json-schema.org) definitions. + +It is RECOMMENDED that the root OpenAPI document be named: `openapi.json` or `openapi.yaml`. + +### Data Types + +Primitive data types in the OAS are based on the types supported by the [JSON Schema Specification Wright Draft 00](https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2). +Note that `integer` as a type is also supported and is defined as a JSON number without a fraction or exponent part. +`null` is not supported as a type (see [`nullable`](#schemaNullable) for an alternative solution). +Models are defined using the [Schema Object](#schemaObject), which is an extended subset of JSON Schema Specification Wright Draft 00. + +Primitives have an optional modifier property: `format`. +OAS uses several known formats to define in fine detail the data type being used. +However, to support documentation needs, the `format` property is an open `string`-valued property, and can have any value. +Formats such as `"email"`, `"uuid"`, and so on, MAY be used even though undefined by this specification. +Types that are not accompanied by a `format` property follow the type definition in the JSON Schema. Tools that do not recognize a specific `format` MAY default back to the `type` alone, as if the `format` is not specified. + +The formats defined by the OAS are: + +[`type`](#dataTypes) | [`format`](#dataTypeFormat) | Comments +------ | -------- | -------- +`integer` | `int32` | signed 32 bits +`integer` | `int64` | signed 64 bits (a.k.a long) +`number` | `float` | | +`number` | `double` | | +`string` | | | +`string` | `byte` | base64 encoded characters +`string` | `binary` | any sequence of octets +`boolean` | | | +`string` | `date` | As defined by `full-date` - [RFC3339](https://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14) +`string` | `date-time` | As defined by `date-time` - [RFC3339](https://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14) +`string` | `password` | A hint to UIs to obscure input. + + +### Rich Text Formatting +Throughout the specification `description` fields are noted as supporting CommonMark markdown formatting. +Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by [CommonMark 0.27](https://spec.commonmark.org/0.27/). Tooling MAY choose to ignore some CommonMark features to address security concerns. + +### Relative References in URLs + +Unless specified otherwise, all properties that are URLs MAY be relative references as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-4.2). +Relative references are resolved using the URLs defined in the [`Server Object`](#serverObject) as a Base URI. + +Relative references used in `$ref` are processed as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03), using the URL of the current document as the base URI. See also the [Reference Object](#referenceObject). + +### Schema + +In the following description, if a field is not explicitly **REQUIRED** or described with a MUST or SHALL, it can be considered OPTIONAL. + +#### OpenAPI Object + +This is the root document object of the [OpenAPI document](#oasDocument). + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +openapi | `string` | **REQUIRED**. This string MUST be the [semantic version number](https://semver.org/spec/v2.0.0.html) of the [OpenAPI Specification version](#versions) that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document. This is *not* related to the API [`info.version`](#infoVersion) string. +info | [Info Object](#infoObject) | **REQUIRED**. Provides metadata about the API. The metadata MAY be used by tooling as required. +servers | [[Server Object](#serverObject)] | An array of Server Objects, which provide connectivity information to a target server. If the `servers` property is not provided, or is an empty array, the default value would be a [Server Object](#serverObject) with a [url](#serverUrl) value of `/`. +paths | [Paths Object](#pathsObject) | **REQUIRED**. The available paths and operations for the API. +components | [Components Object](#componentsObject) | An element to hold various schemas for the specification. +security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement (`{}`) can be included in the array. +tags | [[Tag Object](#tagObject)] | A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](#operationObject) must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### Info Object + +The object provides metadata about the API. +The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +title | `string` | **REQUIRED**. The title of the API. +description | `string` | A short description of the API. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +termsOfService | `string` | A URL to the Terms of Service for the API. MUST be in the format of a URL. +contact | [Contact Object](#contactObject) | The contact information for the exposed API. +license | [License Object](#licenseObject) | The license information for the exposed API. +version | `string` | **REQUIRED**. The version of the OpenAPI document (which is distinct from the [OpenAPI Specification version](#oasVersion) or the API implementation version). + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Info Object Example + +```json +{ + "title": "Sample Pet Store App", + "description": "This is a sample server for a pet store.", + "termsOfService": "http://example.com/terms/", + "contact": { + "name": "API Support", + "url": "http://www.example.com/support", + "email": "support@example.com" + }, + "license": { + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.1" +} +``` + +```yaml +title: Sample Pet Store App +description: This is a sample server for a pet store. +termsOfService: http://example.com/terms/ +contact: + name: API Support + url: http://www.example.com/support + email: support@example.com +license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +version: 1.0.1 +``` + +#### Contact Object + +Contact information for the exposed API. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +name | `string` | The identifying name of the contact person/organization. +url | `string` | The URL pointing to the contact information. MUST be in the format of a URL. +email | `string` | The email address of the contact person/organization. MUST be in the format of an email address. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Contact Object Example + +```json +{ + "name": "API Support", + "url": "http://www.example.com/support", + "email": "support@example.com" +} +``` + +```yaml +name: API Support +url: http://www.example.com/support +email: support@example.com +``` + +#### License Object + +License information for the exposed API. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The license name used for the API. +url | `string` | A URL to the license used for the API. MUST be in the format of a URL. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### License Object Example + +```json +{ + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html" +} +``` + +```yaml +name: Apache 2.0 +url: https://www.apache.org/licenses/LICENSE-2.0.html +``` + +#### Server Object + +An object representing a Server. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +url | `string` | **REQUIRED**. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{`brackets`}`. +description | `string` | An optional string describing the host designated by the URL. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +variables | Map[`string`, [Server Variable Object](#serverVariableObject)] | A map between a variable name and its value. The value is used for substitution in the server's URL template. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Server Object Example + +A single server would be described as: + +```json +{ + "url": "https://development.gigantic-server.com/v1", + "description": "Development server" +} +``` + +```yaml +url: https://development.gigantic-server.com/v1 +description: Development server +``` + +The following shows how multiple servers can be described, for example, at the OpenAPI Object's [`servers`](#oasServers): + +```json +{ + "servers": [ + { + "url": "https://development.gigantic-server.com/v1", + "description": "Development server" + }, + { + "url": "https://staging.gigantic-server.com/v1", + "description": "Staging server" + }, + { + "url": "https://api.gigantic-server.com/v1", + "description": "Production server" + } + ] +} +``` + +```yaml +servers: +- url: https://development.gigantic-server.com/v1 + description: Development server +- url: https://staging.gigantic-server.com/v1 + description: Staging server +- url: https://api.gigantic-server.com/v1 + description: Production server +``` + +The following shows how variables can be used for a server configuration: + +```json +{ + "servers": [ + { + "url": "https://{username}.gigantic-server.com:{port}/{basePath}", + "description": "The production API server", + "variables": { + "username": { + "default": "demo", + "description": "this value is assigned by the service provider, in this example `gigantic-server.com`" + }, + "port": { + "enum": [ + "8443", + "443" + ], + "default": "8443" + }, + "basePath": { + "default": "v2" + } + } + } + ] +} +``` + +```yaml +servers: +- url: https://{username}.gigantic-server.com:{port}/{basePath} + description: The production API server + variables: + username: + # note! no enum here means it is an open value + default: demo + description: this value is assigned by the service provider, in this example `gigantic-server.com` + port: + enum: + - '8443' + - '443' + default: '8443' + basePath: + # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2` + default: v2 +``` + + +#### Server Variable Object + +An object representing a Server Variable for server URL template substitution. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +enum | [`string`] | An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty. +default | `string` | **REQUIRED**. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. Note this behavior is different than the [Schema Object's](#schemaObject) treatment of default values, because in those cases parameter values are optional. If the [`enum`](#serverVariableEnum) is defined, the value SHOULD exist in the enum's values. +description | `string` | An optional description for the server variable. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### Components Object + +Holds a set of reusable objects for different aspects of the OAS. +All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. + + +##### Fixed Fields + +Field Name | Type | Description +---|:---|--- + schemas | Map[`string`, [Schema Object](#schemaObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Schema Objects](#schemaObject). + responses | Map[`string`, [Response Object](#responseObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Response Objects](#responseObject). + parameters | Map[`string`, [Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Parameter Objects](#parameterObject). + examples | Map[`string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Example Objects](#exampleObject). + requestBodies | Map[`string`, [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Request Body Objects](#requestBodyObject). + headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Header Objects](#headerObject). + securitySchemes| Map[`string`, [Security Scheme Object](#securitySchemeObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Security Scheme Objects](#securitySchemeObject). + links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Link Objects](#linkObject). + callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Callback Objects](#callbackObject). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`. + +Field Name Examples: + +``` +User +User_1 +User_Name +user-name +my.org.User +``` + +##### Components Object Example + +```json +"components": { + "schemas": { + "GeneralError": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + } + }, + "parameters": { + "skipParam": { + "name": "skip", + "in": "query", + "description": "number of items to skip", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + } + }, + "limitParam": { + "name": "limit", + "in": "query", + "description": "max records to return", + "required": true, + "schema" : { + "type": "integer", + "format": "int32" + } + } + }, + "responses": { + "NotFound": { + "description": "Entity not found." + }, + "IllegalInput": { + "description": "Illegal input for operation." + }, + "GeneralError": { + "description": "General Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GeneralError" + } + } + } + } + }, + "securitySchemes": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "http://example.org/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } + } + } +} +``` + +```yaml +components: + schemas: + GeneralError: + type: object + properties: + code: + type: integer + format: int32 + message: + type: string + Category: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + parameters: + skipParam: + name: skip + in: query + description: number of items to skip + required: true + schema: + type: integer + format: int32 + limitParam: + name: limit + in: query + description: max records to return + required: true + schema: + type: integer + format: int32 + responses: + NotFound: + description: Entity not found. + IllegalInput: + description: Illegal input for operation. + GeneralError: + description: General Error + content: + application/json: + schema: + $ref: '#/components/schemas/GeneralError' + securitySchemes: + api_key: + type: apiKey + name: api_key + in: header + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: http://example.org/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + + +#### Paths Object + +Holds the relative paths to the individual endpoints and their operations. +The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. The Paths MAY be empty, due to [ACL constraints](#securityFiltering). + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +/{path} | [Path Item Object](#pathItemObject) | A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is **appended** (no relative URL resolution) to the expanded URL from the [`Server Object`](#serverObject)'s `url` field in order to construct the full URL. [Path templating](#pathTemplating) is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Path Templating Matching + +Assuming the following paths, the concrete definition, `/pets/mine`, will be matched first if used: + +``` + /pets/{petId} + /pets/mine +``` + +The following paths are considered identical and invalid: + +``` + /pets/{petId} + /pets/{name} +``` + +The following may lead to ambiguous resolution: + +``` + /{entity}/me + /books/{id} +``` + +##### Paths Object Example + +```json +{ + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "responses": { + "200": { + "description": "A list of pets.", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/pet" + } + } + } + } + } + } + } + } +} +``` + +```yaml +/pets: + get: + description: Returns all pets from the system that the user has access to + responses: + '200': + description: A list of pets. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/pet' +``` + +#### Path Item Object + +Describes the operations available on a single path. +A Path Item MAY be empty, due to [ACL constraints](#securityFiltering). +The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +$ref | `string` | Allows for an external definition of this path item. The referenced structure MUST be in the format of a [Path Item Object](#pathItemObject). In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. +summary| `string` | An optional, string summary, intended to apply to all operations in this path. +description | `string` | An optional, string description, intended to apply to all operations in this path. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +get | [Operation Object](#operationObject) | A definition of a GET operation on this path. +put | [Operation Object](#operationObject) | A definition of a PUT operation on this path. +post | [Operation Object](#operationObject) | A definition of a POST operation on this path. +delete | [Operation Object](#operationObject) | A definition of a DELETE operation on this path. +options | [Operation Object](#operationObject) | A definition of a OPTIONS operation on this path. +head | [Operation Object](#operationObject) | A definition of a HEAD operation on this path. +patch | [Operation Object](#operationObject) | A definition of a PATCH operation on this path. +trace | [Operation Object](#operationObject) | A definition of a TRACE operation on this path. +servers | [[Server Object](#serverObject)] | An alternative `server` array to service all operations in this path. +parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Path Item Object Example + +```json +{ + "get": { + "description": "Returns pets based on ID", + "summary": "Find pets by ID", + "operationId": "getPetsById", + "responses": { + "200": { + "description": "pet response", + "content": { + "*/*": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Pet" + } + } + } + } + }, + "default": { + "description": "error payload", + "content": { + "text/html": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to use", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "simple" + } + ] +} +``` + +```yaml +get: + description: Returns pets based on ID + summary: Find pets by ID + operationId: getPetsById + responses: + '200': + description: pet response + content: + '*/*' : + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + default: + description: error payload + content: + 'text/html': + schema: + $ref: '#/components/schemas/ErrorModel' +parameters: +- name: id + in: path + description: ID of pet to use + required: true + schema: + type: array + items: + type: string + style: simple +``` + +#### Operation Object + +Describes a single API operation on a path. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +tags | [`string`] | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. +summary | `string` | A short summary of what the operation does. +description | `string` | A verbose explanation of the operation behavior. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this operation. +operationId | `string` | Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is **case-sensitive**. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. +parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for this operation. If a parameter is already defined at the [Path Item](#pathItemParameters), the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). +requestBody | [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject) | The request body applicable for this operation. The `requestBody` is only supported in HTTP methods where the HTTP 1.1 specification [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, `requestBody` SHALL be ignored by consumers. +responses | [Responses Object](#responsesObject) | **REQUIRED**. The list of possible responses as they are returned from executing this operation. +callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a [Callback Object](#callbackObject) that describes a request that may be initiated by the API provider and the expected responses. +deprecated | `boolean` | Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`. +security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level [`security`](#oasSecurity). To remove a top-level security declaration, an empty array can be used. +servers | [[Server Object](#serverObject)] | An alternative `server` array to service this operation. If an alternative `server` object is specified at the Path Item Object or Root level, it will be overridden by this value. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Operation Object Example + +```json +{ + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "operationId": "updatePetWithForm", + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "Updated name of the pet", + "type": "string" + }, + "status": { + "description": "Updated status of the pet", + "type": "string" + } + }, + "required": ["status"] + } + } + } + }, + "responses": { + "200": { + "description": "Pet updated.", + "content": { + "application/json": {}, + "application/xml": {} + } + }, + "405": { + "description": "Method Not Allowed", + "content": { + "application/json": {}, + "application/xml": {} + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] +} +``` + +```yaml +tags: +- pet +summary: Updates a pet in the store with form data +operationId: updatePetWithForm +parameters: +- name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: string +requestBody: + content: + 'application/x-www-form-urlencoded': + schema: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + required: + - status +responses: + '200': + description: Pet updated. + content: + 'application/json': {} + 'application/xml': {} + '405': + description: Method Not Allowed + content: + 'application/json': {} + 'application/xml': {} +security: +- petstore_auth: + - write:pets + - read:pets +``` + + +#### External Documentation Object + +Allows referencing an external resource for extended documentation. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +description | `string` | A short description of the target documentation. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +url | `string` | **REQUIRED**. The URL for the target documentation. Value MUST be in the format of a URL. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### External Documentation Object Example + +```json +{ + "description": "Find more info here", + "url": "https://example.com" +} +``` + +```yaml +description: Find more info here +url: https://example.com +``` + +#### Parameter Object + +Describes a single operation parameter. + +A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). + +##### Parameter Locations +There are four possible parameter locations specified by the `in` field: +* path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. +* query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. +* header - Custom headers that are expected as part of the request. Note that [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. +* cookie - Used to pass a specific cookie value to the API. + + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The name of the parameter. Parameter names are *case sensitive*. +in | `string` | **REQUIRED**. The location of the parameter. Possible values are `"query"`, `"header"`, `"path"` or `"cookie"`. +description | `string` | A brief description of the parameter. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +required | `boolean` | Determines whether this parameter is mandatory. If the [parameter location](#parameterIn) is `"path"`, this property is **REQUIRED** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. + deprecated | `boolean` | Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`. + allowEmptyValue | `boolean` | Sets the ability to pass empty-valued parameters. This is valid only for `query` parameters and allows sending a parameter with an empty value. Default value is `false`. If [`style`](#parameterStyle) is used, and if behavior is `n/a` (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision. + +The rules for serialization of the parameter are specified in one of two ways. +For simpler scenarios, a [`schema`](#parameterSchema) and [`style`](#parameterStyle) can describe the structure and syntax of the parameter. + +Field Name | Type | Description +---|:---:|--- +style | `string` | Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `query` - `form`; for `path` - `simple`; for `header` - `simple`; for `cookie` - `form`. +explode | `boolean` | When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this property has no effect. When [`style`](#parameterStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. +allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. This property only applies to parameters with an `in` value of `query`. The default value is `false`. +schema | [Schema Object](#schemaObject) \| [Reference Object](#referenceObject) | The schema defining the type used for the parameter. +example | Any | Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` that contains an example, the `example` value SHALL _override_ the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary. +examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` that contains an example, the `examples` value SHALL _override_ the example provided by the schema. + +For more complex scenarios, the [`content`](#parameterContent) property can define the media type and schema of the parameter. +A parameter MUST contain either a `schema` property, or a `content` property, but not both. +When `example` or `examples` are provided in conjunction with the `schema` object, the example MUST follow the prescribed serialization strategy for the parameter. + + +Field Name | Type | Description +---|:---:|--- +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. + +##### Style Values + +In order to support common ways of serializing simple parameters, a set of `style` values are defined. + +`style` | [`type`](#dataTypes) | `in` | Comments +----------- | ------ | -------- | -------- +matrix | `primitive`, `array`, `object` | `path` | Path-style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7) +label | `primitive`, `array`, `object` | `path` | Label style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.5) +form | `primitive`, `array`, `object` | `query`, `cookie` | Form style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.8). This option replaces `collectionFormat` with a `csv` (when `explode` is false) or `multi` (when `explode` is true) value from OpenAPI 2.0. +simple | `array` | `path`, `header` | Simple style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.2). This option replaces `collectionFormat` with a `csv` value from OpenAPI 2.0. +spaceDelimited | `array` | `query` | Space separated array values. This option replaces `collectionFormat` equal to `ssv` from OpenAPI 2.0. +pipeDelimited | `array` | `query` | Pipe separated array values. This option replaces `collectionFormat` equal to `pipes` from OpenAPI 2.0. +deepObject | `object` | `query` | Provides a simple way of rendering nested objects using form parameters. + + +##### Style Examples + +Assume a parameter named `color` has one of the following values: + +``` + string -> "blue" + array -> ["blue","black","brown"] + object -> { "R": 100, "G": 200, "B": 150 } +``` +The following table shows examples of rendering differences for each value. + +[`style`](#dataTypeFormat) | `explode` | `empty` | `string` | `array` | `object` +----------- | ------ | -------- | -------- | -------- | ------- +matrix | false | ;color | ;color=blue | ;color=blue,black,brown | ;color=R,100,G,200,B,150 +matrix | true | ;color | ;color=blue | ;color=blue;color=black;color=brown | ;R=100;G=200;B=150 +label | false | . | .blue | .blue.black.brown | .R.100.G.200.B.150 +label | true | . | .blue | .blue.black.brown | .R=100.G=200.B=150 +form | false | color= | color=blue | color=blue,black,brown | color=R,100,G,200,B,150 +form | true | color= | color=blue | color=blue&color=black&color=brown | R=100&G=200&B=150 +simple | false | n/a | blue | blue,black,brown | R,100,G,200,B,150 +simple | true | n/a | blue | blue,black,brown | R=100,G=200,B=150 +spaceDelimited | false | n/a | n/a | blue%20black%20brown | R%20100%20G%20200%20B%20150 +pipeDelimited | false | n/a | n/a | blue\|black\|brown | R\|100\|G\|200\|B\|150 +deepObject | true | n/a | n/a | n/a | color[R]=100&color[G]=200&color[B]=150 + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Parameter Object Examples + +A header parameter with an array of 64 bit integer numbers: + +```json +{ + "name": "token", + "in": "header", + "description": "token to be passed as a header", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int64" + } + }, + "style": "simple" +} +``` + +```yaml +name: token +in: header +description: token to be passed as a header +required: true +schema: + type: array + items: + type: integer + format: int64 +style: simple +``` + +A path parameter of a string value: +```json +{ + "name": "username", + "in": "path", + "description": "username to fetch", + "required": true, + "schema": { + "type": "string" + } +} +``` + +```yaml +name: username +in: path +description: username to fetch +required: true +schema: + type: string +``` + +An optional query parameter of a string value, allowing multiple values by repeating the query parameter: +```json +{ + "name": "id", + "in": "query", + "description": "ID of the object to fetch", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "form", + "explode": true +} +``` + +```yaml +name: id +in: query +description: ID of the object to fetch +required: false +schema: + type: array + items: + type: string +style: form +explode: true +``` + +A free-form query parameter, allowing undefined parameters of a specific type: +```json +{ + "in": "query", + "name": "freeForm", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer" + }, + }, + "style": "form" +} +``` + +```yaml +in: query +name: freeForm +schema: + type: object + additionalProperties: + type: integer +style: form +``` + +A complex parameter using `content` to define serialization: + +```json +{ + "in": "query", + "name": "coordinates", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "lat", + "long" + ], + "properties": { + "lat": { + "type": "number" + }, + "long": { + "type": "number" + } + } + } + } + } +} +``` + +```yaml +in: query +name: coordinates +content: + application/json: + schema: + type: object + required: + - lat + - long + properties: + lat: + type: number + long: + type: number +``` + +#### Request Body Object + +Describes a single request body. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +description | `string` | A brief description of the request body. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | **REQUIRED**. The content of the request body. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* +required | `boolean` | Determines if the request body is required in the request. Defaults to `false`. + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Request Body Examples + +A request body with a referenced model definition. +```json +{ + "description": "user to add to the system", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + }, + "examples": { + "user" : { + "summary": "User Example", + "externalValue": "http://foo.bar/examples/user-example.json" + } + } + }, + "application/xml": { + "schema": { + "$ref": "#/components/schemas/User" + }, + "examples": { + "user" : { + "summary": "User example in XML", + "externalValue": "http://foo.bar/examples/user-example.xml" + } + } + }, + "text/plain": { + "examples": { + "user" : { + "summary": "User example in Plain text", + "externalValue": "http://foo.bar/examples/user-example.txt" + } + } + }, + "*/*": { + "examples": { + "user" : { + "summary": "User example in other format", + "externalValue": "http://foo.bar/examples/user-example.whatever" + } + } + } + } +} +``` + +```yaml +description: user to add to the system +content: + 'application/json': + schema: + $ref: '#/components/schemas/User' + examples: + user: + summary: User Example + externalValue: 'http://foo.bar/examples/user-example.json' + 'application/xml': + schema: + $ref: '#/components/schemas/User' + examples: + user: + summary: User Example in XML + externalValue: 'http://foo.bar/examples/user-example.xml' + 'text/plain': + examples: + user: + summary: User example in text plain format + externalValue: 'http://foo.bar/examples/user-example.txt' + '*/*': + examples: + user: + summary: User example in other format + externalValue: 'http://foo.bar/examples/user-example.whatever' +``` + +A body parameter that is an array of string values: +```json +{ + "description": "user to add to the system", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + } +} +``` + +```yaml +description: user to add to the system +required: true +content: + text/plain: + schema: + type: array + items: + type: string +``` + + +#### Media Type Object +Each Media Type Object provides schema and examples for the media type identified by its key. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +schema | [Schema Object](#schemaObject) \| [Reference Object](#referenceObject) | The schema defining the content of the request, response, or parameter. +example | Any | Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` which contains an example, the `example` value SHALL _override_ the example provided by the schema. +examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` which contains an example, the `examples` value SHALL _override_ the example provided by the schema. +encoding | Map[`string`, [Encoding Object](#encodingObject)] | A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to `requestBody` objects when the media type is `multipart` or `application/x-www-form-urlencoded`. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Media Type Examples + +```json +{ + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pet" + }, + "examples": { + "cat" : { + "summary": "An example of a cat", + "value": + { + "name": "Fluffy", + "petType": "Cat", + "color": "White", + "gender": "male", + "breed": "Persian" + } + }, + "dog": { + "summary": "An example of a dog with a cat's name", + "value" : { + "name": "Puma", + "petType": "Dog", + "color": "Black", + "gender": "Female", + "breed": "Mixed" + }, + "frog": { + "$ref": "#/components/examples/frog-example" + } + } + } + } +} +``` + +```yaml +application/json: + schema: + $ref: "#/components/schemas/Pet" + examples: + cat: + summary: An example of a cat + value: + name: Fluffy + petType: Cat + color: White + gender: male + breed: Persian + dog: + summary: An example of a dog with a cat's name + value: + name: Puma + petType: Dog + color: Black + gender: Female + breed: Mixed + frog: + $ref: "#/components/examples/frog-example" +``` + +##### Considerations for File Uploads + +In contrast with the 2.0 specification, `file` input/output content in OpenAPI is described with the same semantics as any other schema type. Specifically: + +```yaml +# content transferred with base64 encoding +schema: + type: string + format: base64 +``` + +```yaml +# content transferred in binary (octet-stream): +schema: + type: string + format: binary +``` + +These examples apply to either input payloads of file uploads or response payloads. + +A `requestBody` for submitting a file in a `POST` operation may look like the following example: + +```yaml +requestBody: + content: + application/octet-stream: + schema: + # a binary file of any type + type: string + format: binary +``` + +In addition, specific media types MAY be specified: + +```yaml +# multiple, specific media types may be specified: +requestBody: + content: + # a binary file of type png or jpeg + 'image/jpeg': + schema: + type: string + format: binary + 'image/png': + schema: + type: string + format: binary +``` + +To upload multiple files, a `multipart` media type MUST be used: + +```yaml +requestBody: + content: + multipart/form-data: + schema: + properties: + # The property name 'file' will be used for all files. + file: + type: array + items: + type: string + format: binary + +``` + +##### Support for x-www-form-urlencoded Request Bodies + +To submit content using form url encoding via [RFC1866](https://tools.ietf.org/html/rfc1866), the following +definition may be used: + +```yaml +requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + # complex types are stringified to support RFC 1866 + type: object + properties: {} +``` + +In this example, the contents in the `requestBody` MUST be stringified per [RFC1866](https://tools.ietf.org/html/rfc1866/) when passed to the server. In addition, the `address` field complex object will be stringified. + +When passing complex objects in the `application/x-www-form-urlencoded` content type, the default serialization strategy of such properties is described in the [`Encoding Object`](#encodingObject)'s [`style`](#encodingStyle) property as `form`. + +##### Special Considerations for `multipart` Content + +It is common to use `multipart/form-data` as a `Content-Type` when transferring request bodies to operations. In contrast to 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content. This supports complex structures as well as supporting mechanisms for multiple file uploads. + +When passing in `multipart` types, boundaries MAY be used to separate sections of the content being transferred — thus, the following default `Content-Type`s are defined for `multipart`: + +* If the property is a primitive, or an array of primitive values, the default Content-Type is `text/plain` +* If the property is complex, or an array of complex values, the default Content-Type is `application/json` +* If the property is a `type: string` with `format: binary` or `format: base64` (aka a file object), the default Content-Type is `application/octet-stream` + + +Examples: + +```yaml +requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + # default Content-Type for objects is `application/json` + type: object + properties: {} + profileImage: + # default Content-Type for string/binary is `application/octet-stream` + type: string + format: binary + children: + # default Content-Type for arrays is based on the `inner` type (text/plain here) + type: array + items: + type: string + addresses: + # default Content-Type for arrays is based on the `inner` type (object shown, so `application/json` in this example) + type: array + items: + type: '#/components/schemas/Address' +``` + +An `encoding` attribute is introduced to give you control over the serialization of parts of `multipart` request bodies. This attribute is _only_ applicable to `multipart` and `application/x-www-form-urlencoded` request bodies. + +#### Encoding Object + +A single encoding definition applied to a single schema property. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +contentType | `string` | The Content-Type for encoding a specific property. Default value depends on the property type: for `string` with `format` being `binary` – `application/octet-stream`; for other primitive types – `text/plain`; for `object` - `application/json`; for `array` – the default is defined based on the inner type. The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or a comma-separated list of the two types. +headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | A map allowing additional information to be provided as headers, for example `Content-Disposition`. `Content-Type` is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a `multipart`. +style | `string` | Describes how a specific property value will be serialized depending on its type. See [Parameter Object](#parameterObject) for details on the [`style`](#parameterStyle) property. The behavior follows the same values as `query` parameters, including default values. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. +explode | `boolean` | When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When [`style`](#encodingStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. +allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Encoding Object Example + +```yaml +requestBody: + content: + multipart/mixed: + schema: + type: object + properties: + id: + # default is text/plain + type: string + format: uuid + address: + # default is application/json + type: object + properties: {} + historyMetadata: + # need to declare XML format! + description: metadata in XML format + type: object + properties: {} + profileImage: + # default is application/octet-stream, need to declare an image type only! + type: string + format: binary + encoding: + historyMetadata: + # require XML Content-Type in utf-8 encoding + contentType: application/xml; charset=utf-8 + profileImage: + # only accept png/jpeg + contentType: image/png, image/jpeg + headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer +``` + +#### Responses Object + +A container for the expected responses of an operation. +The container maps a HTTP response code to the expected response. + +The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. +However, documentation is expected to cover a successful operation response and any known errors. + +The `default` MAY be used as a default response object for all HTTP codes +that are not covered individually by the specification. + +The `Responses Object` MUST contain at least one response code, and it +SHOULD be the response for a successful operation call. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +default | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. A [Reference Object](#referenceObject) can link to a response that the [OpenAPI Object's components/responses](#componentsResponses) section defines. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +[HTTP Status Code](#httpCodes) | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | Any [HTTP status code](#httpCodes) can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. A [Reference Object](#referenceObject) can link to a response that is defined in the [OpenAPI Object's components/responses](#componentsResponses) section. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `[200-299]`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Responses Object Example + +A 200 response for a successful operation and a default response for others (implying an error): + +```json +{ + "200": { + "description": "a pet to be returned", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pet" + } + } + } + }, + "default": { + "description": "Unexpected error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } +} +``` + +```yaml +'200': + description: a pet to be returned + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +default: + description: Unexpected error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorModel' +``` + +#### Response Object +Describes a single response from an API Operation, including design-time, static +`links` to operations based on the response. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +description | `string` | **REQUIRED**. A short description of the response. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | Maps a header name to its definition. [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL be ignored. +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing descriptions of potential response payloads. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* +links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for [Component Objects](#componentsObject). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Response Object Examples + +Response of an array of a complex type: + +```json +{ + "description": "A complex object array response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VeryComplexType" + } + } + } + } +} +``` + +```yaml +description: A complex object array response +content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/VeryComplexType' +``` + +Response with a string type: + +```json +{ + "description": "A simple string response", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + +} +``` + +```yaml +description: A simple string response +content: + text/plain: + schema: + type: string +``` + +Plain text response with headers: + +```json +{ + "description": "A simple string response", + "content": { + "text/plain": { + "schema": { + "type": "string", + "example": "whoa!" + } + } + }, + "headers": { + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Remaining": { + "description": "The number of remaining requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Reset": { + "description": "The number of seconds left in the current period", + "schema": { + "type": "integer" + } + } + } +} +``` + +```yaml +description: A simple string response +content: + text/plain: + schema: + type: string + example: 'whoa!' +headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer + X-Rate-Limit-Remaining: + description: The number of remaining requests in the current period + schema: + type: integer + X-Rate-Limit-Reset: + description: The number of seconds left in the current period + schema: + type: integer +``` + +Response with no return value: + +```json +{ + "description": "object created" +} +``` + +```yaml +description: object created +``` + +#### Callback Object + +A map of possible out-of band callbacks related to the parent operation. +Each value in the map is a [Path Item Object](#pathItemObject) that describes a set of requests that may be initiated by the API provider and the expected responses. +The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +{expression} | [Path Item Object](#pathItemObject) | A Path Item Object used to define a callback request and expected responses. A [complete example](../examples/v3.0/callback-example.yaml) is available. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Key Expression + +The key that identifies the [Path Item Object](#pathItemObject) is a [runtime expression](#runtimeExpression) that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. +A simple example might be `$request.body#/url`. +However, using a [runtime expression](#runtimeExpression) the complete HTTP message can be accessed. +This includes accessing any part of a body that a JSON Pointer [RFC6901](https://tools.ietf.org/html/rfc6901) can reference. + +For example, given the following HTTP request: + +```http +POST /subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning HTTP/1.1 +Host: example.org +Content-Type: application/json +Content-Length: 187 + +{ + "failedUrl" : "http://clientdomain.com/failed", + "successUrls" : [ + "http://clientdomain.com/fast", + "http://clientdomain.com/medium", + "http://clientdomain.com/slow" + ] +} + +201 Created +Location: http://example.org/subscription/1 +``` + +The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named `eventType` and a query parameter named `queryUrl`. + +Expression | Value +---|:--- +$url | http://example.org/subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning +$method | POST +$request.path.eventType | myevent +$request.query.queryUrl | http://clientdomain.com/stillrunning +$request.header.content-Type | application/json +$request.body#/failedUrl | http://clientdomain.com/failed +$request.body#/successUrls/2 | http://clientdomain.com/medium +$response.header.Location | http://example.org/subscription/1 + + +##### Callback Object Examples + +The following example uses the user provided `queryUrl` query string parameter to define the callback URL. This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook. + +```yaml +myCallback: + '{$request.query.queryUrl}': + post: + requestBody: + description: Callback payload + content: + 'application/json': + schema: + $ref: '#/components/schemas/SomePayload' + responses: + '200': + description: callback successfully processed +``` + +The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the `id` and `email` property in the request body. + +```yaml +transactionCallback: + 'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}': + post: + requestBody: + description: Callback payload + content: + 'application/json': + schema: + $ref: '#/components/schemas/SomePayload' + responses: + '200': + description: callback successfully processed +``` + +#### Example Object + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +summary | `string` | Short description for the example. +description | `string` | Long description for the example. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +value | Any | Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary. +externalValue | `string` | A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +In all cases, the example value is expected to be compatible with the type schema +of its associated value. Tooling implementations MAY choose to +validate compatibility automatically, and reject the example value(s) if incompatible. + +##### Example Object Examples + +In a request body: + +```yaml +requestBody: + content: + 'application/json': + schema: + $ref: '#/components/schemas/Address' + examples: + foo: + summary: A foo example + value: {"foo": "bar"} + bar: + summary: A bar example + value: {"bar": "baz"} + 'application/xml': + examples: + xmlExample: + summary: This is an example in XML + externalValue: 'http://example.org/examples/address-example.xml' + 'text/plain': + examples: + textExample: + summary: This is a text example + externalValue: 'http://foo.bar/examples/address-example.txt' +``` + +In a parameter: + +```yaml +parameters: + - name: 'zipCode' + in: 'query' + schema: + type: 'string' + format: 'zip-code' + examples: + zip-example: + $ref: '#/components/examples/zip-example' +``` + +In a response: + +```yaml +responses: + '200': + description: your car appointment has been booked + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessResponse' + examples: + confirmation-success: + $ref: '#/components/examples/confirmation-success' +``` + + +#### Link Object + +The `Link object` represents a possible design-time link for a response. +The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. + +Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. + +For computing links, and providing instructions to execute them, a [runtime expression](#runtimeExpression) is used for accessing values in an operation and using them as parameters while invoking the linked operation. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +operationRef | `string` | A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an [Operation Object](#operationObject). Relative `operationRef` values MAY be used to locate an existing [Operation Object](#operationObject) in the OpenAPI definition. +operationId | `string` | The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field. +parameters | Map[`string`, Any \| [{expression}](#runtimeExpression)] | A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the [parameter location](#parameterIn) `[{in}.]{name}` for operations that use the same parameter name in different locations (e.g. path.id). +requestBody | Any \| [{expression}](#runtimeExpression) | A literal value or [{expression}](#runtimeExpression) to use as a request body when calling the target operation. +description | `string` | A description of the link. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +server | [Server Object](#serverObject) | A server object to be used by the target operation. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +A linked operation MUST be identified using either an `operationRef` or `operationId`. +In the case of an `operationId`, it MUST be unique and resolved in the scope of the OAS document. +Because of the potential for name clashes, the `operationRef` syntax is preferred +for specifications with external references. + +##### Examples + +Computing a link from a request operation where the `$request.path.id` is used to pass a request parameter to the linked operation. + +```yaml +paths: + /users/{id}: + parameters: + - name: id + in: path + required: true + description: the user identifier, as userId + schema: + type: string + get: + responses: + '200': + description: the user being returned + content: + application/json: + schema: + type: object + properties: + uuid: # the unique user id + type: string + format: uuid + links: + address: + # the target link operationId + operationId: getUserAddress + parameters: + # get the `id` field from the request path parameter named `id` + userId: $request.path.id + # the path item of the linked operation + /users/{userid}/address: + parameters: + - name: userid + in: path + required: true + description: the user identifier, as userId + schema: + type: string + # linked operation + get: + operationId: getUserAddress + responses: + '200': + description: the user's address +``` + +When a runtime expression fails to evaluate, no parameter value is passed to the target operation. + +Values from the response body can be used to drive a linked operation. + +```yaml +links: + address: + operationId: getUserAddressByUUID + parameters: + # get the `uuid` field from the `uuid` field in the response body + userUuid: $response.body#/uuid +``` + +Clients follow all links at their discretion. +Neither permissions, nor the capability to make a successful call to that link, is guaranteed +solely by the existence of a relationship. + + +##### OperationRef Examples + +As references to `operationId` MAY NOT be possible (the `operationId` is an optional +field in an [Operation Object](#operationObject)), references MAY also be made through a relative `operationRef`: + +```yaml +links: + UserRepositories: + # returns array of '#/components/schemas/repository' + operationRef: '#/paths/~12.0~1repositories~1{username}/get' + parameters: + username: $response.body#/username +``` + +or an absolute `operationRef`: + +```yaml +links: + UserRepositories: + # returns array of '#/components/schemas/repository' + operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get' + parameters: + username: $response.body#/username +``` + +Note that in the use of `operationRef`, the _escaped forward-slash_ is necessary when +using JSON references. + + +##### Runtime Expressions + +Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. +This mechanism is used by [Link Objects](#linkObject) and [Callback Objects](#callbackObject). + +The runtime expression is defined by the following [ABNF](https://tools.ietf.org/html/rfc5234) syntax + +```abnf + expression = ( "$url" / "$method" / "$statusCode" / "$request." source / "$response." source ) + source = ( header-reference / query-reference / path-reference / body-reference ) + header-reference = "header." token + query-reference = "query." name + path-reference = "path." name + body-reference = "body" ["#" json-pointer ] + json-pointer = *( "/" reference-token ) + reference-token = *( unescaped / escaped ) + unescaped = %x00-2E / %x30-7D / %x7F-10FFFF + ; %x2F ('/') and %x7E ('~') are excluded from 'unescaped' + escaped = "~" ( "0" / "1" ) + ; representing '~' and '/', respectively + name = *( CHAR ) + token = 1*tchar + tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / + "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA +``` + +Here, `json-pointer` is taken from [RFC 6901](https://tools.ietf.org/html/rfc6901), `char` from [RFC 7159](https://tools.ietf.org/html/rfc7159#section-7) and `token` from [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2.6). + +The `name` identifier is case-sensitive, whereas `token` is not. + +The table below provides examples of runtime expressions and examples of their use in a value: + +##### Examples + +Source Location | example expression | notes +---|:---|:---| +HTTP Method | `$method` | The allowable values for the `$method` will be those for the HTTP operation. +Requested media type | `$request.header.accept` | +Request parameter | `$request.path.id` | Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated. This includes request headers. +Request body property | `$request.body#/user/uuid` | In operations which accept payloads, references may be made to portions of the `requestBody` or the entire body. +Request URL | `$url` | +Response value | `$response.body#/status` | In operations which return payloads, references may be made to portions of the response body or the entire body. +Response header | `$response.header.Server` | Single header values only are available + +Runtime expressions preserve the type of the referenced value. +Expressions can be embedded into string values by surrounding the expression with `{}` curly braces. + +#### Header Object + +The Header Object follows the structure of the [Parameter Object](#parameterObject) with the following changes: + +1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. +1. `in` MUST NOT be specified, it is implicitly in `header`. +1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, [`style`](#parameterStyle)). + +##### Header Object Example + +A simple header of type `integer`: + +```json +{ + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } +} +``` + +```yaml +description: The number of allowed requests in the current period +schema: + type: integer +``` + +#### Tag Object + +Adds metadata to a single tag that is used by the [Operation Object](#operationObject). +It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The name of the tag. +description | `string` | A short description for the tag. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this tag. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Tag Object Example + +```json +{ + "name": "pet", + "description": "Pets operations" +} +``` + +```yaml +name: pet +description: Pets operations +``` + + +#### Reference Object + +A simple object to allow referencing other components in the specification, internally and externally. + +The Reference Object is defined by [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) and follows the same structure, behavior and rules. + +For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +$ref | `string` | **REQUIRED**. The reference string. + +This object cannot be extended with additional properties and any properties added SHALL be ignored. + +##### Reference Object Example + +```json +{ + "$ref": "#/components/schemas/Pet" +} +``` + +```yaml +$ref: '#/components/schemas/Pet' +``` + +##### Relative Schema Document Example +```json +{ + "$ref": "Pet.json" +} +``` + +```yaml +$ref: Pet.yaml +``` + +##### Relative Documents With Embedded Schema Example +```json +{ + "$ref": "definitions.json#/Pet" +} +``` + +```yaml +$ref: definitions.yaml#/Pet +``` + +#### Schema Object + +The Schema Object allows the definition of input and output data types. +These types can be objects, but also primitives and arrays. +This object is an extended subset of the [JSON Schema Specification Wright Draft 00](https://json-schema.org/). + +For more information about the properties, see [JSON Schema Core](https://tools.ietf.org/html/draft-wright-json-schema-00) and [JSON Schema Validation](https://tools.ietf.org/html/draft-wright-json-schema-validation-00). +Unless stated otherwise, the property definitions follow the JSON Schema. + +##### Properties + +The following properties are taken directly from the JSON Schema definition and follow the same specifications: + +- title +- multipleOf +- maximum +- exclusiveMaximum +- minimum +- exclusiveMinimum +- maxLength +- minLength +- pattern (This string SHOULD be a valid regular expression, according to the [Ecma-262 Edition 5.1 regular expression](https://www.ecma-international.org/ecma-262/5.1/#sec-15.10.1) dialect) +- maxItems +- minItems +- uniqueItems +- maxProperties +- minProperties +- required +- enum + +The following properties are taken from the JSON Schema definition but their definitions were adjusted to the OpenAPI Specification. +- type - Value MUST be a string. Multiple types via an array are not supported. +- allOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. +- oneOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. +- anyOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. +- not - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. +- items - Value MUST be an object and not an array. Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. `items` MUST be present if the `type` is `array`. +- properties - Property definitions MUST be a [Schema Object](#schemaObject) and not a standard JSON Schema (inline or referenced). +- additionalProperties - Value can be boolean or object. Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. Consistent with JSON Schema, `additionalProperties` defaults to `true`. +- description - [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +- format - See [Data Type Formats](#dataTypeFormat) for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats. +- default - The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level. For example, if `type` is `string`, then `default` can be `"foo"` but cannot be `1`. + +Alternatively, any time a Schema Object can be used, a [Reference Object](#referenceObject) can be used in its place. This allows referencing definitions instead of defining them inline. + +Additional properties defined by the JSON Schema specification that are not mentioned here are strictly unsupported. + +Other than the JSON Schema subset fields, the following fields MAY be used for further schema documentation: + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +nullable | `boolean` | A `true` value adds `"null"` to the allowed type specified by the `type` keyword, only if `type` is explicitly defined within the same Schema Object. Other Schema Object constraints retain their defined behavior, and therefore may disallow the use of `null` as a value. A `false` value leaves the specified or default `type` unmodified. The default value is `false`. +discriminator | [Discriminator Object](#discriminatorObject) | Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See [Composition and Inheritance](#schemaComposition) for more details. +readOnly | `boolean` | Relevant only for Schema `"properties"` definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as `readOnly` being `true` and is in the `required` list, the `required` will take effect on the response only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`. +writeOnly | `boolean` | Relevant only for Schema `"properties"` definitions. Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as `writeOnly` being `true` and is in the `required` list, the `required` will take effect on the request only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`. +xml | [XML Object](#xmlObject) | This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this schema. +example | Any | A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. + deprecated | `boolean` | Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is `false`. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +###### Composition and Inheritance (Polymorphism) + +The OpenAPI Specification allows combining and extending model definitions using the `allOf` property of JSON Schema, in effect offering model composition. +`allOf` takes an array of object definitions that are validated *independently* but together compose a single object. + +While composition offers model extensibility, it does not imply a hierarchy between the models. +To support polymorphism, the OpenAPI Specification adds the `discriminator` field. +When used, the `discriminator` will be the name of the property that decides which schema definition validates the structure of the model. +As such, the `discriminator` field MUST be a required field. +There are two ways to define the value of a discriminator for an inheriting instance. +- Use the schema name. +- Override the schema name by overriding the property with a new value. If a new value exists, this takes precedence over the schema name. +As such, inline schema definitions, which do not have a given id, *cannot* be used in polymorphism. + +###### XML Modeling + +The [xml](#schemaXml) property allows extra definitions when translating the JSON definition to XML. +The [XML Object](#xmlObject) contains additional information about the available options. + +##### Schema Object Examples + +###### Primitive Sample + +```json +{ + "type": "string", + "format": "email" +} +``` + +```yaml +type: string +format: email +``` + +###### Simple Model + +```json +{ + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "address": { + "$ref": "#/components/schemas/Address" + }, + "age": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } +} +``` + +```yaml +type: object +required: +- name +properties: + name: + type: string + address: + $ref: '#/components/schemas/Address' + age: + type: integer + format: int32 + minimum: 0 +``` + +###### Model with Map/Dictionary Properties + +For a simple string to string mapping: + +```json +{ + "type": "object", + "additionalProperties": { + "type": "string" + } +} +``` + +```yaml +type: object +additionalProperties: + type: string +``` + +For a string to model mapping: + +```json +{ + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ComplexModel" + } +} +``` + +```yaml +type: object +additionalProperties: + $ref: '#/components/schemas/ComplexModel' +``` + +###### Model with Example + +```json +{ + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name" + ], + "example": { + "name": "Puma", + "id": 1 + } +} +``` + +```yaml +type: object +properties: + id: + type: integer + format: int64 + name: + type: string +required: +- name +example: + name: Puma + id: 1 +``` + +###### Models with Composition + +```json +{ + "components": { + "schemas": { + "ErrorModel": { + "type": "object", + "required": [ + "message", + "code" + ], + "properties": { + "message": { + "type": "string" + }, + "code": { + "type": "integer", + "minimum": 100, + "maximum": 600 + } + } + }, + "ExtendedErrorModel": { + "allOf": [ + { + "$ref": "#/components/schemas/ErrorModel" + }, + { + "type": "object", + "required": [ + "rootCause" + ], + "properties": { + "rootCause": { + "type": "string" + } + } + } + ] + } + } + } +} +``` + +```yaml +components: + schemas: + ErrorModel: + type: object + required: + - message + - code + properties: + message: + type: string + code: + type: integer + minimum: 100 + maximum: 600 + ExtendedErrorModel: + allOf: + - $ref: '#/components/schemas/ErrorModel' + - type: object + required: + - rootCause + properties: + rootCause: + type: string +``` + +###### Models with Polymorphism Support + +```json +{ + "components": { + "schemas": { + "Pet": { + "type": "object", + "discriminator": { + "propertyName": "petType" + }, + "properties": { + "name": { + "type": "string" + }, + "petType": { + "type": "string" + } + }, + "required": [ + "name", + "petType" + ] + }, + "Cat": { + "description": "A representation of a cat. Note that `Cat` will be used as the discriminator value.", + "allOf": [ + { + "$ref": "#/components/schemas/Pet" + }, + { + "type": "object", + "properties": { + "huntingSkill": { + "type": "string", + "description": "The measured skill for hunting", + "default": "lazy", + "enum": [ + "clueless", + "lazy", + "adventurous", + "aggressive" + ] + } + }, + "required": [ + "huntingSkill" + ] + } + ] + }, + "Dog": { + "description": "A representation of a dog. Note that `Dog` will be used as the discriminator value.", + "allOf": [ + { + "$ref": "#/components/schemas/Pet" + }, + { + "type": "object", + "properties": { + "packSize": { + "type": "integer", + "format": "int32", + "description": "the size of the pack the dog is from", + "default": 0, + "minimum": 0 + } + }, + "required": [ + "packSize" + ] + } + ] + } + } + } +} +``` + +```yaml +components: + schemas: + Pet: + type: object + discriminator: + propertyName: petType + properties: + name: + type: string + petType: + type: string + required: + - name + - petType + Cat: ## "Cat" will be used as the discriminator value + description: A representation of a cat + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + properties: + huntingSkill: + type: string + description: The measured skill for hunting + enum: + - clueless + - lazy + - adventurous + - aggressive + required: + - huntingSkill + Dog: ## "Dog" will be used as the discriminator value + description: A representation of a dog + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + properties: + packSize: + type: integer + format: int32 + description: the size of the pack the dog is from + default: 0 + minimum: 0 + required: + - packSize +``` + +#### Discriminator Object + +When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it. + +When using the discriminator, _inline_ schemas will not be considered. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +propertyName | `string` | **REQUIRED**. The name of the property in the payload that will hold the discriminator value. + mapping | Map[`string`, `string`] | An object to hold mappings between payload values and schema names or references. + +The discriminator object is legal only when using one of the composite keywords `oneOf`, `anyOf`, `allOf`. + +In OAS 3.0, a response payload MAY be described to be exactly one of any number of types: + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' +``` + +which means the payload _MUST_, by validation, match exactly one of the schemas described by `Cat`, `Dog`, or `Lizard`. In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use: + + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' + discriminator: + propertyName: petType +``` + +The expectation now is that a property with name `petType` _MUST_ be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload: + +```json +{ + "id": 12345, + "petType": "Cat" +} +``` + +Will indicate that the `Cat` schema be used in conjunction with this payload. + +In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used: + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' + - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json' + discriminator: + propertyName: petType + mapping: + dog: '#/components/schemas/Dog' + monster: 'https://gigantic-server.com/schemas/Monster/schema.json' +``` + +Here the discriminator _value_ of `dog` will map to the schema `#/components/schemas/Dog`, rather than the default (implicit) value of `Dog`. If the discriminator _value_ does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison. + +When used in conjunction with the `anyOf` construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload. + +In both the `oneOf` and `anyOf` use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an `allOf` construct may be used as an alternate schema. + +For example: + +```yaml +components: + schemas: + Pet: + type: object + required: + - petType + properties: + petType: + type: string + discriminator: + propertyName: petType + mapping: + dog: Dog + Cat: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Cat` + properties: + name: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Dog` + properties: + bark: + type: string + Lizard: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Lizard` + properties: + lovesRocks: + type: boolean +``` + +a payload like this: + +```json +{ + "petType": "Cat", + "name": "misty" +} +``` + +will indicate that the `Cat` schema be used. Likewise this schema: + +```json +{ + "petType": "dog", + "bark": "soft" +} +``` + +will map to `Dog` because of the definition in the `mappings` element. + + +#### XML Object + +A metadata object that allows for more fine-tuned XML model definitions. + +When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. +See examples for expected behavior. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. +namespace | `string` | The URI of the namespace definition. Value MUST be in the form of an absolute URI. +prefix | `string` | The prefix to be used for the [name](#xmlName). +attribute | `boolean` | Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. +wrapped | `boolean` | MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### XML Object Examples + +The examples of the XML object definitions are included inside a property definition of a [Schema Object](#schemaObject) with a sample of the XML representation of it. + +###### No XML Element + +Basic string property: + +```json +{ + "animals": { + "type": "string" + } +} +``` + +```yaml +animals: + type: string +``` + +```xml +... +``` + +Basic string array property ([`wrapped`](#xmlWrapped) is `false` by default): + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string +``` + +```xml +... +... +... +``` + +###### XML Name Replacement + +```json +{ + "animals": { + "type": "string", + "xml": { + "name": "animal" + } + } +} +``` + +```yaml +animals: + type: string + xml: + name: animal +``` + +```xml +... +``` + + +###### XML Attribute, Prefix and Namespace + +In this example, a full model definition is shown. + +```json +{ + "Person": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32", + "xml": { + "attribute": true + } + }, + "name": { + "type": "string", + "xml": { + "namespace": "http://example.com/schema/sample", + "prefix": "sample" + } + } + } + } +} +``` + +```yaml +Person: + type: object + properties: + id: + type: integer + format: int32 + xml: + attribute: true + name: + type: string + xml: + namespace: http://example.com/schema/sample + prefix: sample +``` + +```xml + + example + +``` + +###### XML Arrays + +Changing the element names: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal +``` + +```xml +value +value +``` + +The external `name` property has no effect on the XML: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens +``` + +```xml +value +value +``` + +Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + wrapped: true +``` + +```xml + + value + value + +``` + +To overcome the naming problem in the example above, the following definition can be used: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + wrapped: true +``` + +```xml + + value + value + +``` + +Affecting both internal and external names: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens + wrapped: true +``` + +```xml + + value + value + +``` + +If we change the external element but not the internal ones: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: aliens + wrapped: true +``` + +```xml + + value + value + +``` + +#### Security Scheme Object + +Defines a security scheme that can be used by the operations. +Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749](https://tools.ietf.org/html/rfc6749), and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06). + +##### Fixed Fields +Field Name | Type | Applies To | Description +---|:---:|---|--- +type | `string` | Any | **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"oauth2"`, `"openIdConnect"`. +description | `string` | Any | A short description for security scheme. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +name | `string` | `apiKey` | **REQUIRED**. The name of the header, query or cookie parameter to be used. +in | `string` | `apiKey` | **REQUIRED**. The location of the API key. Valid values are `"query"`, `"header"` or `"cookie"`. +scheme | `string` | `http` | **REQUIRED**. The name of the HTTP Authorization scheme to be used in the [Authorization header as defined in RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1). The values used SHOULD be registered in the [IANA Authentication Scheme registry](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml). +bearerFormat | `string` | `http` (`"bearer"`) | A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. +flows | [OAuth Flows Object](#oauthFlowsObject) | `oauth2` | **REQUIRED**. An object containing configuration information for the flow types supported. +openIdConnectUrl | `string` | `openIdConnect` | **REQUIRED**. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Security Scheme Object Example + +###### Basic Authentication Sample + +```json +{ + "type": "http", + "scheme": "basic" +} +``` + +```yaml +type: http +scheme: basic +``` + +###### API Key Sample + +```json +{ + "type": "apiKey", + "name": "api_key", + "in": "header" +} +``` + +```yaml +type: apiKey +name: api_key +in: header +``` + +###### JWT Bearer Sample + +```json +{ + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT", +} +``` + +```yaml +type: http +scheme: bearer +bearerFormat: JWT +``` + +###### Implicit OAuth2 Sample + +```json +{ + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } +} +``` + +```yaml +type: oauth2 +flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### OAuth Flows Object + +Allows configuration of the supported OAuth Flows. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +implicit| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Implicit flow +password| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Resource Owner Password flow +clientCredentials| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0. +authorizationCode| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### OAuth Flow Object + +Configuration details for a supported OAuth Flow + +##### Fixed Fields +Field Name | Type | Applies To | Description +---|:---:|---|--- +authorizationUrl | `string` | `oauth2` (`"implicit"`, `"authorizationCode"`) | **REQUIRED**. The authorization URL to be used for this flow. This MUST be in the form of a URL. +tokenUrl | `string` | `oauth2` (`"password"`, `"clientCredentials"`, `"authorizationCode"`) | **REQUIRED**. The token URL to be used for this flow. This MUST be in the form of a URL. +refreshUrl | `string` | `oauth2` | The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. +scopes | Map[`string`, `string`] | `oauth2` | **REQUIRED**. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### OAuth Flow Object Examples + +```JSON +{ + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "authorizationCode": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "tokenUrl": "https://example.com/api/oauth/token", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } +} +``` + +```yaml +type: oauth2 +flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + authorizationCode: + authorizationUrl: https://example.com/api/oauth/dialog + tokenUrl: https://example.com/api/oauth/token + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### Security Requirement Object + +Lists the required security schemes to execute this operation. +The name used for each property MUST correspond to a security scheme declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). + +Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. +This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. + +When a list of Security Requirement Objects is defined on the [OpenAPI Object](#oasObject) or [Operation Object](#operationObject), only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +{name} | [`string`] | Each name MUST correspond to a security scheme which is declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). If the security scheme is of type `"oauth2"` or `"openIdConnect"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MUST be empty. + +##### Security Requirement Object Examples + +###### Non-OAuth2 Security Requirement + +```json +{ + "api_key": [] +} +``` + +```yaml +api_key: [] +``` + +###### OAuth2 Security Requirement + +```json +{ + "petstore_auth": [ + "write:pets", + "read:pets" + ] +} +``` + +```yaml +petstore_auth: +- write:pets +- read:pets +``` + +###### Optional OAuth2 Security + +Optional OAuth2 security as would be defined in an OpenAPI Object or an Operation Object: + +```json +{ + "security": [ + {}, + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] +} +``` + +```yaml +security: + - {} + - petstore_auth: + - write:pets + - read:pets +``` + +### Specification Extensions + +While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points. + +The extensions properties are implemented as patterned fields that are always prefixed by `"x-"`. + +Field Pattern | Type | Description +---|:---:|--- +^x- | Any | Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. Can have any valid JSON format value. + +The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced). + +### Security Filtering + +Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation. + +The reasoning is to allow an additional layer of access control over the documentation. +While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization. + +Two examples of this: + +1. The [Paths Object](#pathsObject) MAY be empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They'd still have access to the [Info Object](#infoObject) which may contain additional information regarding authentication. +2. The [Path Item Object](#pathItemObject) MAY be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different from hiding the path itself from the [Paths Object](#pathsObject), because the user will be aware of its existence. This allows the documentation provider to finely control what the viewer can see. + +## Appendix A: Revision History + +Version | Date | Notes +--- | --- | --- +3.0.3 | 2020-02-20 | Patch release of the OpenAPI Specification 3.0.3 +3.0.2 | 2018-10-08 | Patch release of the OpenAPI Specification 3.0.2 +3.0.1 | 2017-12-06 | Patch release of the OpenAPI Specification 3.0.1 +3.0.0 | 2017-07-26 | Release of the OpenAPI Specification 3.0.0 +3.0.0-rc2 | 2017-06-16 | rc2 of the 3.0 specification +3.0.0-rc1 | 2017-04-27 | rc1 of the 3.0 specification +3.0.0-rc0 | 2017-02-28 | Implementer's Draft of the 3.0 specification +2.0 | 2015-12-31 | Donation of Swagger 2.0 to the OpenAPI Initiative +2.0 | 2014-09-08 | Release of Swagger 2.0 +1.2 | 2014-03-14 | Initial release of the formal document. +1.1 | 2012-08-22 | Release of Swagger 1.1 +1.0 | 2011-08-10 | First release of the Swagger Specification diff --git a/chaotic-openapi/chaotic_openapi/front/schema/3.1.0.md b/chaotic-openapi/chaotic_openapi/front/schema/3.1.0.md new file mode 100644 index 000000000000..39425bd6b95f --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/3.1.0.md @@ -0,0 +1,3468 @@ +# OpenAPI Specification + +#### Version 3.1.0 + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://tools.ietf.org/html/bcp14) [RFC2119](https://tools.ietf.org/html/rfc2119) [RFC8174](https://tools.ietf.org/html/rfc8174) when, and only when, they appear in all capitals, as shown here. + +This document is licensed under [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). + +## Introduction + +The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to HTTP APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. + +An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases. + +## Table of Contents + + +- [Definitions](#definitions) + - [OpenAPI Document](#oasDocument) + - [Path Templating](#pathTemplating) + - [Media Types](#mediaTypes) + - [HTTP Status Codes](#httpCodes) +- [Specification](#specification) + - [Versions](#versions) + - [Format](#format) + - [Document Structure](#documentStructure) + - [Data Types](#dataTypes) + - [Rich Text Formatting](#richText) + - [Relative References In URIs](#relativeReferencesURI) + - [Relative References In URLs](#relativeReferencesURL) + - [Schema](#schema) + - [OpenAPI Object](#oasObject) + - [Info Object](#infoObject) + - [Contact Object](#contactObject) + - [License Object](#licenseObject) + - [Server Object](#serverObject) + - [Server Variable Object](#serverVariableObject) + - [Components Object](#componentsObject) + - [Paths Object](#pathsObject) + - [Path Item Object](#pathItemObject) + - [Operation Object](#operationObject) + - [External Documentation Object](#externalDocumentationObject) + - [Parameter Object](#parameterObject) + - [Request Body Object](#requestBodyObject) + - [Media Type Object](#mediaTypeObject) + - [Encoding Object](#encodingObject) + - [Responses Object](#responsesObject) + - [Response Object](#responseObject) + - [Callback Object](#callbackObject) + - [Example Object](#exampleObject) + - [Link Object](#linkObject) + - [Header Object](#headerObject) + - [Tag Object](#tagObject) + - [Reference Object](#referenceObject) + - [Schema Object](#schemaObject) + - [Discriminator Object](#discriminatorObject) + - [XML Object](#xmlObject) + - [Security Scheme Object](#securitySchemeObject) + - [OAuth Flows Object](#oauthFlowsObject) + - [OAuth Flow Object](#oauthFlowObject) + - [Security Requirement Object](#securityRequirementObject) + - [Specification Extensions](#specificationExtensions) + - [Security Filtering](#securityFiltering) +- [Appendix A: Revision History](#revisionHistory) + + + + +## Definitions + +##### OpenAPI Document +A self-contained or composite resource which defines or describes an API or elements of an API. The OpenAPI document MUST contain at least one [paths](#pathsObject) field, a [components](#oasComponents) field or a [webhooks](#oasWebhooks) field. An OpenAPI document uses and conforms to the OpenAPI Specification. + +##### Path Templating +Path templating refers to the usage of template expressions, delimited by curly braces ({}), to mark a section of a URL path as replaceable using path parameters. + +Each template expression in the path MUST correspond to a path parameter that is included in the [Path Item](#path-item-object) itself and/or in each of the Path Item's [Operations](#operation-object). An exception is if the path item is empty, for example due to ACL constraints, matching path parameters are not required. + +The value for these path parameters MUST NOT contain any unescaped "generic syntax" characters described by [RFC3986](https://tools.ietf.org/html/rfc3986#section-3): forward slashes (`/`), question marks (`?`), or hashes (`#`). + +##### Media Types +Media type definitions are spread across several resources. +The media type definitions SHOULD be in compliance with [RFC6838](https://tools.ietf.org/html/rfc6838). + +Some examples of possible media type definitions: +``` + text/plain; charset=utf-8 + application/json + application/vnd.github+json + application/vnd.github.v3+json + application/vnd.github.v3.raw+json + application/vnd.github.v3.text+json + application/vnd.github.v3.html+json + application/vnd.github.v3.full+json + application/vnd.github.v3.diff + application/vnd.github.v3.patch +``` +##### HTTP Status Codes +The HTTP Status Codes are used to indicate the status of the executed operation. +The available status codes are defined by [RFC7231](https://tools.ietf.org/html/rfc7231#section-6) and registered status codes are listed in the [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml). + +## Specification + +### Versions + +The OpenAPI Specification is versioned using a `major`.`minor`.`patch` versioning scheme. The `major`.`minor` portion of the version string (for example `3.1`) SHALL designate the OAS feature set. *`.patch`* versions address errors in, or provide clarifications to, this document, not the feature set. Tooling which supports OAS 3.1 SHOULD be compatible with all OAS 3.1.\* versions. The patch version SHOULD NOT be considered by tooling, making no distinction between `3.1.0` and `3.1.1` for example. + +Occasionally, non-backwards compatible changes may be made in `minor` versions of the OAS where impact is believed to be low relative to the benefit provided. + +An OpenAPI document compatible with OAS 3.\*.\* contains a required [`openapi`](#oasVersion) field which designates the version of the OAS that it uses. + +### Format + +An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either in JSON or YAML format. + +For example, if a field has an array value, the JSON array representation will be used: + +```json +{ + "field": [ 1, 2, 3 ] +} +``` +All field names in the specification are **case sensitive**. +This includes all fields that are used as keys in a map, except where explicitly noted that keys are **case insensitive**. + +The schema exposes two types of fields: Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name. + +Patterned fields MUST have unique names within the containing object. + +In order to preserve the ability to round-trip between YAML and JSON formats, YAML version [1.2](https://yaml.org/spec/1.2/spec.html) is RECOMMENDED along with some additional constraints: + +- Tags MUST be limited to those allowed by the [JSON Schema ruleset](https://yaml.org/spec/1.2/spec.html#id2803231). +- Keys used in YAML maps MUST be limited to a scalar string, as defined by the [YAML Failsafe schema ruleset](https://yaml.org/spec/1.2/spec.html#id2802346). + +**Note:** While APIs may be defined by OpenAPI documents in either YAML or JSON format, the API request and response bodies and other content are not required to be JSON or YAML. + +### Document Structure + +An OpenAPI document MAY be made up of a single document or be divided into multiple, connected parts at the discretion of the author. In the latter case, [`Reference Objects`](#referenceObject) and [`Schema Object`](#schemaObject) `$ref` keywords are used. + +It is RECOMMENDED that the root OpenAPI document be named: `openapi.json` or `openapi.yaml`. + +### Data Types + +Data types in the OAS are based on the types supported by the [JSON Schema Specification Draft 2020-12](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-4.2.1). +Note that `integer` as a type is also supported and is defined as a JSON number without a fraction or exponent part. +Models are defined using the [Schema Object](#schemaObject), which is a superset of JSON Schema Specification Draft 2020-12. + +As defined by the [JSON Schema Validation vocabulary](https://tools.ietf.org/html/draft-bhutton-json-schema-validation-00#section-7.3), data types can have an optional modifier property: `format`. +OAS defines additional formats to provide fine detail for primitive data types. + +The formats defined by the OAS are: + +[`type`](#dataTypes) | [`format`](#dataTypeFormat) | Comments +------ | -------- | -------- +`integer` | `int32` | signed 32 bits +`integer` | `int64` | signed 64 bits (a.k.a long) +`number` | `float` | | +`number` | `double` | | +`string` | `password` | A hint to UIs to obscure input. + +### Rich Text Formatting +Throughout the specification `description` fields are noted as supporting CommonMark markdown formatting. +Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by [CommonMark 0.27](https://spec.commonmark.org/0.27/). Tooling MAY choose to ignore some CommonMark features to address security concerns. + +### Relative References in URIs + +Unless specified otherwise, all properties that are URIs MAY be relative references as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-4.2). + +Relative references, including those in [`Reference Objects`](#referenceObject), [`PathItem Object`](#pathItemObject) `$ref` fields, [`Link Object`](#linkObject) `operationRef` fields and [`Example Object`](#exampleObject) `externalValue` fields, are resolved using the referring document as the Base URI according to [RFC3986](https://tools.ietf.org/html/rfc3986#section-5.2). + +If a URI contains a fragment identifier, then the fragment should be resolved per the fragment resolution mechanism of the referenced document. If the representation of the referenced document is JSON or YAML, then the fragment identifier SHOULD be interpreted as a JSON-Pointer as per [RFC6901](https://tools.ietf.org/html/rfc6901). + +Relative references in [`Schema Objects`](#schemaObject), including any that appear as `$id` values, use the nearest parent `$id` as a Base URI, as described by [JSON Schema Specification Draft 2020-12](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-8.2). If no parent schema contains an `$id`, then the Base URI MUST be determined according to [RFC3986](https://tools.ietf.org/html/rfc3986#section-5.1). + +### Relative References in URLs + +Unless specified otherwise, all properties that are URLs MAY be relative references as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-4.2). +Unless specified otherwise, relative references are resolved using the URLs defined in the [`Server Object`](#serverObject) as a Base URL. Note that these themselves MAY be relative to the referring document. + +### Schema + +In the following description, if a field is not explicitly **REQUIRED** or described with a MUST or SHALL, it can be considered OPTIONAL. + +#### OpenAPI Object + +This is the root object of the [OpenAPI document](#oasDocument). + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +openapi | `string` | **REQUIRED**. This string MUST be the [version number](#versions) of the OpenAPI Specification that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI document. This is *not* related to the API [`info.version`](#infoVersion) string. +info | [Info Object](#infoObject) | **REQUIRED**. Provides metadata about the API. The metadata MAY be used by tooling as required. + jsonSchemaDialect | `string` | The default value for the `$schema` keyword within [Schema Objects](#schemaObject) contained within this OAS document. This MUST be in the form of a URI. +servers | [[Server Object](#serverObject)] | An array of Server Objects, which provide connectivity information to a target server. If the `servers` property is not provided, or is an empty array, the default value would be a [Server Object](#serverObject) with a [url](#serverUrl) value of `/`. +paths | [Paths Object](#pathsObject) | The available paths and operations for the API. +webhooks | Map[`string`, [Path Item Object](#pathItemObject) \| [Reference Object](#referenceObject)] ] | The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement. Closely related to the `callbacks` feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. An [example](../examples/v3.1/webhook-example.yaml) is available. +components | [Components Object](#componentsObject) | An element to hold various schemas for the document. +security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement (`{}`) can be included in the array. +tags | [[Tag Object](#tagObject)] | A list of tags used by the document with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](#operationObject) must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation. + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### Info Object + +The object provides metadata about the API. +The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +title | `string` | **REQUIRED**. The title of the API. +summary | `string` | A short summary of the API. +description | `string` | A description of the API. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +termsOfService | `string` | A URL to the Terms of Service for the API. This MUST be in the form of a URL. +contact | [Contact Object](#contactObject) | The contact information for the exposed API. +license | [License Object](#licenseObject) | The license information for the exposed API. +version | `string` | **REQUIRED**. The version of the OpenAPI document (which is distinct from the [OpenAPI Specification version](#oasVersion) or the API implementation version). + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Info Object Example + +```json +{ + "title": "Sample Pet Store App", + "summary": "A pet store manager.", + "description": "This is a sample server for a pet store.", + "termsOfService": "https://example.com/terms/", + "contact": { + "name": "API Support", + "url": "https://www.example.com/support", + "email": "support@example.com" + }, + "license": { + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.1" +} +``` + +```yaml +title: Sample Pet Store App +summary: A pet store manager. +description: This is a sample server for a pet store. +termsOfService: https://example.com/terms/ +contact: + name: API Support + url: https://www.example.com/support + email: support@example.com +license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +version: 1.0.1 +``` + +#### Contact Object + +Contact information for the exposed API. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +name | `string` | The identifying name of the contact person/organization. +url | `string` | The URL pointing to the contact information. This MUST be in the form of a URL. +email | `string` | The email address of the contact person/organization. This MUST be in the form of an email address. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Contact Object Example + +```json +{ + "name": "API Support", + "url": "https://www.example.com/support", + "email": "support@example.com" +} +``` + +```yaml +name: API Support +url: https://www.example.com/support +email: support@example.com +``` + +#### License Object + +License information for the exposed API. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The license name used for the API. +identifier | `string` | An [SPDX](https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60) license expression for the API. The `identifier` field is mutually exclusive of the `url` field. +url | `string` | A URL to the license used for the API. This MUST be in the form of a URL. The `url` field is mutually exclusive of the `identifier` field. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### License Object Example + +```json +{ + "name": "Apache 2.0", + "identifier": "Apache-2.0" +} +``` + +```yaml +name: Apache 2.0 +identifier: Apache-2.0 +``` + +#### Server Object + +An object representing a Server. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +url | `string` | **REQUIRED**. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{`brackets`}`. +description | `string` | An optional string describing the host designated by the URL. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +variables | Map[`string`, [Server Variable Object](#serverVariableObject)] | A map between a variable name and its value. The value is used for substitution in the server's URL template. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Server Object Example + +A single server would be described as: + +```json +{ + "url": "https://development.gigantic-server.com/v1", + "description": "Development server" +} +``` + +```yaml +url: https://development.gigantic-server.com/v1 +description: Development server +``` + +The following shows how multiple servers can be described, for example, at the OpenAPI Object's [`servers`](#oasServers): + +```json +{ + "servers": [ + { + "url": "https://development.gigantic-server.com/v1", + "description": "Development server" + }, + { + "url": "https://staging.gigantic-server.com/v1", + "description": "Staging server" + }, + { + "url": "https://api.gigantic-server.com/v1", + "description": "Production server" + } + ] +} +``` + +```yaml +servers: +- url: https://development.gigantic-server.com/v1 + description: Development server +- url: https://staging.gigantic-server.com/v1 + description: Staging server +- url: https://api.gigantic-server.com/v1 + description: Production server +``` + +The following shows how variables can be used for a server configuration: + +```json +{ + "servers": [ + { + "url": "https://{username}.gigantic-server.com:{port}/{basePath}", + "description": "The production API server", + "variables": { + "username": { + "default": "demo", + "description": "this value is assigned by the service provider, in this example `gigantic-server.com`" + }, + "port": { + "enum": [ + "8443", + "443" + ], + "default": "8443" + }, + "basePath": { + "default": "v2" + } + } + } + ] +} +``` + +```yaml +servers: +- url: https://{username}.gigantic-server.com:{port}/{basePath} + description: The production API server + variables: + username: + # note! no enum here means it is an open value + default: demo + description: this value is assigned by the service provider, in this example `gigantic-server.com` + port: + enum: + - '8443' + - '443' + default: '8443' + basePath: + # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2` + default: v2 +``` + + +#### Server Variable Object + +An object representing a Server Variable for server URL template substitution. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +enum | [`string`] | An enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty. +default | `string` | **REQUIRED**. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. Note this behavior is different than the [Schema Object's](#schemaObject) treatment of default values, because in those cases parameter values are optional. If the [`enum`](#serverVariableEnum) is defined, the value MUST exist in the enum's values. +description | `string` | An optional description for the server variable. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### Components Object + +Holds a set of reusable objects for different aspects of the OAS. +All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. + + +##### Fixed Fields + +Field Name | Type | Description +---|:---|--- + schemas | Map[`string`, [Schema Object](#schemaObject)] | An object to hold reusable [Schema Objects](#schemaObject). + responses | Map[`string`, [Response Object](#responseObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Response Objects](#responseObject). + parameters | Map[`string`, [Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Parameter Objects](#parameterObject). + examples | Map[`string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Example Objects](#exampleObject). + requestBodies | Map[`string`, [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Request Body Objects](#requestBodyObject). + headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Header Objects](#headerObject). + securitySchemes| Map[`string`, [Security Scheme Object](#securitySchemeObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Security Scheme Objects](#securitySchemeObject). + links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Link Objects](#linkObject). + callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Callback Objects](#callbackObject). + pathItems | Map[`string`, [Path Item Object](#pathItemObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Path Item Object](#pathItemObject). + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`. + +Field Name Examples: + +``` +User +User_1 +User_Name +user-name +my.org.User +``` + +##### Components Object Example + +```json +"components": { + "schemas": { + "GeneralError": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + } + }, + "parameters": { + "skipParam": { + "name": "skip", + "in": "query", + "description": "number of items to skip", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + } + }, + "limitParam": { + "name": "limit", + "in": "query", + "description": "max records to return", + "required": true, + "schema" : { + "type": "integer", + "format": "int32" + } + } + }, + "responses": { + "NotFound": { + "description": "Entity not found." + }, + "IllegalInput": { + "description": "Illegal input for operation." + }, + "GeneralError": { + "description": "General Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GeneralError" + } + } + } + } + }, + "securitySchemes": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.org/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } + } + } +} +``` + +```yaml +components: + schemas: + GeneralError: + type: object + properties: + code: + type: integer + format: int32 + message: + type: string + Category: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + parameters: + skipParam: + name: skip + in: query + description: number of items to skip + required: true + schema: + type: integer + format: int32 + limitParam: + name: limit + in: query + description: max records to return + required: true + schema: + type: integer + format: int32 + responses: + NotFound: + description: Entity not found. + IllegalInput: + description: Illegal input for operation. + GeneralError: + description: General Error + content: + application/json: + schema: + $ref: '#/components/schemas/GeneralError' + securitySchemes: + api_key: + type: apiKey + name: api_key + in: header + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: https://example.org/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### Paths Object + +Holds the relative paths to the individual endpoints and their operations. +The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. The Paths MAY be empty, due to [Access Control List (ACL) constraints](#securityFiltering). + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +/{path} | [Path Item Object](#pathItemObject) | A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is **appended** (no relative URL resolution) to the expanded URL from the [`Server Object`](#serverObject)'s `url` field in order to construct the full URL. [Path templating](#pathTemplating) is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Path Templating Matching + +Assuming the following paths, the concrete definition, `/pets/mine`, will be matched first if used: + +``` + /pets/{petId} + /pets/mine +``` + +The following paths are considered identical and invalid: + +``` + /pets/{petId} + /pets/{name} +``` + +The following may lead to ambiguous resolution: + +``` + /{entity}/me + /books/{id} +``` + +##### Paths Object Example + +```json +{ + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "responses": { + "200": { + "description": "A list of pets.", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/pet" + } + } + } + } + } + } + } + } +} +``` + +```yaml +/pets: + get: + description: Returns all pets from the system that the user has access to + responses: + '200': + description: A list of pets. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/pet' +``` + +#### Path Item Object + +Describes the operations available on a single path. +A Path Item MAY be empty, due to [ACL constraints](#securityFiltering). +The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +$ref | `string` | Allows for a referenced definition of this path item. The referenced structure MUST be in the form of a [Path Item Object](#pathItemObject). In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving [Relative References](#relativeReferencesURI). +summary| `string` | An optional, string summary, intended to apply to all operations in this path. +description | `string` | An optional, string description, intended to apply to all operations in this path. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +get | [Operation Object](#operationObject) | A definition of a GET operation on this path. +put | [Operation Object](#operationObject) | A definition of a PUT operation on this path. +post | [Operation Object](#operationObject) | A definition of a POST operation on this path. +delete | [Operation Object](#operationObject) | A definition of a DELETE operation on this path. +options | [Operation Object](#operationObject) | A definition of a OPTIONS operation on this path. +head | [Operation Object](#operationObject) | A definition of a HEAD operation on this path. +patch | [Operation Object](#operationObject) | A definition of a PATCH operation on this path. +trace | [Operation Object](#operationObject) | A definition of a TRACE operation on this path. +servers | [[Server Object](#serverObject)] | An alternative `server` array to service all operations in this path. +parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Path Item Object Example + +```json +{ + "get": { + "description": "Returns pets based on ID", + "summary": "Find pets by ID", + "operationId": "getPetsById", + "responses": { + "200": { + "description": "pet response", + "content": { + "*/*": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Pet" + } + } + } + } + }, + "default": { + "description": "error payload", + "content": { + "text/html": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to use", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "simple" + } + ] +} +``` + +```yaml +get: + description: Returns pets based on ID + summary: Find pets by ID + operationId: getPetsById + responses: + '200': + description: pet response + content: + '*/*' : + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + default: + description: error payload + content: + 'text/html': + schema: + $ref: '#/components/schemas/ErrorModel' +parameters: +- name: id + in: path + description: ID of pet to use + required: true + schema: + type: array + items: + type: string + style: simple +``` + +#### Operation Object + +Describes a single API operation on a path. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +tags | [`string`] | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. +summary | `string` | A short summary of what the operation does. +description | `string` | A verbose explanation of the operation behavior. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this operation. +operationId | `string` | Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is **case-sensitive**. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. +parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for this operation. If a parameter is already defined at the [Path Item](#pathItemParameters), the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). +requestBody | [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject) | The request body applicable for this operation. The `requestBody` is fully supported in HTTP methods where the HTTP 1.1 specification [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague (such as [GET](https://tools.ietf.org/html/rfc7231#section-4.3.1), [HEAD](https://tools.ietf.org/html/rfc7231#section-4.3.2) and [DELETE](https://tools.ietf.org/html/rfc7231#section-4.3.5)), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible. +responses | [Responses Object](#responsesObject) | The list of possible responses as they are returned from executing this operation. +callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a [Callback Object](#callbackObject) that describes a request that may be initiated by the API provider and the expected responses. +deprecated | `boolean` | Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`. +security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level [`security`](#oasSecurity). To remove a top-level security declaration, an empty array can be used. +servers | [[Server Object](#serverObject)] | An alternative `server` array to service this operation. If an alternative `server` object is specified at the Path Item Object or Root level, it will be overridden by this value. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Operation Object Example + +```json +{ + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "operationId": "updatePetWithForm", + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "Updated name of the pet", + "type": "string" + }, + "status": { + "description": "Updated status of the pet", + "type": "string" + } + }, + "required": ["status"] + } + } + } + }, + "responses": { + "200": { + "description": "Pet updated.", + "content": { + "application/json": {}, + "application/xml": {} + } + }, + "405": { + "description": "Method Not Allowed", + "content": { + "application/json": {}, + "application/xml": {} + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] +} +``` + +```yaml +tags: +- pet +summary: Updates a pet in the store with form data +operationId: updatePetWithForm +parameters: +- name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: string +requestBody: + content: + 'application/x-www-form-urlencoded': + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + required: + - status +responses: + '200': + description: Pet updated. + content: + 'application/json': {} + 'application/xml': {} + '405': + description: Method Not Allowed + content: + 'application/json': {} + 'application/xml': {} +security: +- petstore_auth: + - write:pets + - read:pets +``` + + +#### External Documentation Object + +Allows referencing an external resource for extended documentation. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +description | `string` | A description of the target documentation. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +url | `string` | **REQUIRED**. The URL for the target documentation. This MUST be in the form of a URL. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### External Documentation Object Example + +```json +{ + "description": "Find more info here", + "url": "https://example.com" +} +``` + +```yaml +description: Find more info here +url: https://example.com +``` + +#### Parameter Object + +Describes a single operation parameter. + +A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). + +##### Parameter Locations +There are four possible parameter locations specified by the `in` field: +* path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. +* query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. +* header - Custom headers that are expected as part of the request. Note that [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. +* cookie - Used to pass a specific cookie value to the API. + + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The name of the parameter. Parameter names are *case sensitive*.
  • If [`in`](#parameterIn) is `"path"`, the `name` field MUST correspond to a template expression occurring within the [path](#pathsPath) field in the [Paths Object](#pathsObject). See [Path Templating](#pathTemplating) for further information.
  • If [`in`](#parameterIn) is `"header"` and the `name` field is `"Accept"`, `"Content-Type"` or `"Authorization"`, the parameter definition SHALL be ignored.
  • For all other cases, the `name` corresponds to the parameter name used by the [`in`](#parameterIn) property.
+in | `string` | **REQUIRED**. The location of the parameter. Possible values are `"query"`, `"header"`, `"path"` or `"cookie"`. +description | `string` | A brief description of the parameter. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +required | `boolean` | Determines whether this parameter is mandatory. If the [parameter location](#parameterIn) is `"path"`, this property is **REQUIRED** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. + deprecated | `boolean` | Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`. + allowEmptyValue | `boolean` | Sets the ability to pass empty-valued parameters. This is valid only for `query` parameters and allows sending a parameter with an empty value. Default value is `false`. If [`style`](#parameterStyle) is used, and if behavior is `n/a` (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision. + +The rules for serialization of the parameter are specified in one of two ways. +For simpler scenarios, a [`schema`](#parameterSchema) and [`style`](#parameterStyle) can describe the structure and syntax of the parameter. + +Field Name | Type | Description +---|:---:|--- +style | `string` | Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `query` - `form`; for `path` - `simple`; for `header` - `simple`; for `cookie` - `form`. +explode | `boolean` | When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this property has no effect. When [`style`](#parameterStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. +allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. This property only applies to parameters with an `in` value of `query`. The default value is `false`. +schema | [Schema Object](#schemaObject) | The schema defining the type used for the parameter. +example | Any | Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` that contains an example, the `example` value SHALL _override_ the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary. +examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` that contains an example, the `examples` value SHALL _override_ the example provided by the schema. + +For more complex scenarios, the [`content`](#parameterContent) property can define the media type and schema of the parameter. +A parameter MUST contain either a `schema` property, or a `content` property, but not both. +When `example` or `examples` are provided in conjunction with the `schema` object, the example MUST follow the prescribed serialization strategy for the parameter. + + +Field Name | Type | Description +---|:---:|--- +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. + +##### Style Values + +In order to support common ways of serializing simple parameters, a set of `style` values are defined. + +`style` | [`type`](#dataTypes) | `in` | Comments +----------- | ------ | -------- | -------- +matrix | `primitive`, `array`, `object` | `path` | Path-style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7) +label | `primitive`, `array`, `object` | `path` | Label style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.5) +form | `primitive`, `array`, `object` | `query`, `cookie` | Form style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.8). This option replaces `collectionFormat` with a `csv` (when `explode` is false) or `multi` (when `explode` is true) value from OpenAPI 2.0. +simple | `array` | `path`, `header` | Simple style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.2). This option replaces `collectionFormat` with a `csv` value from OpenAPI 2.0. +spaceDelimited | `array`, `object` | `query` | Space separated array or object values. This option replaces `collectionFormat` equal to `ssv` from OpenAPI 2.0. +pipeDelimited | `array`, `object` | `query` | Pipe separated array or object values. This option replaces `collectionFormat` equal to `pipes` from OpenAPI 2.0. +deepObject | `object` | `query` | Provides a simple way of rendering nested objects using form parameters. + + +##### Style Examples + +Assume a parameter named `color` has one of the following values: + +``` + string -> "blue" + array -> ["blue","black","brown"] + object -> { "R": 100, "G": 200, "B": 150 } +``` +The following table shows examples of rendering differences for each value. + +[`style`](#styleValues) | `explode` | `empty` | `string` | `array` | `object` +----------- | ------ | -------- | -------- | -------- | ------- +matrix | false | ;color | ;color=blue | ;color=blue,black,brown | ;color=R,100,G,200,B,150 +matrix | true | ;color | ;color=blue | ;color=blue;color=black;color=brown | ;R=100;G=200;B=150 +label | false | . | .blue | .blue.black.brown | .R.100.G.200.B.150 +label | true | . | .blue | .blue.black.brown | .R=100.G=200.B=150 +form | false | color= | color=blue | color=blue,black,brown | color=R,100,G,200,B,150 +form | true | color= | color=blue | color=blue&color=black&color=brown | R=100&G=200&B=150 +simple | false | n/a | blue | blue,black,brown | R,100,G,200,B,150 +simple | true | n/a | blue | blue,black,brown | R=100,G=200,B=150 +spaceDelimited | false | n/a | n/a | blue%20black%20brown | R%20100%20G%20200%20B%20150 +pipeDelimited | false | n/a | n/a | blue\|black\|brown | R\|100\|G\|200\|B\|150 +deepObject | true | n/a | n/a | n/a | color[R]=100&color[G]=200&color[B]=150 + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Parameter Object Examples + +A header parameter with an array of 64 bit integer numbers: + +```json +{ + "name": "token", + "in": "header", + "description": "token to be passed as a header", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int64" + } + }, + "style": "simple" +} +``` + +```yaml +name: token +in: header +description: token to be passed as a header +required: true +schema: + type: array + items: + type: integer + format: int64 +style: simple +``` + +A path parameter of a string value: +```json +{ + "name": "username", + "in": "path", + "description": "username to fetch", + "required": true, + "schema": { + "type": "string" + } +} +``` + +```yaml +name: username +in: path +description: username to fetch +required: true +schema: + type: string +``` + +An optional query parameter of a string value, allowing multiple values by repeating the query parameter: +```json +{ + "name": "id", + "in": "query", + "description": "ID of the object to fetch", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "form", + "explode": true +} +``` + +```yaml +name: id +in: query +description: ID of the object to fetch +required: false +schema: + type: array + items: + type: string +style: form +explode: true +``` + +A free-form query parameter, allowing undefined parameters of a specific type: +```json +{ + "in": "query", + "name": "freeForm", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer" + }, + }, + "style": "form" +} +``` + +```yaml +in: query +name: freeForm +schema: + type: object + additionalProperties: + type: integer +style: form +``` + +A complex parameter using `content` to define serialization: + +```json +{ + "in": "query", + "name": "coordinates", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "lat", + "long" + ], + "properties": { + "lat": { + "type": "number" + }, + "long": { + "type": "number" + } + } + } + } + } +} +``` + +```yaml +in: query +name: coordinates +content: + application/json: + schema: + type: object + required: + - lat + - long + properties: + lat: + type: number + long: + type: number +``` + +#### Request Body Object + +Describes a single request body. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +description | `string` | A brief description of the request body. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | **REQUIRED**. The content of the request body. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* +required | `boolean` | Determines if the request body is required in the request. Defaults to `false`. + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Request Body Examples + +A request body with a referenced model definition. +```json +{ + "description": "user to add to the system", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + }, + "examples": { + "user" : { + "summary": "User Example", + "externalValue": "https://foo.bar/examples/user-example.json" + } + } + }, + "application/xml": { + "schema": { + "$ref": "#/components/schemas/User" + }, + "examples": { + "user" : { + "summary": "User example in XML", + "externalValue": "https://foo.bar/examples/user-example.xml" + } + } + }, + "text/plain": { + "examples": { + "user" : { + "summary": "User example in Plain text", + "externalValue": "https://foo.bar/examples/user-example.txt" + } + } + }, + "*/*": { + "examples": { + "user" : { + "summary": "User example in other format", + "externalValue": "https://foo.bar/examples/user-example.whatever" + } + } + } + } +} +``` + +```yaml +description: user to add to the system +content: + 'application/json': + schema: + $ref: '#/components/schemas/User' + examples: + user: + summary: User Example + externalValue: 'https://foo.bar/examples/user-example.json' + 'application/xml': + schema: + $ref: '#/components/schemas/User' + examples: + user: + summary: User example in XML + externalValue: 'https://foo.bar/examples/user-example.xml' + 'text/plain': + examples: + user: + summary: User example in Plain text + externalValue: 'https://foo.bar/examples/user-example.txt' + '*/*': + examples: + user: + summary: User example in other format + externalValue: 'https://foo.bar/examples/user-example.whatever' +``` + +A body parameter that is an array of string values: +```json +{ + "description": "user to add to the system", + "required": true, + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + } +} +``` + +```yaml +description: user to add to the system +required: true +content: + text/plain: + schema: + type: array + items: + type: string +``` + + +#### Media Type Object +Each Media Type Object provides schema and examples for the media type identified by its key. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +schema | [Schema Object](#schemaObject) | The schema defining the content of the request, response, or parameter. +example | Any | Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` which contains an example, the `example` value SHALL _override_ the example provided by the schema. +examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` which contains an example, the `examples` value SHALL _override_ the example provided by the schema. +encoding | Map[`string`, [Encoding Object](#encodingObject)] | A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to `requestBody` objects when the media type is `multipart` or `application/x-www-form-urlencoded`. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Media Type Examples + +```json +{ + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pet" + }, + "examples": { + "cat" : { + "summary": "An example of a cat", + "value": + { + "name": "Fluffy", + "petType": "Cat", + "color": "White", + "gender": "male", + "breed": "Persian" + } + }, + "dog": { + "summary": "An example of a dog with a cat's name", + "value" : { + "name": "Puma", + "petType": "Dog", + "color": "Black", + "gender": "Female", + "breed": "Mixed" + }, + "frog": { + "$ref": "#/components/examples/frog-example" + } + } + } + } +} +``` + +```yaml +application/json: + schema: + $ref: "#/components/schemas/Pet" + examples: + cat: + summary: An example of a cat + value: + name: Fluffy + petType: Cat + color: White + gender: male + breed: Persian + dog: + summary: An example of a dog with a cat's name + value: + name: Puma + petType: Dog + color: Black + gender: Female + breed: Mixed + frog: + $ref: "#/components/examples/frog-example" +``` + +##### Considerations for File Uploads + +In contrast with the 2.0 specification, `file` input/output content in OpenAPI is described with the same semantics as any other schema type. + +In contrast with the 3.0 specification, the `format` keyword has no effect on the content-encoding of the schema. JSON Schema offers a `contentEncoding` keyword, which may be used to specify the `Content-Encoding` for the schema. The `contentEncoding` keyword supports all encodings defined in [RFC4648](https://tools.ietf.org/html/rfc4648), including "base64" and "base64url", as well as "quoted-printable" from [RFC2045](https://tools.ietf.org/html/rfc2045#section-6.7). The encoding specified by the `contentEncoding` keyword is independent of an encoding specified by the `Content-Type` header in the request or response or metadata of a multipart body -- when both are present, the encoding specified in the `contentEncoding` is applied first and then the encoding specified in the `Content-Type` header. + +JSON Schema also offers a `contentMediaType` keyword. However, when the media type is already specified by the Media Type Object's key, or by the `contentType` field of an [Encoding Object](#encodingObject), the `contentMediaType` keyword SHALL be ignored if present. + +Examples: + +Content transferred in binary (octet-stream) MAY omit `schema`: + +```yaml +# a PNG image as a binary file: +content: + image/png: {} +``` + +```yaml +# an arbitrary binary file: +content: + application/octet-stream: {} +``` + +Binary content transferred with base64 encoding: + +```yaml +content: + image/png: + schema: + type: string + contentMediaType: image/png + contentEncoding: base64 +``` + +Note that the `Content-Type` remains `image/png`, describing the semantics of the payload. The JSON Schema `type` and `contentEncoding` fields explain that the payload is transferred as text. The JSON Schema `contentMediaType` is technically redundant, but can be used by JSON Schema tools that may not be aware of the OpenAPI context. + +These examples apply to either input payloads of file uploads or response payloads. + +A `requestBody` for submitting a file in a `POST` operation may look like the following example: + +```yaml +requestBody: + content: + application/octet-stream: {} +``` + +In addition, specific media types MAY be specified: + +```yaml +# multiple, specific media types may be specified: +requestBody: + content: + # a binary file of type png or jpeg + image/jpeg: {} + image/png: {} +``` + +To upload multiple files, a `multipart` media type MUST be used: + +```yaml +requestBody: + content: + multipart/form-data: + schema: + properties: + # The property name 'file' will be used for all files. + file: + type: array + items: {} +``` + +As seen in the section on `multipart/form-data` below, the empty schema for `items` indicates a media type of `application/octet-stream`. + +##### Support for x-www-form-urlencoded Request Bodies + +To submit content using form url encoding via [RFC1866](https://tools.ietf.org/html/rfc1866), the following +definition may be used: + +```yaml +requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + # complex types are stringified to support RFC 1866 + type: object + properties: {} +``` + +In this example, the contents in the `requestBody` MUST be stringified per [RFC1866](https://tools.ietf.org/html/rfc1866/) when passed to the server. In addition, the `address` field complex object will be stringified. + +When passing complex objects in the `application/x-www-form-urlencoded` content type, the default serialization strategy of such properties is described in the [`Encoding Object`](#encodingObject)'s [`style`](#encodingStyle) property as `form`. + +##### Special Considerations for `multipart` Content + +It is common to use `multipart/form-data` as a `Content-Type` when transferring request bodies to operations. In contrast to 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content. This supports complex structures as well as supporting mechanisms for multiple file uploads. + +In a `multipart/form-data` request body, each schema property, or each element of a schema array property, takes a section in the payload with an internal header as defined by [RFC7578](https://tools.ietf.org/html/rfc7578). The serialization strategy for each property of a `multipart/form-data` request body can be specified in an associated [`Encoding Object`](#encodingObject). + +When passing in `multipart` types, boundaries MAY be used to separate sections of the content being transferred – thus, the following default `Content-Type`s are defined for `multipart`: + +* If the property is a primitive, or an array of primitive values, the default Content-Type is `text/plain` +* If the property is complex, or an array of complex values, the default Content-Type is `application/json` +* If the property is a `type: string` with a `contentEncoding`, the default Content-Type is `application/octet-stream` + +Per the JSON Schema specification, `contentMediaType` without `contentEncoding` present is treated as if `contentEncoding: identity` were present. While useful for embedding text documents such as `text/html` into JSON strings, it is not useful for a `multipart/form-data` part, as it just causes the document to be treated as `text/plain` instead of its actual media type. Use the Encoding Object without `contentMediaType` if no `contentEncoding` is required. + +Examples: + +```yaml +requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + # default Content-Type for objects is `application/json` + type: object + properties: {} + profileImage: + # Content-Type for application-level encoded resource is `text/plain` + type: string + contentMediaType: image/png + contentEncoding: base64 + children: + # default Content-Type for arrays is based on the _inner_ type (`text/plain` here) + type: array + items: + type: string + addresses: + # default Content-Type for arrays is based on the _inner_ type (object shown, so `application/json` in this example) + type: array + items: + type: object + $ref: '#/components/schemas/Address' +``` + +An `encoding` attribute is introduced to give you control over the serialization of parts of `multipart` request bodies. This attribute is _only_ applicable to `multipart` and `application/x-www-form-urlencoded` request bodies. + +#### Encoding Object + +A single encoding definition applied to a single schema property. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +contentType | `string` | The Content-Type for encoding a specific property. Default value depends on the property type: for `object` - `application/json`; for `array` – the default is defined based on the inner type; for all other cases the default is `application/octet-stream`. The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or a comma-separated list of the two types. +headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | A map allowing additional information to be provided as headers, for example `Content-Disposition`. `Content-Type` is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a `multipart`. +style | `string` | Describes how a specific property value will be serialized depending on its type. See [Parameter Object](#parameterObject) for details on the [`style`](#parameterStyle) property. The behavior follows the same values as `query` parameters, including default values. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of [`contentType`](#encodingContentType) (implicit or explicit) SHALL be ignored. +explode | `boolean` | When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When [`style`](#encodingStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of [`contentType`](#encodingContentType) (implicit or explicit) SHALL be ignored. +allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of [`contentType`](#encodingContentType) (implicit or explicit) SHALL be ignored. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Encoding Object Example + +```yaml +requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + id: + # default is text/plain + type: string + format: uuid + address: + # default is application/json + type: object + properties: {} + historyMetadata: + # need to declare XML format! + description: metadata in XML format + type: object + properties: {} + profileImage: {} + encoding: + historyMetadata: + # require XML Content-Type in utf-8 encoding + contentType: application/xml; charset=utf-8 + profileImage: + # only accept png/jpeg + contentType: image/png, image/jpeg + headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer +``` + +#### Responses Object + +A container for the expected responses of an operation. +The container maps a HTTP response code to the expected response. + +The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. +However, documentation is expected to cover a successful operation response and any known errors. + +The `default` MAY be used as a default response object for all HTTP codes +that are not covered individually by the `Responses Object`. + +The `Responses Object` MUST contain at least one response code, and if only one +response code is provided it SHOULD be the response for a successful operation +call. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +default | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +[HTTP Status Code](#httpCodes) | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | Any [HTTP status code](#httpCodes) can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `[200-299]`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Responses Object Example + +A 200 response for a successful operation and a default response for others (implying an error): + +```json +{ + "200": { + "description": "a pet to be returned", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pet" + } + } + } + }, + "default": { + "description": "Unexpected error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } +} +``` + +```yaml +'200': + description: a pet to be returned + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +default: + description: Unexpected error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorModel' +``` + +#### Response Object +Describes a single response from an API Operation, including design-time, static +`links` to operations based on the response. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +description | `string` | **REQUIRED**. A description of the response. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | Maps a header name to its definition. [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL be ignored. +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing descriptions of potential response payloads. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* +links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for [Component Objects](#componentsObject). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Response Object Examples + +Response of an array of a complex type: + +```json +{ + "description": "A complex object array response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VeryComplexType" + } + } + } + } +} +``` + +```yaml +description: A complex object array response +content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/VeryComplexType' +``` + +Response with a string type: + +```json +{ + "description": "A simple string response", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + +} +``` + +```yaml +description: A simple string response +content: + text/plain: + schema: + type: string +``` + +Plain text response with headers: + +```json +{ + "description": "A simple string response", + "content": { + "text/plain": { + "schema": { + "type": "string", + "example": "whoa!" + } + } + }, + "headers": { + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Remaining": { + "description": "The number of remaining requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Reset": { + "description": "The number of seconds left in the current period", + "schema": { + "type": "integer" + } + } + } +} +``` + +```yaml +description: A simple string response +content: + text/plain: + schema: + type: string + example: 'whoa!' +headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer + X-Rate-Limit-Remaining: + description: The number of remaining requests in the current period + schema: + type: integer + X-Rate-Limit-Reset: + description: The number of seconds left in the current period + schema: + type: integer +``` + +Response with no return value: + +```json +{ + "description": "object created" +} +``` + +```yaml +description: object created +``` + +#### Callback Object + +A map of possible out-of band callbacks related to the parent operation. +Each value in the map is a [Path Item Object](#pathItemObject) that describes a set of requests that may be initiated by the API provider and the expected responses. +The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. + +To describe incoming requests from the API provider independent from another API call, use the [`webhooks`](#oasWebhooks) field. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +{expression} | [Path Item Object](#pathItemObject) \| [Reference Object](#referenceObject) | A Path Item Object, or a reference to one, used to define a callback request and expected responses. A [complete example](../examples/v3.0/callback-example.yaml) is available. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Key Expression + +The key that identifies the [Path Item Object](#pathItemObject) is a [runtime expression](#runtimeExpression) that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. +A simple example might be `$request.body#/url`. +However, using a [runtime expression](#runtimeExpression) the complete HTTP message can be accessed. +This includes accessing any part of a body that a JSON Pointer [RFC6901](https://tools.ietf.org/html/rfc6901) can reference. + +For example, given the following HTTP request: + +```http +POST /subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning HTTP/1.1 +Host: example.org +Content-Type: application/json +Content-Length: 187 + +{ + "failedUrl" : "https://clientdomain.com/failed", + "successUrls" : [ + "https://clientdomain.com/fast", + "https://clientdomain.com/medium", + "https://clientdomain.com/slow" + ] +} + +201 Created +Location: https://example.org/subscription/1 +``` + +The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named `eventType` and a query parameter named `queryUrl`. + +Expression | Value +---|:--- +$url | https://example.org/subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning +$method | POST +$request.path.eventType | myevent +$request.query.queryUrl | https://clientdomain.com/stillrunning +$request.header.content-Type | application/json +$request.body#/failedUrl | https://clientdomain.com/failed +$request.body#/successUrls/2 | https://clientdomain.com/medium +$response.header.Location | https://example.org/subscription/1 + + +##### Callback Object Examples + +The following example uses the user provided `queryUrl` query string parameter to define the callback URL. This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook. + +```yaml +myCallback: + '{$request.query.queryUrl}': + post: + requestBody: + description: Callback payload + content: + 'application/json': + schema: + $ref: '#/components/schemas/SomePayload' + responses: + '200': + description: callback successfully processed +``` + +The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the `id` and `email` property in the request body. + +```yaml +transactionCallback: + 'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}': + post: + requestBody: + description: Callback payload + content: + 'application/json': + schema: + $ref: '#/components/schemas/SomePayload' + responses: + '200': + description: callback successfully processed +``` + +#### Example Object + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +summary | `string` | Short description for the example. +description | `string` | Long description for the example. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +value | Any | Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary. +externalValue | `string` | A URI that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. See the rules for resolving [Relative References](#relativeReferencesURI). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +In all cases, the example value is expected to be compatible with the type schema +of its associated value. Tooling implementations MAY choose to +validate compatibility automatically, and reject the example value(s) if incompatible. + +##### Example Object Examples + +In a request body: + +```yaml +requestBody: + content: + 'application/json': + schema: + $ref: '#/components/schemas/Address' + examples: + foo: + summary: A foo example + value: {"foo": "bar"} + bar: + summary: A bar example + value: {"bar": "baz"} + 'application/xml': + examples: + xmlExample: + summary: This is an example in XML + externalValue: 'https://example.org/examples/address-example.xml' + 'text/plain': + examples: + textExample: + summary: This is a text example + externalValue: 'https://foo.bar/examples/address-example.txt' +``` + +In a parameter: + +```yaml +parameters: + - name: 'zipCode' + in: 'query' + schema: + type: 'string' + format: 'zip-code' + examples: + zip-example: + $ref: '#/components/examples/zip-example' +``` + +In a response: + +```yaml +responses: + '200': + description: your car appointment has been booked + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessResponse' + examples: + confirmation-success: + $ref: '#/components/examples/confirmation-success' +``` + + +#### Link Object + +The `Link object` represents a possible design-time link for a response. +The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. + +Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. + +For computing links, and providing instructions to execute them, a [runtime expression](#runtimeExpression) is used for accessing values in an operation and using them as parameters while invoking the linked operation. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +operationRef | `string` | A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an [Operation Object](#operationObject). Relative `operationRef` values MAY be used to locate an existing [Operation Object](#operationObject) in the OpenAPI definition. See the rules for resolving [Relative References](#relativeReferencesURI). +operationId | `string` | The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field. +parameters | Map[`string`, Any \| [{expression}](#runtimeExpression)] | A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the [parameter location](#parameterIn) `[{in}.]{name}` for operations that use the same parameter name in different locations (e.g. path.id). +requestBody | Any \| [{expression}](#runtimeExpression) | A literal value or [{expression}](#runtimeExpression) to use as a request body when calling the target operation. +description | `string` | A description of the link. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +server | [Server Object](#serverObject) | A server object to be used by the target operation. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +A linked operation MUST be identified using either an `operationRef` or `operationId`. +In the case of an `operationId`, it MUST be unique and resolved in the scope of the OAS document. +Because of the potential for name clashes, the `operationRef` syntax is preferred +for OpenAPI documents with external references. + +##### Examples + +Computing a link from a request operation where the `$request.path.id` is used to pass a request parameter to the linked operation. + +```yaml +paths: + /users/{id}: + parameters: + - name: id + in: path + required: true + description: the user identifier, as userId + schema: + type: string + get: + responses: + '200': + description: the user being returned + content: + application/json: + schema: + type: object + properties: + uuid: # the unique user id + type: string + format: uuid + links: + address: + # the target link operationId + operationId: getUserAddress + parameters: + # get the `id` field from the request path parameter named `id` + userId: $request.path.id + # the path item of the linked operation + /users/{userid}/address: + parameters: + - name: userid + in: path + required: true + description: the user identifier, as userId + schema: + type: string + # linked operation + get: + operationId: getUserAddress + responses: + '200': + description: the user's address +``` + +When a runtime expression fails to evaluate, no parameter value is passed to the target operation. + +Values from the response body can be used to drive a linked operation. + +```yaml +links: + address: + operationId: getUserAddressByUUID + parameters: + # get the `uuid` field from the `uuid` field in the response body + userUuid: $response.body#/uuid +``` + +Clients follow all links at their discretion. +Neither permissions, nor the capability to make a successful call to that link, is guaranteed +solely by the existence of a relationship. + + +##### OperationRef Examples + +As references to `operationId` MAY NOT be possible (the `operationId` is an optional +field in an [Operation Object](#operationObject)), references MAY also be made through a relative `operationRef`: + +```yaml +links: + UserRepositories: + # returns array of '#/components/schemas/repository' + operationRef: '#/paths/~12.0~1repositories~1{username}/get' + parameters: + username: $response.body#/username +``` + +or an absolute `operationRef`: + +```yaml +links: + UserRepositories: + # returns array of '#/components/schemas/repository' + operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get' + parameters: + username: $response.body#/username +``` + +Note that in the use of `operationRef`, the _escaped forward-slash_ is necessary when +using JSON references. + + +##### Runtime Expressions + +Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. +This mechanism is used by [Link Objects](#linkObject) and [Callback Objects](#callbackObject). + +The runtime expression is defined by the following [ABNF](https://tools.ietf.org/html/rfc5234) syntax + +```abnf + expression = ( "$url" / "$method" / "$statusCode" / "$request." source / "$response." source ) + source = ( header-reference / query-reference / path-reference / body-reference ) + header-reference = "header." token + query-reference = "query." name + path-reference = "path." name + body-reference = "body" ["#" json-pointer ] + json-pointer = *( "/" reference-token ) + reference-token = *( unescaped / escaped ) + unescaped = %x00-2E / %x30-7D / %x7F-10FFFF + ; %x2F ('/') and %x7E ('~') are excluded from 'unescaped' + escaped = "~" ( "0" / "1" ) + ; representing '~' and '/', respectively + name = *( CHAR ) + token = 1*tchar + tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / + "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA +``` + +Here, `json-pointer` is taken from [RFC6901](https://tools.ietf.org/html/rfc6901), `char` from [RFC7159](https://tools.ietf.org/html/rfc7159#section-7) and `token` from [RFC7230](https://tools.ietf.org/html/rfc7230#section-3.2.6). + +The `name` identifier is case-sensitive, whereas `token` is not. + +The table below provides examples of runtime expressions and examples of their use in a value: + +##### Examples + +Source Location | example expression | notes +---|:---|:---| +HTTP Method | `$method` | The allowable values for the `$method` will be those for the HTTP operation. +Requested media type | `$request.header.accept` | +Request parameter | `$request.path.id` | Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated. This includes request headers. +Request body property | `$request.body#/user/uuid` | In operations which accept payloads, references may be made to portions of the `requestBody` or the entire body. +Request URL | `$url` | +Response value | `$response.body#/status` | In operations which return payloads, references may be made to portions of the response body or the entire body. +Response header | `$response.header.Server` | Single header values only are available + +Runtime expressions preserve the type of the referenced value. +Expressions can be embedded into string values by surrounding the expression with `{}` curly braces. + +#### Header Object + +The Header Object follows the structure of the [Parameter Object](#parameterObject) with the following changes: + +1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. +1. `in` MUST NOT be specified, it is implicitly in `header`. +1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, [`style`](#parameterStyle)). + +##### Header Object Example + +A simple header of type `integer`: + +```json +{ + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } +} +``` + +```yaml +description: The number of allowed requests in the current period +schema: + type: integer +``` + +#### Tag Object + +Adds metadata to a single tag that is used by the [Operation Object](#operationObject). +It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The name of the tag. +description | `string` | A description for the tag. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this tag. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Tag Object Example + +```json +{ + "name": "pet", + "description": "Pets operations" +} +``` + +```yaml +name: pet +description: Pets operations +``` + + +#### Reference Object + +A simple object to allow referencing other components in the OpenAPI document, internally and externally. + +The `$ref` string value contains a URI [RFC3986](https://tools.ietf.org/html/rfc3986), which identifies the location of the value being referenced. + +See the rules for resolving [Relative References](#relativeReferencesURI). + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +$ref | `string` | **REQUIRED**. The reference identifier. This MUST be in the form of a URI. +summary | `string` | A short summary which by default SHOULD override that of the referenced component. If the referenced object-type does not allow a `summary` field, then this field has no effect. +description | `string` | A description which by default SHOULD override that of the referenced component. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. If the referenced object-type does not allow a `description` field, then this field has no effect. + +This object cannot be extended with additional properties and any properties added SHALL be ignored. + +Note that this restriction on additional properties is a difference between Reference Objects and [`Schema Objects`](#schemaObject) that contain a `$ref` keyword. + +##### Reference Object Example + +```json +{ + "$ref": "#/components/schemas/Pet" +} +``` + +```yaml +$ref: '#/components/schemas/Pet' +``` + +##### Relative Schema Document Example +```json +{ + "$ref": "Pet.json" +} +``` + +```yaml +$ref: Pet.yaml +``` + +##### Relative Documents With Embedded Schema Example +```json +{ + "$ref": "definitions.json#/Pet" +} +``` + +```yaml +$ref: definitions.yaml#/Pet +``` + +#### Schema Object + +The Schema Object allows the definition of input and output data types. +These types can be objects, but also primitives and arrays. This object is a superset of the [JSON Schema Specification Draft 2020-12](https://tools.ietf.org/html/draft-bhutton-json-schema-00). + +For more information about the properties, see [JSON Schema Core](https://tools.ietf.org/html/draft-bhutton-json-schema-00) and [JSON Schema Validation](https://tools.ietf.org/html/draft-bhutton-json-schema-validation-00). + +Unless stated otherwise, the property definitions follow those of JSON Schema and do not add any additional semantics. +Where JSON Schema indicates that behavior is defined by the application (e.g. for annotations), OAS also defers the definition of semantics to the application consuming the OpenAPI document. + +##### Properties + +The OpenAPI Schema Object [dialect](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-4.3.3) is defined as requiring the [OAS base vocabulary](#baseVocabulary), in addition to the vocabularies as specified in the JSON Schema draft 2020-12 [general purpose meta-schema](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-8). + +The OpenAPI Schema Object dialect for this version of the specification is identified by the URI `https://spec.openapis.org/oas/3.1/dialect/base` (the "OAS dialect schema id"). + +The following properties are taken from the JSON Schema specification but their definitions have been extended by the OAS: + +- description - [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +- format - See [Data Type Formats](#dataTypeFormat) for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats. + +In addition to the JSON Schema properties comprising the OAS dialect, the Schema Object supports keywords from any other vocabularies, or entirely arbitrary properties. + +The OpenAPI Specification's base vocabulary is comprised of the following keywords: + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +discriminator | [Discriminator Object](#discriminatorObject) | Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See [Composition and Inheritance](#schemaComposition) for more details. +xml | [XML Object](#xmlObject) | This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this schema. +example | Any | A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary.

**Deprecated:** The `example` property has been deprecated in favor of the JSON Schema `examples` keyword. Use of `example` is discouraged, and later versions of this specification may remove it. + +This object MAY be extended with [Specification Extensions](#specificationExtensions), though as noted, additional properties MAY omit the `x-` prefix within this object. + +###### Composition and Inheritance (Polymorphism) + +The OpenAPI Specification allows combining and extending model definitions using the `allOf` property of JSON Schema, in effect offering model composition. +`allOf` takes an array of object definitions that are validated *independently* but together compose a single object. + +While composition offers model extensibility, it does not imply a hierarchy between the models. +To support polymorphism, the OpenAPI Specification adds the `discriminator` field. +When used, the `discriminator` will be the name of the property that decides which schema definition validates the structure of the model. +As such, the `discriminator` field MUST be a required field. +There are two ways to define the value of a discriminator for an inheriting instance. +- Use the schema name. +- Override the schema name by overriding the property with a new value. If a new value exists, this takes precedence over the schema name. +As such, inline schema definitions, which do not have a given id, *cannot* be used in polymorphism. + +###### XML Modeling + +The [xml](#schemaXml) property allows extra definitions when translating the JSON definition to XML. +The [XML Object](#xmlObject) contains additional information about the available options. + +###### Specifying Schema Dialects + +It is important for tooling to be able to determine which dialect or meta-schema any given resource wishes to be processed with: JSON Schema Core, JSON Schema Validation, OpenAPI Schema dialect, or some custom meta-schema. + +The `$schema` keyword MAY be present in any root Schema Object, and if present MUST be used to determine which dialect should be used when processing the schema. This allows use of Schema Objects which comply with other drafts of JSON Schema than the default Draft 2020-12 support. Tooling MUST support the OAS dialect schema id, and MAY support additional values of `$schema`. + +To allow use of a different default `$schema` value for all Schema Objects contained within an OAS document, a `jsonSchemaDialect` value may be set within the OpenAPI Object. If this default is not set, then the OAS dialect schema id MUST be used for these Schema Objects. The value of `$schema` within a Schema Object always overrides any default. + +When a Schema Object is referenced from an external resource which is not an OAS document (e.g. a bare JSON Schema resource), then the value of the `$schema` keyword for schemas within that resource MUST follow [JSON Schema rules](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-8.1.1). + +##### Schema Object Examples + +###### Primitive Sample + +```json +{ + "type": "string", + "format": "email" +} +``` + +```yaml +type: string +format: email +``` + +###### Simple Model + +```json +{ + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "address": { + "$ref": "#/components/schemas/Address" + }, + "age": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } +} +``` + +```yaml +type: object +required: +- name +properties: + name: + type: string + address: + $ref: '#/components/schemas/Address' + age: + type: integer + format: int32 + minimum: 0 +``` + +###### Model with Map/Dictionary Properties + +For a simple string to string mapping: + +```json +{ + "type": "object", + "additionalProperties": { + "type": "string" + } +} +``` + +```yaml +type: object +additionalProperties: + type: string +``` + +For a string to model mapping: + +```json +{ + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ComplexModel" + } +} +``` + +```yaml +type: object +additionalProperties: + $ref: '#/components/schemas/ComplexModel' +``` + +###### Model with Example + +```json +{ + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name" + ], + "example": { + "name": "Puma", + "id": 1 + } +} +``` + +```yaml +type: object +properties: + id: + type: integer + format: int64 + name: + type: string +required: +- name +example: + name: Puma + id: 1 +``` + +###### Models with Composition + +```json +{ + "components": { + "schemas": { + "ErrorModel": { + "type": "object", + "required": [ + "message", + "code" + ], + "properties": { + "message": { + "type": "string" + }, + "code": { + "type": "integer", + "minimum": 100, + "maximum": 600 + } + } + }, + "ExtendedErrorModel": { + "allOf": [ + { + "$ref": "#/components/schemas/ErrorModel" + }, + { + "type": "object", + "required": [ + "rootCause" + ], + "properties": { + "rootCause": { + "type": "string" + } + } + } + ] + } + } + } +} +``` + +```yaml +components: + schemas: + ErrorModel: + type: object + required: + - message + - code + properties: + message: + type: string + code: + type: integer + minimum: 100 + maximum: 600 + ExtendedErrorModel: + allOf: + - $ref: '#/components/schemas/ErrorModel' + - type: object + required: + - rootCause + properties: + rootCause: + type: string +``` + +###### Models with Polymorphism Support + +```json +{ + "components": { + "schemas": { + "Pet": { + "type": "object", + "discriminator": { + "propertyName": "petType" + }, + "properties": { + "name": { + "type": "string" + }, + "petType": { + "type": "string" + } + }, + "required": [ + "name", + "petType" + ] + }, + "Cat": { + "description": "A representation of a cat. Note that `Cat` will be used as the discriminator value.", + "allOf": [ + { + "$ref": "#/components/schemas/Pet" + }, + { + "type": "object", + "properties": { + "huntingSkill": { + "type": "string", + "description": "The measured skill for hunting", + "default": "lazy", + "enum": [ + "clueless", + "lazy", + "adventurous", + "aggressive" + ] + } + }, + "required": [ + "huntingSkill" + ] + } + ] + }, + "Dog": { + "description": "A representation of a dog. Note that `Dog` will be used as the discriminator value.", + "allOf": [ + { + "$ref": "#/components/schemas/Pet" + }, + { + "type": "object", + "properties": { + "packSize": { + "type": "integer", + "format": "int32", + "description": "the size of the pack the dog is from", + "default": 0, + "minimum": 0 + } + }, + "required": [ + "packSize" + ] + } + ] + } + } + } +} +``` + +```yaml +components: + schemas: + Pet: + type: object + discriminator: + propertyName: petType + properties: + name: + type: string + petType: + type: string + required: + - name + - petType + Cat: ## "Cat" will be used as the discriminator value + description: A representation of a cat + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + properties: + huntingSkill: + type: string + description: The measured skill for hunting + enum: + - clueless + - lazy + - adventurous + - aggressive + required: + - huntingSkill + Dog: ## "Dog" will be used as the discriminator value + description: A representation of a dog + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + properties: + packSize: + type: integer + format: int32 + description: the size of the pack the dog is from + default: 0 + minimum: 0 + required: + - packSize +``` + +#### Discriminator Object + +When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the document of an alternative schema based on the value associated with it. + +When using the discriminator, _inline_ schemas will not be considered. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +propertyName | `string` | **REQUIRED**. The name of the property in the payload that will hold the discriminator value. + mapping | Map[`string`, `string`] | An object to hold mappings between payload values and schema names or references. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +The discriminator object is legal only when using one of the composite keywords `oneOf`, `anyOf`, `allOf`. + +In OAS 3.0, a response payload MAY be described to be exactly one of any number of types: + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' +``` + +which means the payload _MUST_, by validation, match exactly one of the schemas described by `Cat`, `Dog`, or `Lizard`. In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use: + + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' + discriminator: + propertyName: petType +``` + +The expectation now is that a property with name `petType` _MUST_ be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload: + +```json +{ + "id": 12345, + "petType": "Cat" +} +``` + +Will indicate that the `Cat` schema be used in conjunction with this payload. + +In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used: + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' + - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json' + discriminator: + propertyName: petType + mapping: + dog: '#/components/schemas/Dog' + monster: 'https://gigantic-server.com/schemas/Monster/schema.json' +``` + +Here the discriminator _value_ of `dog` will map to the schema `#/components/schemas/Dog`, rather than the default (implicit) value of `Dog`. If the discriminator _value_ does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison. + +When used in conjunction with the `anyOf` construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload. + +In both the `oneOf` and `anyOf` use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an `allOf` construct may be used as an alternate schema. + +For example: + +```yaml +components: + schemas: + Pet: + type: object + required: + - petType + properties: + petType: + type: string + discriminator: + propertyName: petType + mapping: + dog: Dog + Cat: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Cat` + properties: + name: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Dog` + properties: + bark: + type: string + Lizard: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Lizard` + properties: + lovesRocks: + type: boolean +``` + +a payload like this: + +```json +{ + "petType": "Cat", + "name": "misty" +} +``` + +will indicate that the `Cat` schema be used. Likewise this schema: + +```json +{ + "petType": "dog", + "bark": "soft" +} +``` + +will map to `Dog` because of the definition in the `mapping` element. + + +#### XML Object + +A metadata object that allows for more fine-tuned XML model definitions. + +When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. +See examples for expected behavior. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. +namespace | `string` | The URI of the namespace definition. This MUST be in the form of an absolute URI. +prefix | `string` | The prefix to be used for the [name](#xmlName). +attribute | `boolean` | Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. +wrapped | `boolean` | MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### XML Object Examples + +The examples of the XML object definitions are included inside a property definition of a [Schema Object](#schemaObject) with a sample of the XML representation of it. + +###### No XML Element + +Basic string property: + +```json +{ + "animals": { + "type": "string" + } +} +``` + +```yaml +animals: + type: string +``` + +```xml +... +``` + +Basic string array property ([`wrapped`](#xmlWrapped) is `false` by default): + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string +``` + +```xml +... +... +... +``` + +###### XML Name Replacement + +```json +{ + "animals": { + "type": "string", + "xml": { + "name": "animal" + } + } +} +``` + +```yaml +animals: + type: string + xml: + name: animal +``` + +```xml +... +``` + + +###### XML Attribute, Prefix and Namespace + +In this example, a full model definition is shown. + +```json +{ + "Person": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32", + "xml": { + "attribute": true + } + }, + "name": { + "type": "string", + "xml": { + "namespace": "https://example.com/schema/sample", + "prefix": "sample" + } + } + } + } +} +``` + +```yaml +Person: + type: object + properties: + id: + type: integer + format: int32 + xml: + attribute: true + name: + type: string + xml: + namespace: https://example.com/schema/sample + prefix: sample +``` + +```xml + + example + +``` + +###### XML Arrays + +Changing the element names: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal +``` + +```xml +value +value +``` + +The external `name` property has no effect on the XML: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens +``` + +```xml +value +value +``` + +Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + wrapped: true +``` + +```xml + + value + value + +``` + +To overcome the naming problem in the example above, the following definition can be used: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + wrapped: true +``` + +```xml + + value + value + +``` + +Affecting both internal and external names: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens + wrapped: true +``` + +```xml + + value + value + +``` + +If we change the external element but not the internal ones: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: aliens + wrapped: true +``` + +```xml + + value + value + +``` + +#### Security Scheme Object + +Defines a security scheme that can be used by the operations. + +Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), mutual TLS (use of a client certificate), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749](https://tools.ietf.org/html/rfc6749), and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06). +Please note that as of 2020, the implicit flow is about to be deprecated by [OAuth 2.0 Security Best Current Practice](https://tools.ietf.org/html/draft-ietf-oauth-security-topics). Recommended for most use case is Authorization Code Grant flow with PKCE. + +##### Fixed Fields +Field Name | Type | Applies To | Description +---|:---:|---|--- +type | `string` | Any | **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"mutualTLS"`, `"oauth2"`, `"openIdConnect"`. +description | `string` | Any | A description for security scheme. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +name | `string` | `apiKey` | **REQUIRED**. The name of the header, query or cookie parameter to be used. +in | `string` | `apiKey` | **REQUIRED**. The location of the API key. Valid values are `"query"`, `"header"` or `"cookie"`. +scheme | `string` | `http` | **REQUIRED**. The name of the HTTP Authorization scheme to be used in the [Authorization header as defined in RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1). The values used SHOULD be registered in the [IANA Authentication Scheme registry](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml). +bearerFormat | `string` | `http` (`"bearer"`) | A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. +flows | [OAuth Flows Object](#oauthFlowsObject) | `oauth2` | **REQUIRED**. An object containing configuration information for the flow types supported. +openIdConnectUrl | `string` | `openIdConnect` | **REQUIRED**. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL. The OpenID Connect standard requires the use of TLS. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Security Scheme Object Example + +###### Basic Authentication Sample + +```json +{ + "type": "http", + "scheme": "basic" +} +``` + +```yaml +type: http +scheme: basic +``` + +###### API Key Sample + +```json +{ + "type": "apiKey", + "name": "api_key", + "in": "header" +} +``` + +```yaml +type: apiKey +name: api_key +in: header +``` + +###### JWT Bearer Sample + +```json +{ + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT", +} +``` + +```yaml +type: http +scheme: bearer +bearerFormat: JWT +``` + +###### Implicit OAuth2 Sample + +```json +{ + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } +} +``` + +```yaml +type: oauth2 +flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### OAuth Flows Object + +Allows configuration of the supported OAuth Flows. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +implicit| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Implicit flow +password| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Resource Owner Password flow +clientCredentials| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0. +authorizationCode| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### OAuth Flow Object + +Configuration details for a supported OAuth Flow + +##### Fixed Fields +Field Name | Type | Applies To | Description +---|:---:|---|--- +authorizationUrl | `string` | `oauth2` (`"implicit"`, `"authorizationCode"`) | **REQUIRED**. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. +tokenUrl | `string` | `oauth2` (`"password"`, `"clientCredentials"`, `"authorizationCode"`) | **REQUIRED**. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. +refreshUrl | `string` | `oauth2` | The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. +scopes | Map[`string`, `string`] | `oauth2` | **REQUIRED**. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### OAuth Flow Object Examples + +```JSON +{ + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "authorizationCode": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "tokenUrl": "https://example.com/api/oauth/token", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } +} +``` + +```yaml +type: oauth2 +flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + authorizationCode: + authorizationUrl: https://example.com/api/oauth/dialog + tokenUrl: https://example.com/api/oauth/token + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### Security Requirement Object + +Lists the required security schemes to execute this operation. +The name used for each property MUST correspond to a security scheme declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). + +Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. +This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. + +When a list of Security Requirement Objects is defined on the [OpenAPI Object](#oasObject) or [Operation Object](#operationObject), only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +{name} | [`string`] | Each name MUST correspond to a security scheme which is declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). If the security scheme is of type `"oauth2"` or `"openIdConnect"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band. + +##### Security Requirement Object Examples + +###### Non-OAuth2 Security Requirement + +```json +{ + "api_key": [] +} +``` + +```yaml +api_key: [] +``` + +###### OAuth2 Security Requirement + +```json +{ + "petstore_auth": [ + "write:pets", + "read:pets" + ] +} +``` + +```yaml +petstore_auth: +- write:pets +- read:pets +``` + +###### Optional OAuth2 Security + +Optional OAuth2 security as would be defined in an OpenAPI Object or an Operation Object: + +```json +{ + "security": [ + {}, + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] +} +``` + +```yaml +security: + - {} + - petstore_auth: + - write:pets + - read:pets +``` + +### Specification Extensions + +While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points. + +The extensions properties are implemented as patterned fields that are always prefixed by `"x-"`. + +Field Pattern | Type | Description +---|:---:|--- +^x- | Any | Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. Field names beginning `x-oai-` and `x-oas-` are reserved for uses defined by the [OpenAPI Initiative](https://www.openapis.org/). The value can be `null`, a primitive, an array or an object. + +The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced). + +### Security Filtering + +Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation. + +The reasoning is to allow an additional layer of access control over the documentation. +While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization. + +Two examples of this: + +1. The [Paths Object](#pathsObject) MAY be present but empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They would still have access to at least the [Info Object](#infoObject) which may contain additional information regarding authentication. +2. The [Path Item Object](#pathItemObject) MAY be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different from hiding the path itself from the [Paths Object](#pathsObject), because the user will be aware of its existence. This allows the documentation provider to finely control what the viewer can see. + + +## Appendix A: Revision History + +Version | Date | Notes +--- | --- | --- +3.1.0 | 2021-02-15 | Release of the OpenAPI Specification 3.1.0 +3.1.0-rc1 | 2020-10-08 | rc1 of the 3.1 specification +3.1.0-rc0 | 2020-06-18 | rc0 of the 3.1 specification +3.0.3 | 2020-02-20 | Patch release of the OpenAPI Specification 3.0.3 +3.0.2 | 2018-10-08 | Patch release of the OpenAPI Specification 3.0.2 +3.0.1 | 2017-12-06 | Patch release of the OpenAPI Specification 3.0.1 +3.0.0 | 2017-07-26 | Release of the OpenAPI Specification 3.0.0 +3.0.0-rc2 | 2017-06-16 | rc2 of the 3.0 specification +3.0.0-rc1 | 2017-04-27 | rc1 of the 3.0 specification +3.0.0-rc0 | 2017-02-28 | Implementer's Draft of the 3.0 specification +2.0 | 2015-12-31 | Donation of Swagger 2.0 to the OpenAPI Initiative +2.0 | 2014-09-08 | Release of Swagger 2.0 +1.2 | 2014-03-14 | Initial release of the formal document. +1.1 | 2012-08-22 | Release of Swagger 1.1 +1.0 | 2011-08-10 | First release of the Swagger Specification diff --git a/chaotic-openapi/chaotic_openapi/front/schema/__init__.py b/chaotic-openapi/chaotic_openapi/front/schema/__init__.py new file mode 100644 index 000000000000..21a90f5fb701 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/__init__.py @@ -0,0 +1,31 @@ +__all__ = [ + "DataType", + "MediaType", + "OpenAPI", + "Operation", + "Parameter", + "Parameter", + "ParameterLocation", + "PathItem", + "Reference", + "RequestBody", + "Response", + "Responses", + "Schema", +] + + +from .data_type import DataType +from .openapi_schema_pydantic import ( + MediaType, + OpenAPI, + Operation, + Parameter, + PathItem, + Reference, + RequestBody, + Response, + Responses, + Schema, +) +from .parameter_location import ParameterLocation diff --git a/chaotic-openapi/chaotic_openapi/front/schema/data_type.py b/chaotic-openapi/chaotic_openapi/front/schema/data_type.py new file mode 100644 index 000000000000..1c104142e4f2 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/data_type.py @@ -0,0 +1,18 @@ +from enum import Enum + + +class DataType(str, Enum): + """The data type of a schema is defined by the type keyword + + References: + - https://swagger.io/docs/specification/data-models/data-types/ + - https://json-schema.org/draft/2020-12/json-schema-validation.html#name-type + """ + + STRING = "string" + NUMBER = "number" + INTEGER = "integer" + BOOLEAN = "boolean" + ARRAY = "array" + OBJECT = "object" + NULL = "null" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/LICENSE b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/LICENSE new file mode 100644 index 000000000000..19166577b1a3 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Kuimono + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md new file mode 100644 index 000000000000..3d92b4d018df --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md @@ -0,0 +1,42 @@ +Everything in this directory (including the rest of this file after this paragraph) is a vendored copy of [openapi-schem-pydantic](https://github.com/kuimono/openapi-schema-pydantic) and is licensed under the LICENSE file in this directory. + +Included vendored version is the [following](https://github.com/kuimono/openapi-schema-pydantic/commit/0836b429086917feeb973de3367a7ac4c2b3a665) +Small patches has been applied to it. + +## Alias + +Due to the reserved words in python and pydantic, +the following fields are used with [alias](https://pydantic-docs.helpmanual.io/usage/schema/#field-customisation) feature provided by pydantic: + +| Class | Field name in the class | Alias (as in OpenAPI spec) | +| ----- | ----------------------- | -------------------------- | +| Header[*](#header_param_in) | param_in | in | +| MediaType | media_type_schema | schema | +| Parameter | param_in | in | +| Parameter | param_schema | schema | +| PathItem | ref | $ref | +| Reference | ref | $ref | +| SecurityScheme | security_scheme_in | in | +| Schema | schema_format | format | +| Schema | schema_not | not | + +> The "in" field in Header object is actually a constant (`{"in": "header"}`). + +> For convenience of object creation, the classes mentioned in above +> has configured `allow_population_by_field_name=True`. +> +> Reference: [Pydantic's Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) + +## Non-pydantic schema types + +Due to the constriants of python typing structure (not able to handle dynamic field names), +the following schema classes are actually just a typing of `Dict`: + +| Schema Type | Implementation | +| ----------- | -------------- | +| Callback | `Callback = Dict[str, PathItem]` | +| Paths | `Paths = Dict[str, PathItem]` | +| Responses | `Responses = Dict[str, Union[Response, Reference]]` | +| SecurityRequirement | `SecurityRequirement = Dict[str, List[str]]` | + +On creating such schema instances, please use python's `dict` type instead to instantiate. diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/__init__.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/__init__.py new file mode 100644 index 000000000000..b61cefc66597 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/__init__.py @@ -0,0 +1,83 @@ +""" +OpenAPI v3.0.3 schema types, created according to the specification: +https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md + +The type orders are according to the contents of the specification: +https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#table-of-contents +""" + +__all__ = [ + "XML", + "Callback", + "Components", + "Contact", + "Discriminator", + "Encoding", + "Example", + "ExternalDocumentation", + "Header", + "Info", + "License", + "Link", + "MediaType", + "OAuthFlow", + "OAuthFlows", + "OpenAPI", + "Operation", + "Parameter", + "PathItem", + "Paths", + "Reference", + "RequestBody", + "Response", + "Responses", + "Schema", + "SecurityRequirement", + "SecurityScheme", + "Server", + "ServerVariable", + "Tag", +] + + +from .callback import Callback +from .components import Components +from .contact import Contact +from .discriminator import Discriminator +from .encoding import Encoding +from .example import Example +from .external_documentation import ExternalDocumentation +from .header import Header +from .info import Info +from .license import License +from .link import Link +from .media_type import MediaType +from .oauth_flow import OAuthFlow +from .oauth_flows import OAuthFlows +from .open_api import OpenAPI +from .operation import Operation +from .parameter import Parameter +from .path_item import PathItem +from .paths import Paths +from .reference import Reference +from .request_body import RequestBody +from .response import Response +from .responses import Responses +from .schema import Schema +from .security_requirement import SecurityRequirement +from .security_scheme import SecurityScheme +from .server import Server +from .server_variable import ServerVariable +from .tag import Tag +from .xml import XML + +PathItem.model_rebuild() +Operation.model_rebuild() +Components.model_rebuild() +Encoding.model_rebuild() +MediaType.model_rebuild() +OpenAPI.model_rebuild() +Parameter.model_rebuild() +Header.model_rebuild() +RequestBody.model_rebuild() +Response.model_rebuild() diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py new file mode 100644 index 000000000000..51fdc454e27c --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py @@ -0,0 +1,15 @@ +from typing import TYPE_CHECKING, Dict + +if TYPE_CHECKING: # pragma: no cover + from .path_item import PathItem +else: + PathItem = "PathItem" + +Callback = Dict[str, PathItem] +""" +A map of possible out-of band callbacks related to the parent operation. +Each value in the map is a [Path Item Object](#pathItemObject) +that describes a set of requests that may be initiated by the API provider and the expected responses. +The key value used to identify the path item object is an expression, evaluated at runtime, +that identifies a URL to use for the callback operation. +""" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py new file mode 100644 index 000000000000..003a04b3b5d5 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py @@ -0,0 +1,103 @@ +from typing import Optional, Union, Dict + +from pydantic import BaseModel, ConfigDict + +from .callback import Callback +from .example import Example +from .header import Header +from .link import Link +from .parameter import Parameter +from .reference import Reference +from .request_body import RequestBody +from .response import Response +from .schema import Schema +from .security_scheme import SecurityScheme + + +class Components(BaseModel): + """ + Holds a set of reusable objects for different aspects of the OAS. + All objects defined within the components object will have no effect on the API + unless they are explicitly referenced from properties outside the components object. + + References: + - https://swagger.io/docs/specification/components/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#componentsObject + """ + + schemas: Optional[Dict[str, Union[Schema, Reference]]] = None + responses: Optional[Dict[str, Union[Response, Reference]]] = None + parameters: Optional[Dict[str, Union[Parameter, Reference]]] = None + examples: Optional[Dict[str, Union[Example, Reference]]] = None + requestBodies: Optional[Dict[str, Union[RequestBody, Reference]]] = None + headers: Optional[Dict[str, Union[Header, Reference]]] = None + securitySchemes: Optional[Dict[str, Union[SecurityScheme, Reference]]] = None + links: Optional[Dict[str, Union[Link, Reference]]] = None + callbacks: Optional[Dict[str, Union[Callback, Reference]]] = None + model_config = ConfigDict( + # `Callback` contains an unresolvable forward reference, will rebuild in `__init__.py`: + defer_build=True, + extra="allow", + json_schema_extra={ + "examples": [ + { + "schemas": { + "GeneralError": { + "type": "object", + "properties": { + "code": {"type": "integer", "format": "int32"}, + "message": {"type": "string"}, + }, + }, + "Category": { + "type": "object", + "properties": {"id": {"type": "integer", "format": "int64"}, "name": {"type": "string"}}, + }, + "Tag": { + "type": "object", + "properties": {"id": {"type": "integer", "format": "int64"}, "name": {"type": "string"}}, + }, + }, + "parameters": { + "skipParam": { + "name": "skip", + "in": "query", + "description": "number of items to skip", + "required": True, + "schema": {"type": "integer", "format": "int32"}, + }, + "limitParam": { + "name": "limit", + "in": "query", + "description": "max records to return", + "required": True, + "schema": {"type": "integer", "format": "int32"}, + }, + }, + "responses": { + "NotFound": {"description": "Entity not found."}, + "IllegalInput": {"description": "Illegal input for operation."}, + "GeneralError": { + "description": "General Error", + "content": {"application/json": {"schema": {"$ref": "#/components/schemas/GeneralError"}}}, + }, + }, + "securitySchemes": { + "api_key": {"type": "apiKey", "name": "api_key", "in": "header"}, + "petstore_auth": { + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "http://example.org/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets", + }, + } + }, + }, + }, + } + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/contact.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/contact.py new file mode 100644 index 000000000000..c04fdbbe0201 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/contact.py @@ -0,0 +1,24 @@ +from typing import Optional + +from pydantic import BaseModel, ConfigDict + + +class Contact(BaseModel): + """ + Contact information for the exposed API. + + See Also: + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#contactObject + """ + + name: Optional[str] = None + url: Optional[str] = None + email: Optional[str] = None + model_config = ConfigDict( + extra="allow", + json_schema_extra={ + "examples": [ + {"name": "API Support", "url": "http://www.example.com/support", "email": "support@example.com"} + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py new file mode 100644 index 000000000000..939271bdeab7 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py @@ -0,0 +1,36 @@ +from typing import Optional, Dict + +from pydantic import BaseModel, ConfigDict + + +class Discriminator(BaseModel): + """ + When request bodies or response payloads may be one of a number of different schemas, + a `discriminator` object can be used to aid in serialization, deserialization, and validation. + + The discriminator is a specific object in a schema which is used to inform the consumer of the specification + of an alternative schema based on the value associated with it. + + When using the discriminator, _inline_ schemas will not be considered. + + References: + - https://swagger.io/docs/specification/data-models/inheritance-and-polymorphism/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#discriminatorObject + """ + + propertyName: str + mapping: Optional[Dict[str, str]] = None + model_config = ConfigDict( + extra="allow", + json_schema_extra={ + "examples": [ + { + "propertyName": "petType", + "mapping": { + "dog": "#/components/schemas/Dog", + "monster": "https://gigantic-server.com/schemas/Monster/schema.json", + }, + } + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py new file mode 100644 index 000000000000..609654f57572 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py @@ -0,0 +1,41 @@ +from typing import TYPE_CHECKING, Optional, Union, Dict + +from pydantic import BaseModel, ConfigDict + +from .reference import Reference + +if TYPE_CHECKING: # pragma: no cover + from .header import Header + + +class Encoding(BaseModel): + """A single encoding definition applied to a single schema property. + + References: + - https://swagger.io/docs/specification/describing-request-body/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#encodingObject + """ + + contentType: Optional[str] = None + headers: Optional[Dict[str, Union["Header", Reference]]] = None + style: Optional[str] = None + explode: bool = False + allowReserved: bool = False + model_config = ConfigDict( + # `Header` is an unresolvable forward reference, will rebuild in `__init__.py`: + defer_build=True, + extra="allow", + json_schema_extra={ + "examples": [ + { + "contentType": "image/png, image/jpeg", + "headers": { + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "schema": {"type": "integer"}, + } + }, + } + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/example.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/example.py new file mode 100644 index 000000000000..90db2530e0b4 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/example.py @@ -0,0 +1,30 @@ +from typing import Any, Optional + +from pydantic import BaseModel, ConfigDict + + +class Example(BaseModel): + """Examples added to parameters / components to help clarify usage. + + References: + - https://swagger.io/docs/specification/adding-examples/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#exampleObject + """ + + summary: Optional[str] = None + description: Optional[str] = None + value: Optional[Any] = None + externalValue: Optional[str] = None + model_config = ConfigDict( + extra="allow", + json_schema_extra={ + "examples": [ + {"summary": "A foo example", "value": {"foo": "bar"}}, + { + "summary": "This is an example in XML", + "externalValue": "http://example.org/examples/address-example.xml", + }, + {"summary": "This is a text example", "externalValue": "http://foo.bar/examples/address-example.txt"}, + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/external_documentation.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/external_documentation.py new file mode 100644 index 000000000000..2c0c39b7cf6f --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/external_documentation.py @@ -0,0 +1,18 @@ +from typing import Optional + +from pydantic import BaseModel, ConfigDict + + +class ExternalDocumentation(BaseModel): + """Allows referencing an external resource for extended documentation. + + References: + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#externalDocumentationObject + """ + + description: Optional[str] = None + url: str + model_config = ConfigDict( + extra="allow", + json_schema_extra={"examples": [{"description": "Find more info here", "url": "https://example.com"}]}, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/header.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/header.py new file mode 100644 index 000000000000..2deb6f3908f1 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/header.py @@ -0,0 +1,33 @@ +from pydantic import ConfigDict, Field + +from ..parameter_location import ParameterLocation +from .parameter import Parameter + + +class Header(Parameter): + """ + The Header Object follows the structure of the [Parameter Object](#parameterObject) with the following changes: + + 1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. + 2. `in` MUST NOT be specified, it is implicitly in `header`. + 3. All traits that are affected by the location MUST be applicable to a location of `header` + (for example, [`style`](#parameterStyle)). + + References: + - https://swagger.io/docs/specification/describing-parameters/#header-parameters + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#headerObject + """ + + name: str = Field(default="") + param_in: ParameterLocation = Field(default=ParameterLocation.HEADER, alias="in") + model_config = ConfigDict( + # `Parameter` is not build yet, will rebuild in `__init__.py`: + defer_build=True, + extra="allow", + populate_by_name=True, + json_schema_extra={ + "examples": [ + {"description": "The number of allowed requests in the current period", "schema": {"type": "integer"}} + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/info.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/info.py new file mode 100644 index 000000000000..bec1354da663 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/info.py @@ -0,0 +1,44 @@ +from typing import Optional + +from pydantic import BaseModel, ConfigDict + +from .contact import Contact +from .license import License + + +class Info(BaseModel): + """ + The object provides metadata about the API. + The metadata MAY be used by the clients if needed, + and MAY be presented in editing or documentation generation tools for convenience. + + References: + - https://swagger.io/docs/specification/api-general-info/ + -https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#infoObject + """ + + title: str + description: Optional[str] = None + termsOfService: Optional[str] = None + contact: Optional[Contact] = None + license: Optional[License] = None + version: str + model_config = ConfigDict( + extra="allow", + json_schema_extra={ + "examples": [ + { + "title": "Sample Pet Store App", + "description": "This is a sample server for a pet store.", + "termsOfService": "http://example.com/terms/", + "contact": { + "name": "API Support", + "url": "http://www.example.com/support", + "email": "support@example.com", + }, + "license": {"name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html"}, + "version": "1.0.1", + } + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/license.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/license.py new file mode 100644 index 000000000000..185eec1dbf39 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/license.py @@ -0,0 +1,21 @@ +from typing import Optional + +from pydantic import BaseModel, ConfigDict + + +class License(BaseModel): + """ + License information for the exposed API. + + References: + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#licenseObject + """ + + name: str + url: Optional[str] = None + model_config = ConfigDict( + extra="allow", + json_schema_extra={ + "examples": [{"name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html"}] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py new file mode 100644 index 000000000000..609ae3ff9032 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py @@ -0,0 +1,43 @@ +from typing import Any, Optional, Dict + +from pydantic import BaseModel, ConfigDict + +from .server import Server + + +class Link(BaseModel): + """ + The `Link object` represents a possible design-time link for a response. + The presence of a link does not guarantee the caller's ability to successfully invoke it, + rather it provides a known relationship and traversal mechanism between responses and other operations. + + Unlike _dynamic_ links (i.e. links provided **in** the response payload), + the OAS linking mechanism does not require link information in the runtime response. + + For computing links, and providing instructions to execute them, + a [runtime expression](#runtimeExpression) is used for accessing values in an operation + and using them as parameters while invoking the linked operation. + + References: + - https://swagger.io/docs/specification/links/ + - https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#linkObject + """ + + operationRef: Optional[str] = None + operationId: Optional[str] = None + parameters: Optional[Dict[str, Any]] = None + requestBody: Optional[Any] = None + description: Optional[str] = None + server: Optional[Server] = None + model_config = ConfigDict( + extra="allow", + json_schema_extra={ + "examples": [ + {"operationId": "getUserAddressByUUID", "parameters": {"userUuid": "$response.body#/uuid"}}, + { + "operationRef": "#/paths/~12.0~1repositories~1{username}/get", + "parameters": {"username": "$response.body#/username"}, + }, + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py new file mode 100644 index 000000000000..aa81247e5f85 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py @@ -0,0 +1,57 @@ +from typing import Any, Optional, Union, Dict + +from pydantic import BaseModel, ConfigDict, Field + +from .encoding import Encoding +from .example import Example +from .reference import Reference +from .schema import Schema + + +class MediaType(BaseModel): + """Each Media Type Object provides schema and examples for the media type identified by its key. + + References: + - https://swagger.io/docs/specification/media-types/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#mediaTypeObject + """ + + media_type_schema: Optional[Union[Reference, Schema]] = Field(default=None, alias="schema") + example: Optional[Any] = None + examples: Optional[Dict[str, Union[Example, Reference]]] = None + encoding: Optional[Dict[str, Encoding]] = None + model_config = ConfigDict( + # `Encoding` is not build yet, will rebuild in `__init__.py`: + defer_build=True, + extra="allow", + populate_by_name=True, + json_schema_extra={ + "examples": [ + { + "schema": {"$ref": "#/components/schemas/Pet"}, + "examples": { + "cat": { + "summary": "An example of a cat", + "value": { + "name": "Fluffy", + "petType": "Cat", + "color": "White", + "gender": "male", + "breed": "Persian", + }, + }, + "dog": { + "summary": "An example of a dog with a cat's name", + "value": { + "name": "Puma", + "petType": "Dog", + "color": "Black", + "gender": "Female", + "breed": "Mixed", + }, + }, + }, + } + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py new file mode 100644 index 000000000000..ea02439b2da0 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py @@ -0,0 +1,34 @@ +from typing import Optional, Dict + +from pydantic import BaseModel, ConfigDict + + +class OAuthFlow(BaseModel): + """ + Configuration details for a supported OAuth Flow + + References: + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oauthFlowObject + - https://swagger.io/docs/specification/authentication/oauth2/ + """ + + authorizationUrl: Optional[str] = None + tokenUrl: Optional[str] = None + refreshUrl: Optional[str] = None + scopes: Dict[str, str] + model_config = ConfigDict( + extra="allow", + json_schema_extra={ + "examples": [ + { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": {"write:pets": "modify pets in your account", "read:pets": "read your pets"}, + }, + { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "tokenUrl": "https://example.com/api/oauth/token", + "scopes": {"write:pets": "modify pets in your account", "read:pets": "read your pets"}, + }, + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flows.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flows.py new file mode 100644 index 000000000000..dba193713699 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flows.py @@ -0,0 +1,21 @@ +from typing import Optional + +from pydantic import BaseModel, ConfigDict + +from .oauth_flow import OAuthFlow + + +class OAuthFlows(BaseModel): + """ + Allows configuration of the supported OAuth Flows. + + References: + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oauthFlowsObject + - https://swagger.io/docs/specification/authentication/oauth2/ + """ + + implicit: Optional[OAuthFlow] = None + password: Optional[OAuthFlow] = None + clientCredentials: Optional[OAuthFlow] = None + authorizationCode: Optional[OAuthFlow] = None + model_config = ConfigDict(extra="allow") diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py new file mode 100644 index 000000000000..818e9ebf3214 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py @@ -0,0 +1,49 @@ +from typing import Optional, List + +from pydantic import BaseModel, ConfigDict, field_validator + +from .components import Components +from .external_documentation import ExternalDocumentation +from .info import Info +from .paths import Paths +from .security_requirement import SecurityRequirement +from .server import Server +from .tag import Tag + +NUM_SEMVER_PARTS = 3 + + +class OpenAPI(BaseModel): + """This is the root document object of the OpenAPI document. + + References: + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oasObject + - https://swagger.io/docs/specification/basic-structure/ + """ + + info: Info + servers: List[Server] = [Server(url="/")] + paths: Paths + components: Optional[Components] = None + security: Optional[List[SecurityRequirement]] = None + tags: Optional[List[Tag]] = None + externalDocs: Optional[ExternalDocumentation] = None + openapi: str + model_config = ConfigDict( + # `Components` is not build yet, will rebuild in `__init__.py`: + defer_build=True, + extra="allow", + ) + + @field_validator("openapi") + @classmethod + def check_openapi_version(cls, value: str) -> str: + """Validates that the declared OpenAPI version is a supported one""" + parts = value.split(".") + if len(parts) != NUM_SEMVER_PARTS: + raise ValueError(f"Invalid OpenAPI version {value}") + if parts[0] != "3": + raise ValueError(f"Only OpenAPI versions 3.* are supported, got {value}") + if int(parts[1]) > 1: + raise ValueError(f"Only OpenAPI versions 3.1.* are supported, got {value}") + return value diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py new file mode 100644 index 000000000000..e2d2924e0b13 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py @@ -0,0 +1,89 @@ +from typing import Optional, Union, List, Dict + +from pydantic import BaseModel, ConfigDict, Field + +from .callback import Callback +from .external_documentation import ExternalDocumentation +from .parameter import Parameter +from .reference import Reference +from .request_body import RequestBody +from .responses import Responses +from .security_requirement import SecurityRequirement +from .server import Server + + +class Operation(BaseModel): + """Describes a single API operation on a path. + + References: + - https://swagger.io/docs/specification/paths-and-operations/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operationObject + """ + + tags: Optional[List[str]] = None + summary: Optional[str] = None + description: Optional[str] = None + externalDocs: Optional[ExternalDocumentation] = None + operationId: Optional[str] = None + parameters: Optional[List[Union[Parameter, Reference]]] = None + request_body: Optional[Union[RequestBody, Reference]] = Field(None, alias="requestBody") + responses: Responses + callbacks: Optional[Dict[str, Callback]] = None + + deprecated: bool = False + security: Optional[List[SecurityRequirement]] = None + servers: Optional[List[Server]] = None + model_config = ConfigDict( + # `Callback` contains an unresolvable forward reference, will rebuild in `__init__.py`: + defer_build=True, + extra="allow", + json_schema_extra={ + "examples": [ + { + "tags": ["pet"], + "summary": "Updates a pet in the store with form data", + "operationId": "updatePetWithForm", + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": True, + "schema": {"type": "string"}, + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "Updated name of the pet", + "type": "string", + }, + "status": { + "description": "Updated status of the pet", + "type": "string", + }, + }, + "required": ["status"], + } + } + } + }, + "responses": { + "200": { + "description": "Pet updated.", + "content": {"application/json": {}, "application/xml": {}}, + }, + "405": { + "description": "Method Not Allowed", + "content": {"application/json": {}, "application/xml": {}}, + }, + }, + "security": [{"petstore_auth": ["write:pets", "read:pets"]}], + } + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py new file mode 100644 index 000000000000..981f7b375136 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py @@ -0,0 +1,89 @@ +from typing import Any, Optional, Union, Dict + +from pydantic import BaseModel, ConfigDict, Field + +from ..parameter_location import ParameterLocation +from .example import Example +from .media_type import MediaType +from .reference import Reference +from .schema import Schema + + +class Parameter(BaseModel): + """ + Describes a single operation parameter. + + A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). + + References: + - https://swagger.io/docs/specification/describing-parameters/ + - https://swagger.io/docs/specification/serialization/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameterObject + """ + + name: str + param_in: ParameterLocation = Field(alias="in") + description: Optional[str] = None + required: bool = False + deprecated: bool = False + allowEmptyValue: bool = False + style: Optional[str] = None + explode: bool = False + allowReserved: bool = False + param_schema: Optional[Union[Reference, Schema]] = Field(default=None, alias="schema") + example: Optional[Any] = None + examples: Optional[Dict[str, Union[Example, Reference]]] = None + content: Optional[Dict[str, MediaType]] = None + model_config = ConfigDict( + # `MediaType` is not build yet, will rebuild in `__init__.py`: + defer_build=True, + extra="allow", + populate_by_name=True, + json_schema_extra={ + "examples": [ + { + "name": "token", + "in": "header", + "description": "token to be passed as a header", + "required": True, + "schema": {"type": "array", "items": {"type": "integer", "format": "int64"}}, + "style": "simple", + }, + { + "name": "username", + "in": "path", + "description": "username to fetch", + "required": True, + "schema": {"type": "string"}, + }, + { + "name": "id", + "in": "query", + "description": "ID of the object to fetch", + "required": False, + "schema": {"type": "array", "items": {"type": "string"}}, + "style": "form", + "explode": True, + }, + { + "in": "query", + "name": "freeForm", + "schema": {"type": "object", "additionalProperties": {"type": "integer"}}, + "style": "form", + }, + { + "in": "query", + "name": "coordinates", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["lat", "long"], + "properties": {"lat": {"type": "number"}, "long": {"type": "number"}}, + } + } + }, + }, + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py new file mode 100644 index 000000000000..7dd06a3fcae2 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py @@ -0,0 +1,76 @@ +from typing import TYPE_CHECKING, Optional, Union, List + +from pydantic import BaseModel, ConfigDict, Field + +from .parameter import Parameter +from .reference import Reference +from .server import Server + +if TYPE_CHECKING: + from .operation import Operation # pragma: no cover + + +class PathItem(BaseModel): + """ + Describes the operations available on a single path. + A Path Item MAY be empty, due to [ACL constraints](#securityFiltering). + The path itself is still exposed to the documentation viewer + but they will not know which operations and parameters are available. + + References: + - https://swagger.io/docs/specification/paths-and-operations/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#pathItemObject + """ + + ref: Optional[str] = Field(default=None, alias="$ref") + summary: Optional[str] = None + description: Optional[str] = None + get: Optional["Operation"] = None + put: Optional["Operation"] = None + post: Optional["Operation"] = None + delete: Optional["Operation"] = None + options: Optional["Operation"] = None + head: Optional["Operation"] = None + patch: Optional["Operation"] = None + trace: Optional["Operation"] = None + servers: Optional[List[Server]] = None + parameters: Optional[List[Union[Parameter, Reference]]] = None + model_config = ConfigDict( + # `Operation` is an unresolvable forward reference, will rebuild in `__init__.py`: + defer_build=True, + extra="allow", + populate_by_name=True, + json_schema_extra={ + "examples": [ + { + "get": { + "description": "Returns pets based on ID", + "summary": "Find pets by ID", + "operationId": "getPetsById", + "responses": { + "200": { + "description": "pet response", + "content": { + "*/*": {"schema": {"type": "array", "items": {"$ref": "#/components/schemas/Pet"}}} + }, + }, + "default": { + "description": "error payload", + "content": {"text/html": {"schema": {"$ref": "#/components/schemas/ErrorModel"}}}, + }, + }, + }, + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to use", + "required": True, + "schema": {"type": "array", "items": {"type": "string"}}, + "style": "simple", + } + ], + } + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py new file mode 100644 index 000000000000..d8861238305f --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py @@ -0,0 +1,14 @@ +from .path_item import PathItem +from typing import Dict + +Paths = Dict[str, PathItem] +""" +Holds the relative paths to the individual endpoints and their operations. +The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. + +The Paths MAY be empty, due to [ACL constraints](#securityFiltering). + +References: + - https://swagger.io/docs/specification/paths-and-operations/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#pathsObject +""" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/reference.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/reference.py new file mode 100644 index 000000000000..50d26064f88c --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/reference.py @@ -0,0 +1,26 @@ +from pydantic import BaseModel, ConfigDict, Field + + +class Reference(BaseModel): + """ + A simple object to allow referencing other components in the specification, internally and externally. + + The Reference Object is defined by [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) + and follows the same structure, behavior and rules. + + For this specification, reference resolution is accomplished as defined by the JSON Reference specification + and not by the JSON Schema specification. + + References: + - https://swagger.io/docs/specification/using-ref/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#referenceObject + """ + + ref: str = Field(alias="$ref") + model_config = ConfigDict( + extra="allow", + populate_by_name=True, + json_schema_extra={ + "examples": [{"$ref": "#/components/schemas/Pet"}, {"$ref": "Pet.json"}, {"$ref": "definitions.json#/Pet"}] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py new file mode 100644 index 000000000000..b1464e47e1dd --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py @@ -0,0 +1,70 @@ +from typing import Optional, Dict + +from pydantic import BaseModel, ConfigDict + +from .media_type import MediaType + + +class RequestBody(BaseModel): + """Describes a single request body. + + References: + - https://swagger.io/docs/specification/describing-request-body/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#requestBodyObject + """ + + description: Optional[str] = None + content: Dict[str, MediaType] + required: bool = False + model_config = ConfigDict( + # `MediaType` is not build yet, will rebuild in `__init__.py`: + defer_build=True, + extra="allow", + json_schema_extra={ + "examples": [ + { + "description": "user to add to the system", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"}, + "examples": { + "user": { + "summary": "User Example", + "externalValue": "http://foo.bar/examples/user-example.json", + } + }, + }, + "application/xml": { + "schema": {"$ref": "#/components/schemas/User"}, + "examples": { + "user": { + "summary": "User example in XML", + "externalValue": "http://foo.bar/examples/user-example.xml", + } + }, + }, + "text/plain": { + "examples": { + "user": { + "summary": "User example in Plain text", + "externalValue": "http://foo.bar/examples/user-example.txt", + } + } + }, + "*/*": { + "examples": { + "user": { + "summary": "User example in other format", + "externalValue": "http://foo.bar/examples/user-example.whatever", + } + } + }, + }, + }, + { + "description": "user to add to the system", + "content": {"text/plain": {"schema": {"type": "array", "items": {"type": "string"}}}}, + }, + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py new file mode 100644 index 000000000000..bb20fad84d8e --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py @@ -0,0 +1,61 @@ +from typing import Optional, Union, Dict + +from pydantic import BaseModel, ConfigDict + +from .header import Header +from .link import Link +from .media_type import MediaType +from .reference import Reference + + +class Response(BaseModel): + """ + Describes a single response from an API Operation, including design-time, + static `links` to operations based on the response. + + References: + - https://swagger.io/docs/specification/describing-responses/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#responseObject + """ + + description: str + headers: Optional[Dict[str, Union[Header, Reference]]] = None + content: Optional[Dict[str, MediaType]] = None + links: Optional[Dict[str, Union[Link, Reference]]] = None + model_config = ConfigDict( + # `MediaType` is not build yet, will rebuild in `__init__.py`: + defer_build=True, + extra="allow", + json_schema_extra={ + "examples": [ + { + "description": "A complex object array response", + "content": { + "application/json": { + "schema": {"type": "array", "items": {"$ref": "#/components/schemas/VeryComplexType"}} + } + }, + }, + {"description": "A simple string response", "content": {"text/plain": {"schema": {"type": "string"}}}}, + { + "description": "A simple string response", + "content": {"text/plain": {"schema": {"type": "string", "example": "whoa!"}}}, + "headers": { + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "schema": {"type": "integer"}, + }, + "X-Rate-Limit-Remaining": { + "description": "The number of remaining requests in the current period", + "schema": {"type": "integer"}, + }, + "X-Rate-Limit-Reset": { + "description": "The number of seconds left in the current period", + "schema": {"type": "integer"}, + }, + }, + }, + {"description": "object created"}, + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py new file mode 100644 index 000000000000..719e772e62e4 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py @@ -0,0 +1,23 @@ +from typing import Union, Dict + +from .reference import Reference +from .response import Response + +Responses = Dict[str, Union[Response, Reference]] +""" +A container for the expected responses of an operation. +The container maps a HTTP response code to the expected response. + +The documentation is not necessarily expected to cover all possible HTTP response codes +because they may not be known in advance. +However, documentation is expected to cover a successful operation response and any known errors. + +The `default` MAY be used as a default response object for all HTTP codes +that are not covered individually by the specification. + +The `Responses Object` MUST contain at least one response code, and it +SHOULD be the response for a successful operation call. + +References: + - https://swagger.io/docs/specification/describing-responses/ +""" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py new file mode 100644 index 000000000000..30e4d18e52dd --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py @@ -0,0 +1,208 @@ +from typing import Any, Optional, Union, List, Dict + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr, model_validator + +from ..data_type import DataType +from .discriminator import Discriminator +from .external_documentation import ExternalDocumentation +from .reference import Reference +from .xml import XML + + +class Schema(BaseModel): + """ + The Schema Object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + This object is an extended subset of the [JSON Schema Specification Wright Draft 00](https://json-schema.org/). + + References: + - https://swagger.io/docs/specification/data-models/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schemaObject + """ + + title: Optional[str] = None + multipleOf: Optional[float] = Field(default=None, gt=0.0) + maximum: Optional[float] = None + exclusiveMaximum: Optional[Union[bool, float]] = None + minimum: Optional[float] = None + exclusiveMinimum: Optional[Union[bool, float]] = None + maxLength: Optional[int] = Field(default=None, ge=0) + minLength: Optional[int] = Field(default=None, ge=0) + pattern: Optional[str] = None + maxItems: Optional[int] = Field(default=None, ge=0) + minItems: Optional[int] = Field(default=None, ge=0) + uniqueItems: Optional[bool] = None + maxProperties: Optional[int] = Field(default=None, ge=0) + minProperties: Optional[int] = Field(default=None, ge=0) + required: Optional[List[str]] = Field(default=None) + enum: Union[None, List[Any]] = Field(default=None, min_length=1) + const: Union[None, StrictStr, StrictInt, StrictFloat, StrictBool] = None + type: Union[DataType, List[DataType], None] = Field(default=None) + allOf: List[Union[Reference, "Schema"]] = Field(default_factory=list) + oneOf: List[Union[Reference, "Schema"]] = Field(default_factory=list) + anyOf: List[Union[Reference, "Schema"]] = Field(default_factory=list) + schema_not: Optional[Union[Reference, "Schema"]] = Field(default=None, alias="not") + items: Optional[Union[Reference, "Schema"]] = None + prefixItems: List[Union[Reference, "Schema"]] = Field(default_factory=list) + properties: Optional[Dict[str, Union[Reference, "Schema"]]] = None + additionalProperties: Optional[Union[bool, Reference, "Schema"]] = None + description: Optional[str] = None + schema_format: Optional[str] = Field(default=None, alias="format") + default: Optional[Any] = None + nullable: bool = Field(default=False) + discriminator: Optional[Discriminator] = None + readOnly: Optional[bool] = None + writeOnly: Optional[bool] = None + xml: Optional[XML] = None + externalDocs: Optional[ExternalDocumentation] = None + example: Optional[Any] = None + deprecated: Optional[bool] = None + model_config = ConfigDict( + extra="allow", + populate_by_name=True, + json_schema_extra={ + "examples": [ + {"type": "string", "format": "email"}, + { + "type": "object", + "required": ["name"], + "properties": { + "name": {"type": "string"}, + "address": {"$ref": "#/components/schemas/Address"}, + "age": {"type": "integer", "format": "int32", "minimum": 0}, + }, + }, + {"type": "object", "additionalProperties": {"type": "string"}}, + { + "type": "object", + "additionalProperties": {"$ref": "#/components/schemas/ComplexModel"}, + }, + { + "type": "object", + "properties": { + "id": {"type": "integer", "format": "int64"}, + "name": {"type": "string"}, + }, + "required": ["name"], + "example": {"name": "Puma", "id": 1}, + }, + { + "type": "object", + "required": ["message", "code"], + "properties": { + "message": {"type": "string"}, + "code": {"type": "integer", "minimum": 100, "maximum": 600}, + }, + }, + { + "allOf": [ + {"$ref": "#/components/schemas/ErrorModel"}, + { + "type": "object", + "required": ["rootCause"], + "properties": {"rootCause": {"type": "string"}}, + }, + ] + }, + { + "type": "object", + "discriminator": {"propertyName": "petType"}, + "properties": { + "name": {"type": "string"}, + "petType": {"type": "string"}, + }, + "required": ["name", "petType"], + }, + { + "description": "A representation of a cat. " + "Note that `Cat` will be used as the discriminator value.", + "allOf": [ + {"$ref": "#/components/schemas/Pet"}, + { + "type": "object", + "properties": { + "huntingSkill": { + "type": "string", + "description": "The measured skill for hunting", + "default": "lazy", + "enum": [ + "clueless", + "lazy", + "adventurous", + "aggressive", + ], + } + }, + "required": ["huntingSkill"], + }, + ], + }, + { + "description": "A representation of a dog. " + "Note that `Dog` will be used as the discriminator value.", + "allOf": [ + {"$ref": "#/components/schemas/Pet"}, + { + "type": "object", + "properties": { + "packSize": { + "type": "integer", + "format": "int32", + "description": "the size of the pack the dog is from", + "default": 0, + "minimum": 0, + } + }, + "required": ["packSize"], + }, + ], + }, + ] + }, + ) + + @model_validator(mode="after") + def handle_exclusive_min_max(self) -> "Schema": + """ + Convert exclusiveMinimum/exclusiveMaximum between OpenAPI v3.0 (bool) and v3.1 (numeric). + """ + # Handle exclusiveMinimum + if isinstance(self.exclusiveMinimum, bool) and self.minimum is not None: + if self.exclusiveMinimum: + self.exclusiveMinimum = self.minimum + self.minimum = None + else: + self.exclusiveMinimum = None + elif isinstance(self.exclusiveMinimum, float): + self.minimum = None + + # Handle exclusiveMaximum + if isinstance(self.exclusiveMaximum, bool) and self.maximum is not None: + if self.exclusiveMaximum: + self.exclusiveMaximum = self.maximum + self.maximum = None + else: + self.exclusiveMaximum = None + elif isinstance(self.exclusiveMaximum, float): + self.maximum = None + + return self + + @model_validator(mode="after") + def handle_nullable(self) -> "Schema": + """Convert the old 3.0 `nullable` property into the new 3.1 style""" + if not self.nullable: + return self + if isinstance(self.type, str): + self.type = [self.type, DataType.NULL] + elif isinstance(self.type, list): + if DataType.NULL not in self.type: + self.type.append(DataType.NULL) + elif len(self.oneOf) > 0: + self.oneOf.append(Schema(type=DataType.NULL)) + elif len(self.anyOf) > 0: + self.anyOf.append(Schema(type=DataType.NULL)) + elif len(self.allOf) > 0: # Nullable allOf is basically oneOf[null, allOf] + self.oneOf = [Schema(type=DataType.NULL), Schema(allOf=self.allOf)] + self.allOf = [] + return self diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py new file mode 100644 index 000000000000..04fe5fe31239 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py @@ -0,0 +1,20 @@ +from typing import Dict, List + +SecurityRequirement = Dict[str, List[str]] +""" +Lists the required security schemes to execute this operation. +The name used for each property MUST correspond to a security scheme declared in the +[Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). + +Security Requirement Objects that contain multiple schemes require that +all schemes MUST be satisfied for a request to be authorized. +This enables support for scenarios where multiple query parameters or HTTP headers +are required to convey security information. + +When a list of Security Requirement Objects is defined on the +[OpenAPI Object](#oasObject) or [Operation Object](#operationObject), +only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. + +References: + - https://swagger.io/docs/specification/authentication/ +""" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_scheme.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_scheme.py new file mode 100644 index 000000000000..df385440c6ea --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_scheme.py @@ -0,0 +1,49 @@ +from typing import Optional + +from pydantic import BaseModel, ConfigDict, Field + +from .oauth_flows import OAuthFlows + + +class SecurityScheme(BaseModel): + """ + Defines a security scheme that can be used by the operations. + Supported schemes are HTTP authentication, + an API key (either as a header, a cookie parameter or as a query parameter), + OAuth2's common flows (implicit, password, client credentials and authorization code) + as defined in [RFC6749](https://tools.ietf.org/html/rfc6749), + and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06). + + References: + - https://swagger.io/docs/specification/authentication/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#componentsObject + """ + + type: str + description: Optional[str] = None + name: Optional[str] = None + security_scheme_in: Optional[str] = Field(default=None, alias="in") + scheme: Optional[str] = None + bearerFormat: Optional[str] = None + flows: Optional[OAuthFlows] = None + openIdConnectUrl: Optional[str] = None + model_config = ConfigDict( + extra="allow", + populate_by_name=True, + json_schema_extra={ + "examples": [ + {"type": "http", "scheme": "basic"}, + {"type": "apiKey", "name": "api_key", "in": "header"}, + {"type": "http", "scheme": "bearer", "bearerFormat": "JWT"}, + { + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": {"write:pets": "modify pets in your account", "read:pets": "read your pets"}, + } + }, + }, + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py new file mode 100644 index 000000000000..17d1cf39f7cf --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py @@ -0,0 +1,39 @@ +from typing import Optional, Dict + +from pydantic import BaseModel, ConfigDict + +from .server_variable import ServerVariable + + +class Server(BaseModel): + """An object representing a Server. + + References: + - https://swagger.io/docs/specification/api-host-and-base-path/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#serverObject + """ + + url: str + description: Optional[str] = None + variables: Optional[Dict[str, ServerVariable]] = None + model_config = ConfigDict( + extra="allow", + json_schema_extra={ + "examples": [ + {"url": "https://development.gigantic-server.com/v1", "description": "Development server"}, + { + "url": "https://{username}.gigantic-server.com:{port}/{basePath}", + "description": "The production API server", + "variables": { + "username": { + "default": "demo", + "description": "this value is assigned by the service provider, " + "in this example `gigantic-server.com`", + }, + "port": {"enum": ["8443", "443"], "default": "8443"}, + "basePath": {"default": "v2"}, + }, + }, + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py new file mode 100644 index 000000000000..2bbcba461dcd --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py @@ -0,0 +1,17 @@ +from typing import Optional, List + +from pydantic import BaseModel, ConfigDict + + +class ServerVariable(BaseModel): + """An object representing a Server Variable for server URL template substitution. + + References: + - https://swagger.io/docs/specification/api-host-and-base-path/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#serverVariableObject + """ + + enum: Optional[List[str]] = None + default: str + description: Optional[str] = None + model_config = ConfigDict(extra="allow") diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/tag.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/tag.py new file mode 100644 index 000000000000..acb5fdc288df --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/tag.py @@ -0,0 +1,23 @@ +from typing import Optional + +from pydantic import BaseModel, ConfigDict + +from .external_documentation import ExternalDocumentation + + +class Tag(BaseModel): + """ + Adds metadata to a single tag that is used by the [Operation Object](#operationObject). + It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. + + References: + - https://swagger.io/docs/specification/paths-and-operations/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#tagObject + """ + + name: str + description: Optional[str] = None + externalDocs: Optional[ExternalDocumentation] = None + model_config = ConfigDict( + extra="allow", json_schema_extra={"examples": [{"name": "pet", "description": "Pets operations"}]} + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/xml.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/xml.py new file mode 100644 index 000000000000..986aa44f43a7 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/xml.py @@ -0,0 +1,32 @@ +from typing import Optional + +from pydantic import BaseModel, ConfigDict + + +class XML(BaseModel): + """ + A metadata object that allows for more fine-tuned XML model definitions. + + When using arrays, XML element names are *not* inferred (for singular/plural forms) + and the `name` property SHOULD be used to add that information. + See examples for expected behavior. + + References: + - https://swagger.io/docs/specification/data-models/representing-xml/ + - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#xmlObject + """ + + name: Optional[str] = None + namespace: Optional[str] = None + prefix: Optional[str] = None + attribute: bool = False + wrapped: bool = False + model_config = ConfigDict( + extra="allow", + json_schema_extra={ + "examples": [ + {"namespace": "http://example.com/schema/sample", "prefix": "sample"}, + {"name": "aliens", "wrapped": True}, + ] + }, + ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/parameter_location.py b/chaotic-openapi/chaotic_openapi/front/schema/parameter_location.py new file mode 100644 index 000000000000..162a7cb131ca --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/schema/parameter_location.py @@ -0,0 +1,25 @@ +# Python 3.11 has StrEnum but breaks the old `str, Enum` hack. +# Unless this gets fixed, we need to have two implementations :( +import sys + +if sys.version_info >= (3, 11): + from enum import StrEnum + + class ParameterLocation(StrEnum): + """The places Parameters can be put when calling an Endpoint""" + + QUERY = "query" + PATH = "path" + HEADER = "header" + COOKIE = "cookie" + +else: + from enum import Enum + + class ParameterLocation(str, Enum): + """The places Parameters can be put when calling an Endpoint""" + + QUERY = "query" + PATH = "path" + HEADER = "header" + COOKIE = "cookie" diff --git a/chaotic-openapi/chaotic_openapi/front/utils.py b/chaotic-openapi/chaotic_openapi/front/utils.py new file mode 100644 index 000000000000..8429af035176 --- /dev/null +++ b/chaotic-openapi/chaotic_openapi/front/utils.py @@ -0,0 +1,122 @@ +from __future__ import annotations + +import builtins +import re +from email.message import Message +from keyword import iskeyword +from typing import Any + +from .config import Config + +DELIMITERS = r"\. _-" + + +class PythonIdentifier(str): + """A snake_case string which has been validated / transformed into a valid identifier for Python""" + + def __new__(cls, value: str, prefix: str, skip_snake_case: bool = False) -> PythonIdentifier: + new_value = sanitize(value) + if not skip_snake_case: + new_value = snake_case(new_value) + new_value = fix_reserved_words(new_value) + + if not new_value.isidentifier() or value.startswith("_"): + new_value = f"{prefix}{new_value}" + return str.__new__(cls, new_value) + + def __deepcopy__(self, _: Any) -> PythonIdentifier: + return self + + +class ClassName(str): + """A PascalCase string which has been validated / transformed into a valid class name for Python""" + + def __new__(cls, value: str, prefix: str) -> ClassName: + new_value = fix_reserved_words(pascal_case(sanitize(value))) + + if not new_value.isidentifier(): + value = f"{prefix}{new_value}" + new_value = fix_reserved_words(pascal_case(sanitize(value))) + return str.__new__(cls, new_value) + + def __deepcopy__(self, _: Any) -> ClassName: + return self + + +def sanitize(value: str) -> str: + """Removes every character that isn't 0-9, A-Z, a-z, or a known delimiter""" + return re.sub(rf"[^\w{DELIMITERS}]+", "", value) + + +def split_words(value: str) -> List[str]: + """Split a string on words and known delimiters""" + # We can't guess words if there is no capital letter + if any(c.isupper() for c in value): + value = " ".join(re.split("([A-Z]?[a-z]+)", value)) + return re.findall(rf"[^{DELIMITERS}]+", value) + + +RESERVED_WORDS = (set(dir(builtins)) | {"self", "true", "false", "datetime"}) - { + "id", +} + + +def fix_reserved_words(value: str) -> str: + """ + Using reserved Python words as identifiers in generated code causes problems, so this function renames them. + + Args: + value: The identifier to-be that should be renamed if it's a reserved word. + + Returns: + `value` suffixed with `_` if it was a reserved word. + """ + if value in RESERVED_WORDS or iskeyword(value): + return f"{value}_" + return value + + +def snake_case(value: str) -> str: + """Converts to snake_case""" + words = split_words(sanitize(value)) + return "_".join(words).lower() + + +def pascal_case(value: str) -> str: + """Converts to PascalCase""" + words = split_words(sanitize(value)) + capitalized_words = (word.capitalize() if not word.isupper() else word for word in words) + return "".join(capitalized_words) + + +def kebab_case(value: str) -> str: + """Converts to kebab-case""" + words = split_words(sanitize(value)) + return "-".join(words).lower() + + +def remove_string_escapes(value: str) -> str: + """Used when parsing string-literal defaults to prevent escaping the string to write arbitrary Python + + **REMOVING OR CHANGING THE USAGE OF THIS FUNCTION HAS SECURITY IMPLICATIONS** + + See Also: + - https://github.com/openapi-generators/openapi-python-client/security/advisories/GHSA-9x4c-63pf-525f + """ + return value.replace('"', r"\"") + + +def get_content_type(content_type: str, config: Config) -> str | None: + """ + Given a string representing a content type with optional parameters, returns the content type only + """ + content_type = config.content_type_overrides.get(content_type, content_type) + message = Message() + message.add_header("Content-Type", content_type) + + parsed_content_type = message.get_content_type() + if not content_type.startswith(parsed_content_type): + # Always defaults to `text/plain` if it's not recognized. We want to return an error, not default. + return None + + return parsed_content_type From 2f712579062f85c6f874c52bde11cd59960484b9 Mon Sep 17 00:00:00 2001 From: Artem Khromov Date: Mon, 13 Jan 2025 02:42:15 +0300 Subject: [PATCH 2/5] Better --- .../chaotic_openapi/{_parser.py => alo.py} | 5 +- .../chaotic_openapi/front/__init__.py | 6 +- .../chaotic_openapi/front/parser/bodies.py | 12 ++-- .../chaotic_openapi/front/parser/openapi.py | 64 +++++++++---------- .../front/parser/properties/__init__.py | 32 +++++----- .../front/parser/properties/boolean.py | 2 +- .../front/parser/properties/const.py | 2 +- .../front/parser/properties/date.py | 2 +- .../front/parser/properties/datetime.py | 2 +- .../front/parser/properties/enum_property.py | 14 ++-- .../front/parser/properties/file.py | 2 +- .../front/parser/properties/float.py | 2 +- .../front/parser/properties/int.py | 2 +- .../front/parser/properties/list_property.py | 14 ++-- .../properties/literal_enum_property.py | 12 ++-- .../parser/properties/merge_properties.py | 8 +-- .../front/parser/properties/model_property.py | 60 ++++++++--------- .../front/parser/properties/none.py | 2 +- .../front/parser/properties/protocol.py | 8 +-- .../front/parser/properties/schemas.py | 22 +++---- .../front/parser/properties/string.py | 2 +- .../front/parser/properties/union.py | 18 +++--- .../front/parser/properties/uuid.py | 4 +- .../chaotic_openapi/front/parser/responses.py | 6 +- .../schema/openapi_schema_pydantic/README.md | 8 +-- .../openapi_schema_pydantic/callback.py | 4 +- .../openapi_schema_pydantic/components.py | 20 +++--- .../openapi_schema_pydantic/discriminator.py | 4 +- .../openapi_schema_pydantic/encoding.py | 4 +- .../schema/openapi_schema_pydantic/link.py | 4 +- .../openapi_schema_pydantic/media_type.py | 6 +- .../openapi_schema_pydantic/oauth_flow.py | 4 +- .../openapi_schema_pydantic/open_api.py | 8 +-- .../openapi_schema_pydantic/operation.py | 12 ++-- .../openapi_schema_pydantic/parameter.py | 6 +- .../openapi_schema_pydantic/path_item.py | 6 +- .../schema/openapi_schema_pydantic/paths.py | 3 +- .../openapi_schema_pydantic/request_body.py | 4 +- .../openapi_schema_pydantic/response.py | 8 +-- .../openapi_schema_pydantic/responses.py | 4 +- .../schema/openapi_schema_pydantic/schema.py | 18 +++--- .../security_requirement.py | 4 +- .../schema/openapi_schema_pydantic/server.py | 4 +- .../server_variable.py | 4 +- .../chaotic_openapi/{front => }/opa.yaml | 0 45 files changed, 218 insertions(+), 220 deletions(-) rename chaotic-openapi/chaotic_openapi/{_parser.py => alo.py} (68%) rename chaotic-openapi/chaotic_openapi/{front => }/opa.yaml (100%) diff --git a/chaotic-openapi/chaotic_openapi/_parser.py b/chaotic-openapi/chaotic_openapi/alo.py similarity index 68% rename from chaotic-openapi/chaotic_openapi/_parser.py rename to chaotic-openapi/chaotic_openapi/alo.py index 66828ccedf2c..cc8c99c504cd 100644 --- a/chaotic-openapi/chaotic_openapi/_parser.py +++ b/chaotic-openapi/chaotic_openapi/alo.py @@ -1,5 +1,5 @@ from typing import Any, Union, Dict -from front.parser import GeneratorData +from front.parser.openapi import GeneratorData from front.config import Config, ConfigFile, MetaType from pathlib import Path @@ -13,4 +13,5 @@ def config(): conf = config() -print(parse(_get_document(conf.document_source), conf)) +# print(_get_document(source=conf.document_source, timeout=10)) +print(parse(_get_document(source=conf.document_source, timeout=10), conf)) diff --git a/chaotic-openapi/chaotic_openapi/front/__init__.py b/chaotic-openapi/chaotic_openapi/front/__init__.py index 3823906156a3..411caaa2d2a8 100644 --- a/chaotic-openapi/chaotic_openapi/front/__init__.py +++ b/chaotic-openapi/chaotic_openapi/front/__init__.py @@ -16,14 +16,14 @@ from ruamel.yaml import YAML from ruamel.yaml.error import YAMLError -from openapi_python_client import utils +from . import utils -from .config import Config, MetaType +from .config import Config, ConfigFile, MetaType from .parser import GeneratorData, import_string_from_class from .parser.errors import ErrorLevel, GeneratorError from .parser.properties import LiteralEnumProperty -__version__ = version(__package__) +# __version__ = version(__package__) TEMPLATE_FILTERS = { diff --git a/chaotic-openapi/chaotic_openapi/front/parser/bodies.py b/chaotic-openapi/chaotic_openapi/front/parser/bodies.py index bf4c05c4da07..514b6f0f7cd8 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/bodies.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/bodies.py @@ -1,9 +1,9 @@ import sys -from typing import Union, Dict, List, Tuple +from typing import Union import attr -from openapi_python_client.parser.properties import ( +from .properties import ( ModelProperty, Property, Schemas, @@ -44,10 +44,10 @@ def body_from_data( *, data: oai.Operation, schemas: Schemas, - request_bodies: Dict[str, Union[oai.RequestBody, oai.Reference]], + request_bodies: dict[str, Union[oai.RequestBody, oai.Reference]], config: Config, endpoint_name: str, -) -> Tuple[List[Union[Body, ParseError]], Schemas]: +) -> tuple[list[Union[Body, ParseError]], Schemas]: """Adds form or JSON body to Endpoint if included in data""" body = _resolve_reference(data.request_body, request_bodies) if isinstance(body, ParseError): @@ -55,7 +55,7 @@ def body_from_data( if body is None: return [], schemas - bodies: List[Union[Body, ParseError]] = [] + bodies: list[Union[Body, ParseError]] = [] body_content = body.content prefix_type_names = len(body_content) > 1 @@ -131,7 +131,7 @@ def body_from_data( def _resolve_reference( - body: Union[oai.RequestBody, oai.Reference, None], request_bodies: Dict[str, Union[oai.RequestBody, oai.Reference]] + body: Union[oai.RequestBody, oai.Reference, None], request_bodies: dict[str, Union[oai.RequestBody, oai.Reference]] ) -> Union[oai.RequestBody, ParseError, None]: if body is None: return None diff --git a/chaotic-openapi/chaotic_openapi/front/parser/openapi.py b/chaotic-openapi/chaotic_openapi/front/parser/openapi.py index cd3056eb6930..117b2ee30c5a 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/openapi.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/openapi.py @@ -1,9 +1,9 @@ import re -from typing import Iterator +from collections.abc import Iterator from copy import deepcopy from dataclasses import dataclass, field from http import HTTPStatus -from typing import Any, Optional, Protocol, Union, List, Dict, Tuple, Set +from typing import Any, Optional, Protocol, Union from pydantic import ValidationError @@ -41,20 +41,20 @@ class EndpointCollection: """A bunch of endpoints grouped under a tag that will become a module""" tag: str - endpoints: List["Endpoint"] = field(default_factory=list) - parse_errors: List[ParseError] = field(default_factory=list) + endpoints: list["Endpoint"] = field(default_factory=list) + parse_errors: list[ParseError] = field(default_factory=list) @staticmethod def from_data( *, - data: Dict[str, oai.PathItem], + data: dict[str, oai.PathItem], schemas: Schemas, parameters: Parameters, - request_bodies: Dict[str, Union[oai.RequestBody, oai.Reference]], + request_bodies: dict[str, Union[oai.RequestBody, oai.Reference]], config: Config, - ) -> Tuple[Dict[utils.PythonIdentifier, "EndpointCollection"], Schemas, Parameters]: + ) -> tuple[dict[utils.PythonIdentifier, "EndpointCollection"], Schemas, Parameters]: """Parse the openapi paths data to get EndpointCollections by tag""" - endpoints_by_tag: Dict[utils.PythonIdentifier, EndpointCollection] = {} + endpoints_by_tag: dict[utils.PythonIdentifier, EndpointCollection] = {} methods = ["get", "put", "post", "delete", "options", "head", "patch", "trace"] @@ -124,7 +124,7 @@ class RequestBodyParser(Protocol): def __call__( self, *, body: oai.RequestBody, schemas: Schemas, parent_name: str, config: Config - ) -> Tuple[Union[Property, PropertyError, None], Schemas]: ... # pragma: no cover + ) -> tuple[Union[Property, PropertyError, None], Schemas]: ... # pragma: no cover @dataclass @@ -138,21 +138,21 @@ class Endpoint: description: Optional[str] name: str requires_security: bool - tags: List[PythonIdentifier] + tags: list[PythonIdentifier] summary: Optional[str] = "" - relative_imports: Set[str] = field(default_factory=set) - query_parameters: List[Property] = field(default_factory=list) - path_parameters: List[Property] = field(default_factory=list) - header_parameters: List[Property] = field(default_factory=list) - cookie_parameters: List[Property] = field(default_factory=list) - responses: List[Response] = field(default_factory=list) - bodies: List[Body] = field(default_factory=list) - errors: List[ParseError] = field(default_factory=list) + relative_imports: set[str] = field(default_factory=set) + query_parameters: list[Property] = field(default_factory=list) + path_parameters: list[Property] = field(default_factory=list) + header_parameters: list[Property] = field(default_factory=list) + cookie_parameters: list[Property] = field(default_factory=list) + responses: list[Response] = field(default_factory=list) + bodies: list[Body] = field(default_factory=list) + errors: list[ParseError] = field(default_factory=list) @staticmethod def _add_responses( *, endpoint: "Endpoint", data: oai.Responses, schemas: Schemas, config: Config - ) -> Tuple["Endpoint", Schemas]: + ) -> tuple["Endpoint", Schemas]: endpoint = deepcopy(endpoint) for code, response_data in data.items(): status_code: HTTPStatus @@ -204,7 +204,7 @@ def add_parameters( schemas: Schemas, parameters: Parameters, config: Config, - ) -> Tuple[Union["Endpoint", ParseError], Schemas, Parameters]: + ) -> tuple[Union["Endpoint", ParseError], Schemas, Parameters]: """Process the defined `parameters` for an Endpoint. Any existing parameters will be ignored, so earlier instances of a parameter take precedence. PathItem @@ -233,8 +233,8 @@ def add_parameters( endpoint = deepcopy(endpoint) - unique_parameters: Set[Tuple[str, oai.ParameterLocation]] = set() - parameters_by_location: Dict[str, List[Property]] = { + unique_parameters: set[tuple[str, oai.ParameterLocation]] = set() + parameters_by_location: dict[str, list[Property]] = { oai.ParameterLocation.QUERY: endpoint.query_parameters, oai.ParameterLocation.PATH: endpoint.path_parameters, oai.ParameterLocation.HEADER: endpoint.header_parameters, @@ -311,7 +311,7 @@ def _check_parameters_for_conflicts( self, *, config: Config, - previously_modified_params: Optional[Set[Tuple[oai.ParameterLocation, str]]] = None, + previously_modified_params: Optional[set[tuple[oai.ParameterLocation, str]]] = None, ) -> Union["Endpoint", ParseError]: """Check for conflicting parameters @@ -323,7 +323,7 @@ def _check_parameters_for_conflicts( unique python_name. """ modified_params = previously_modified_params or set() - used_python_names: Dict[PythonIdentifier, Tuple[oai.ParameterLocation, Property]] = {} + used_python_names: dict[PythonIdentifier, tuple[oai.ParameterLocation, Property]] = {} reserved_names = ["client", "url"] for parameter in self.iter_all_parameters(): location, prop = parameter @@ -399,12 +399,12 @@ def from_data( data: oai.Operation, path: str, method: str, - tags: List[PythonIdentifier], + tags: list[PythonIdentifier], schemas: Schemas, parameters: Parameters, - request_bodies: Dict[str, Union[oai.RequestBody, oai.Reference]], + request_bodies: dict[str, Union[oai.RequestBody, oai.Reference]], config: Config, - ) -> Tuple[Union["Endpoint", ParseError], Schemas, Parameters]: + ) -> tuple[Union["Endpoint", ParseError], Schemas, Parameters]: """Construct an endpoint from the OpenAPI data""" if data.operationId is None: @@ -468,14 +468,14 @@ def response_type(self) -> str: return self.responses[0].prop.get_type_string(quoted=False) return f"Union[{', '.join(types)}]" - def iter_all_parameters(self) -> Iterator[Tuple[oai.ParameterLocation, Property]]: + def iter_all_parameters(self) -> Iterator[tuple[oai.ParameterLocation, Property]]: """Iterate through all the parameters of this endpoint""" yield from ((oai.ParameterLocation.PATH, param) for param in self.path_parameters) yield from ((oai.ParameterLocation.QUERY, param) for param in self.query_parameters) yield from ((oai.ParameterLocation.HEADER, param) for param in self.header_parameters) yield from ((oai.ParameterLocation.COOKIE, param) for param in self.cookie_parameters) - def list_all_parameters(self) -> List[Property]: + def list_all_parameters(self) -> list[Property]: """Return a list of all the parameters of this endpoint""" return ( self.path_parameters @@ -494,12 +494,12 @@ class GeneratorData: description: Optional[str] version: str models: Iterator[ModelProperty] - errors: List[ParseError] - endpoint_collections_by_tag: Dict[utils.PythonIdentifier, EndpointCollection] + errors: list[ParseError] + endpoint_collections_by_tag: dict[utils.PythonIdentifier, EndpointCollection] enums: Iterator[Union[EnumProperty, LiteralEnumProperty]] @staticmethod - def from_dict(data: Dict[str, Any], *, config: Config) -> Union["GeneratorData", GeneratorError]: + def from_dict(data: dict[str, Any], *, config: Config) -> Union["GeneratorData", GeneratorError]: """Create an OpenAPI from dict""" try: openapi = oai.OpenAPI.model_validate(data) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py index ec4212d9af23..ba667347bd07 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py @@ -108,8 +108,8 @@ def _property_from_ref( data: oai.Reference, schemas: Schemas, config: Config, - roots: Set[ReferencePath | utils.ClassName], -) -> Tuple[Property | PropertyError, Schemas]: + roots: set[ReferencePath | utils.ClassName], +) -> tuple[Property | PropertyError, Schemas]: ref_path = parse_reference_path(data.ref) if isinstance(ref_path, ParseError): return PropertyError(data=data, detail=ref_path.detail), schemas @@ -145,8 +145,8 @@ def property_from_data( # noqa: PLR0911, PLR0912 parent_name: str, config: Config, process_properties: bool = True, - roots: Set[ReferencePath | utils.ClassName] | None = None, -) -> Tuple[Property | PropertyError, Schemas]: + roots: set[ReferencePath | utils.ClassName] | None = None, +) -> tuple[Property | PropertyError, Schemas]: """Generate a Property from the OpenAPI dictionary representation of it""" roots = roots or set() name = utils.remove_string_escapes(name) @@ -161,7 +161,7 @@ def property_from_data( # noqa: PLR0911, PLR0912 roots=roots, ) - sub_data: List[oai.Schema | oai.Reference] = data.allOf + data.anyOf + data.oneOf + sub_data: list[oai.Schema | oai.Reference] = data.allOf + data.anyOf + data.oneOf # A union of a single reference should just be passed through to that reference (don't create copy class) if len(sub_data) == 1 and isinstance(sub_data[0], oai.Reference): prop, schemas = _property_from_ref( @@ -312,13 +312,13 @@ def property_from_data( # noqa: PLR0911, PLR0912 def _create_schemas( *, - components: Dict[str, oai.Reference | oai.Schema], + components: dict[str, oai.Reference | oai.Schema], schemas: Schemas, config: Config, ) -> Schemas: - to_process: Iterable[Tuple[str, oai.Reference | oai.Schema]] = components.items() + to_process: Iterable[tuple[str, oai.Reference | oai.Schema]] = components.items() still_making_progress = True - errors: List[PropertyError] = [] + errors: list[PropertyError] = [] # References could have forward References so keep going as long as we are making progress while still_making_progress: @@ -360,8 +360,8 @@ def _propogate_removal(*, root: ReferencePath | utils.ClassName, schemas: Schema def _process_model_errors( - model_errors: List[Tuple[ModelProperty, PropertyError]], *, schemas: Schemas -) -> List[PropertyError]: + model_errors: list[tuple[ModelProperty, PropertyError]], *, schemas: Schemas +) -> list[PropertyError]: for model, error in model_errors: error.detail = error.detail or "" error.detail += "\n\nFailure to process schema has resulted in the removal of:" @@ -373,8 +373,8 @@ def _process_model_errors( def _process_models(*, schemas: Schemas, config: Config) -> Schemas: to_process = schemas.models_to_process still_making_progress = True - final_model_errors: List[Tuple[ModelProperty, PropertyError]] = [] - latest_model_errors: List[Tuple[ModelProperty, PropertyError]] = [] + final_model_errors: list[tuple[ModelProperty, PropertyError]] = [] + latest_model_errors: list[tuple[ModelProperty, PropertyError]] = [] # Models which refer to other models in their allOf must be processed after their referenced models while still_making_progress: @@ -407,7 +407,7 @@ def _process_models(*, schemas: Schemas, config: Config) -> Schemas: def build_schemas( *, - components: Dict[str, oai.Reference | oai.Schema], + components: dict[str, oai.Reference | oai.Schema], schemas: Schemas, config: Config, ) -> Schemas: @@ -419,16 +419,16 @@ def build_schemas( def build_parameters( *, - components: Dict[str, oai.Reference | oai.Parameter], + components: dict[str, oai.Reference | oai.Parameter], parameters: Parameters, config: Config, ) -> Parameters: """Get a list of Parameters from an OpenAPI dict""" - to_process: Iterable[Tuple[str, oai.Reference | oai.Parameter]] = [] + to_process: Iterable[tuple[str, oai.Reference | oai.Parameter]] = [] if components is not None: to_process = components.items() still_making_progress = True - errors: List[ParameterError] = [] + errors: list[ParameterError] = [] # References could have forward References so keep going as long as we are making progress while still_making_progress: diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py index 882d9f6b7894..5fd4235d75b3 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py @@ -23,7 +23,7 @@ class BooleanProperty(PropertyProtocol): _type_string: ClassVar[str] = "bool" _json_type_string: ClassVar[str] = "bool" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { oai.ParameterLocation.QUERY, oai.ParameterLocation.PATH, oai.ParameterLocation.COOKIE, diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/const.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/const.py index f4d9b5b758ff..8b9967f19734 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/const.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/const.py @@ -102,7 +102,7 @@ def get_type_string( return f"Union[{lit}, Unset]" return lit - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/date.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/date.py index b5c3ca997c27..7261698ea302 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/date.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/date.py @@ -60,7 +60,7 @@ def convert_value(cls, value: Any) -> Value | None | PropertyError: return Value(python_code=f"isoparse({value!r}).date()", raw_value=value) return PropertyError(f"Cannot convert {value} to a date") - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py index 0556228d0742..5924d173cda2 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py @@ -62,7 +62,7 @@ def convert_value(cls, value: Any) -> Value | None | PropertyError: return Value(python_code=f"isoparse({value!r})", raw_value=value) return PropertyError(f"Cannot convert {value} to a datetime") - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py index b5bf1e79553f..fc7f20bd924c 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py @@ -29,13 +29,13 @@ class EnumProperty(PropertyProtocol): python_name: utils.PythonIdentifier description: str | None example: str | None - values: Dict[str, ValueType] + values: dict[str, ValueType] class_info: Class value_type: type[ValueType] template: ClassVar[str] = "enum_property.py.jinja" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { oai.ParameterLocation.QUERY, oai.ParameterLocation.PATH, oai.ParameterLocation.COOKIE, @@ -52,7 +52,7 @@ def build( # noqa: PLR0911 schemas: Schemas, parent_name: str, config: Config, - ) -> Tuple[EnumProperty | NoneProperty | UnionProperty | PropertyError, Schemas]: + ) -> tuple[EnumProperty | NoneProperty | UnionProperty | PropertyError, Schemas]: """ Create an EnumProperty from schema data. @@ -99,7 +99,7 @@ def build( # noqa: PLR0911 if value_type not in (str, int): return PropertyError(header=f"Unsupported enum type {value_type}", data=data), schemas value_list = cast( - Union[List[int], list[str]], unchecked_value_list + Union[list[int], list[str]], unchecked_value_list ) # We checked this with all the value_types stuff if len(value_list) < len(enum): # Only one of the values was None, that becomes a union @@ -170,7 +170,7 @@ def get_base_type_string(self, *, quoted: bool = False) -> str: def get_base_json_type_string(self, *, quoted: bool = False) -> str: return self.value_type.__name__ - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere @@ -183,9 +183,9 @@ def get_imports(self, *, prefix: str) -> Set[str]: return imports @staticmethod - def values_from_list(values: List[str] | list[int], class_info: Class) -> Dict[str, ValueType]: + def values_from_list(values: list[str] | list[int], class_info: Class) -> dict[str, ValueType]: """Convert a list of values into dict of {name: value}, where value can sometimes be None""" - output: Dict[str, ValueType] = {} + output: dict[str, ValueType] = {} for i, value in enumerate(values): value = cast(Union[str, int], value) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/file.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/file.py index f8a5baa711fa..505876b6370e 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/file.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/file.py @@ -54,7 +54,7 @@ def convert_value(cls, value: Any) -> None | PropertyError: return PropertyError(detail="File properties cannot have a default value") return value - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/float.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/float.py index d8cfe62f96be..a785db6d4a11 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/float.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/float.py @@ -23,7 +23,7 @@ class FloatProperty(PropertyProtocol): _type_string: ClassVar[str] = "float" _json_type_string: ClassVar[str] = "float" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { oai.ParameterLocation.QUERY, oai.ParameterLocation.PATH, oai.ParameterLocation.COOKIE, diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/int.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/int.py index 44b1f91d6473..1cd340fbdd76 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/int.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/int.py @@ -23,7 +23,7 @@ class IntProperty(PropertyProtocol): _type_string: ClassVar[str] = "int" _json_type_string: ClassVar[str] = "int" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { oai.ParameterLocation.QUERY, oai.ParameterLocation.PATH, oai.ParameterLocation.COOKIE, diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py index f0a77754b992..bf0756fe307c 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py @@ -35,8 +35,8 @@ def build( parent_name: str, config: Config, process_properties: bool, - roots: Set[ReferencePath | utils.ClassName], - ) -> Tuple[ListProperty | PropertyError, Schemas]: + roots: set[ReferencePath | utils.ClassName], + ) -> tuple[ListProperty | PropertyError, Schemas]: """ Build a ListProperty the right way, use this instead of the normal constructor. @@ -106,16 +106,16 @@ def convert_value(self, value: Any) -> Value | None | PropertyError: return None # pragma: no cover def get_base_type_string(self, *, quoted: bool = False) -> str: - return f"List[{self.inner_property.get_type_string(quoted=not self.inner_property.is_base_type)}]" + return f"list[{self.inner_property.get_type_string(quoted=not self.inner_property.is_base_type)}]" def get_base_json_type_string(self, *, quoted: bool = False) -> str: - return f"List[{self.inner_property.get_type_string(json=True, quoted=not self.inner_property.is_base_type)}]" + return f"list[{self.inner_property.get_type_string(json=True, quoted=not self.inner_property.is_base_type)}]" def get_instance_type_string(self) -> str: """Get a string representation of runtime type that should be used for `isinstance` checks""" return "list" - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere @@ -128,7 +128,7 @@ def get_imports(self, *, prefix: str) -> Set[str]: imports.add("from typing import cast") return imports - def get_lazy_imports(self, *, prefix: str) -> Set[str]: + def get_lazy_imports(self, *, prefix: str) -> set[str]: lazy_imports = super().get_lazy_imports(prefix=prefix) lazy_imports.update(self.inner_property.get_lazy_imports(prefix=prefix)) return lazy_imports @@ -151,7 +151,7 @@ def get_type_string( if json: type_string = self.get_base_json_type_string() elif multipart: - type_string = "Tuple[None, bytes, str]" + type_string = "tuple[None, bytes, str]" else: type_string = self.get_base_type_string() diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py index 549d81912a29..669b62f583fa 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py @@ -29,13 +29,13 @@ class LiteralEnumProperty(PropertyProtocol): python_name: utils.PythonIdentifier description: str | None example: str | None - values: Set[ValueType] + values: set[ValueType] class_info: Class value_type: type[ValueType] template: ClassVar[str] = "literal_enum_property.py.jinja" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { oai.ParameterLocation.QUERY, oai.ParameterLocation.PATH, oai.ParameterLocation.COOKIE, @@ -52,7 +52,7 @@ def build( # noqa: PLR0911 schemas: Schemas, parent_name: str, config: Config, - ) -> Tuple[LiteralEnumProperty | NoneProperty | UnionProperty | PropertyError, Schemas]: + ) -> tuple[LiteralEnumProperty | NoneProperty | UnionProperty | PropertyError, Schemas]: """ Create a LiteralEnumProperty from schema data. @@ -98,7 +98,7 @@ def build( # noqa: PLR0911 if value_type not in (str, int): return PropertyError(header=f"Unsupported enum type {value_type}", data=data), schemas value_list = cast( - Union[List[int], list[str]], unchecked_value_list + Union[list[int], list[str]], unchecked_value_list ) # We checked this with all the value_types stuff if len(value_list) < len(enum): # Only one of the values was None, that becomes a union @@ -120,7 +120,7 @@ def build( # noqa: PLR0911 if parent_name: class_name = f"{utils.pascal_case(parent_name)}{utils.pascal_case(class_name)}" class_info = Class.from_string(string=class_name, config=config) - values: Set[str | int] = set(value_list) + values: set[str | int] = set(value_list) if class_info.name in schemas.classes_by_name: existing = schemas.classes_by_name[class_info.name] @@ -171,7 +171,7 @@ def get_base_json_type_string(self, *, quoted: bool = False) -> str: def get_instance_type_string(self) -> str: return self.value_type.__name__ - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py index db6424a7c631..f04b67928a37 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py @@ -1,9 +1,9 @@ from __future__ import annotations -from openapi_python_client.parser.properties.date import DateProperty -from openapi_python_client.parser.properties.datetime import DateTimeProperty -from openapi_python_client.parser.properties.file import FileProperty -from openapi_python_client.parser.properties.literal_enum_property import LiteralEnumProperty +from .date import DateProperty +from .datetime import DateTimeProperty +from .file import FileProperty +from .literal_enum_property import LiteralEnumProperty __all__ = ["merge_properties"] diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py index 73bc56ae0519..76262450113c 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py @@ -26,13 +26,13 @@ class ModelProperty(PropertyProtocol): class_info: Class data: oai.Schema description: str - roots: Set[ReferencePath | utils.ClassName] - required_properties: List[Property] | None - optional_properties: List[Property] | None - relative_imports: Set[str] | None - lazy_imports: Set[str] | None + roots: set[ReferencePath | utils.ClassName] + required_properties: list[Property] | None + optional_properties: list[Property] | None + relative_imports: set[str] | None + lazy_imports: set[str] | None additional_properties: Property | None - _json_type_string: ClassVar[str] = "Dict[str, Any]" + _json_type_string: ClassVar[str] = "dict[str, Any]" template: ClassVar[str] = "model_property.py.jinja" json_is_dict: ClassVar[bool] = True @@ -49,8 +49,8 @@ def build( parent_name: str | None, config: Config, process_properties: bool, - roots: Set[ReferencePath | utils.ClassName], - ) -> Tuple[ModelProperty | PropertyError, Schemas]: + roots: set[ReferencePath | utils.ClassName], + ) -> tuple[ModelProperty | PropertyError, Schemas]: """ A single ModelProperty from its OAI data @@ -75,10 +75,10 @@ def build( class_string = title class_info = Class.from_string(string=class_string, config=config) model_roots = {*roots, class_info.name} - required_properties: List[Property] | None = None - optional_properties: List[Property] | None = None - relative_imports: Set[str] | None = None - lazy_imports: Set[str] | None = None + required_properties: list[Property] | None = None + optional_properties: list[Property] | None = None + relative_imports: set[str] | None = None + lazy_imports: set[str] | None = None additional_properties: Property | None = None if process_properties: data_or_err, schemas = _process_property_data( @@ -143,7 +143,7 @@ def self_import(self) -> str: def get_base_type_string(self, *, quoted: bool = False) -> str: return f'"{self.class_info.name}"' if quoted else self.class_info.name - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere @@ -159,7 +159,7 @@ def get_imports(self, *, prefix: str) -> Set[str]: ) return imports - def get_lazy_imports(self, *, prefix: str) -> Set[str]: + def get_lazy_imports(self, *, prefix: str) -> set[str]: """Get a set of lazy import strings that should be included when this property is used somewhere Args: @@ -168,7 +168,7 @@ def get_lazy_imports(self, *, prefix: str) -> Set[str]: """ return {f"from {prefix}{self.self_import}"} - def set_relative_imports(self, relative_imports: Set[str]) -> None: + def set_relative_imports(self, relative_imports: set[str]) -> None: """Set the relative imports set for this ModelProperty, filtering out self imports Args: @@ -176,7 +176,7 @@ def set_relative_imports(self, relative_imports: Set[str]) -> None: """ object.__setattr__(self, "relative_imports", {ri for ri in relative_imports if self.self_import not in ri}) - def set_lazy_imports(self, lazy_imports: Set[str]) -> None: + def set_lazy_imports(self, lazy_imports: set[str]) -> None: """Set the lazy imports set for this ModelProperty, filtering out self imports Args: @@ -202,7 +202,7 @@ def get_type_string( if json: type_string = self.get_base_json_type_string() elif multipart: - type_string = "Tuple[None, bytes, str]" + type_string = "tuple[None, bytes, str]" else: type_string = self.get_base_type_string() @@ -230,10 +230,10 @@ def _resolve_naming_conflict(first: Property, second: Property, config: Config) class _PropertyData(NamedTuple): - optional_props: List[Property] - required_props: List[Property] - relative_imports: Set[str] - lazy_imports: Set[str] + optional_props: list[Property] + required_props: list[Property] + relative_imports: set[str] + lazy_imports: set[str] schemas: Schemas @@ -243,14 +243,14 @@ def _process_properties( # noqa: PLR0912, PLR0911 schemas: Schemas, class_name: utils.ClassName, config: Config, - roots: Set[ReferencePath | utils.ClassName], + roots: set[ReferencePath | utils.ClassName], ) -> _PropertyData | PropertyError: from . import property_from_data from .merge_properties import merge_properties - properties: Dict[str, Property] = {} - relative_imports: Set[str] = set() - lazy_imports: Set[str] = set() + properties: dict[str, Property] = {} + relative_imports: set[str] = set() + lazy_imports: set[str] = set() required_set = set(data.required or []) def _add_if_no_conflict(new_prop: Property) -> PropertyError | None: @@ -274,7 +274,7 @@ def _add_if_no_conflict(new_prop: Property) -> PropertyError | None: properties[merged_prop.name] = merged_prop return None - unprocessed_props: List[Tuple[str, oai.Reference | oai.Schema]] = ( + unprocessed_props: list[tuple[str, oai.Reference | oai.Schema]] = ( list(data.properties.items()) if data.properties else [] ) for sub_prop in data.allOf: @@ -354,8 +354,8 @@ def _get_additional_properties( schemas: Schemas, class_name: utils.ClassName, config: Config, - roots: Set[ReferencePath | utils.ClassName], -) -> Tuple[Property | None | PropertyError, Schemas]: + roots: set[ReferencePath | utils.ClassName], +) -> tuple[Property | None | PropertyError, Schemas]: from . import property_from_data if schema_additional is None: @@ -388,8 +388,8 @@ def _process_property_data( schemas: Schemas, class_info: Class, config: Config, - roots: Set[ReferencePath | utils.ClassName], -) -> Tuple[tuple[_PropertyData, Property | None] | PropertyError, Schemas]: + roots: set[ReferencePath | utils.ClassName], +) -> tuple[tuple[_PropertyData, Property | None] | PropertyError, Schemas]: property_data = _process_properties( data=data, schemas=schemas, class_name=class_info.name, config=config, roots=roots ) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/none.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/none.py index ab493fc65836..9c473693dfb2 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/none.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/none.py @@ -21,7 +21,7 @@ class NoneProperty(PropertyProtocol): description: str | None example: str | None - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { oai.ParameterLocation.QUERY, oai.ParameterLocation.COOKIE, oai.ParameterLocation.HEADER, diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py index 280b0e8ade6c..9a5b51828b04 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py @@ -49,7 +49,7 @@ class PropertyProtocol(Protocol): required: bool _type_string: ClassVar[str] = "" _json_type_string: ClassVar[str] = "" # Type of the property after JSON serialization - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { oai.ParameterLocation.QUERY, oai.ParameterLocation.PATH, oai.ParameterLocation.COOKIE, @@ -116,7 +116,7 @@ def get_type_string( if json: type_string = self.get_base_json_type_string(quoted=quoted) elif multipart: - type_string = "Tuple[None, bytes, str]" + type_string = "tuple[None, bytes, str]" else: type_string = self.get_base_type_string(quoted=quoted) @@ -129,7 +129,7 @@ def get_instance_type_string(self) -> str: return self.get_type_string(no_optional=True, quoted=False) # noinspection PyUnusedLocal - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere @@ -143,7 +143,7 @@ def get_imports(self, *, prefix: str) -> Set[str]: imports.add(f"from {prefix}types import UNSET, Unset") return imports - def get_lazy_imports(self, *, prefix: str) -> Set[str]: + def get_lazy_imports(self, *, prefix: str) -> set[str]: """Get a set of lazy import strings that should be included when this property is used somewhere Args: diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py index c31455ade372..177a86924545 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py @@ -10,7 +10,7 @@ "update_schemas_with_data", ] -from typing import TYPE_CHECKING, NewType, Union, cast, Dict, Set, List, Tuple +from typing import TYPE_CHECKING, NewType, Union, cast from urllib.parse import urlparse from attrs import define, evolve, field @@ -76,13 +76,13 @@ def from_string(*, string: str, config: Config) -> "Class": class Schemas: """Structure for containing all defined, shareable, and reusable schemas (attr classes and Enums)""" - classes_by_reference: Dict[ReferencePath, Property] = field(factory=dict) - dependencies: Dict[ReferencePath, Set[Union[ReferencePath, ClassName]]] = field(factory=dict) - classes_by_name: Dict[ClassName, Property] = field(factory=dict) - models_to_process: List[ModelProperty] = field(factory=list) - errors: List[ParseError] = field(factory=list) + classes_by_reference: dict[ReferencePath, Property] = field(factory=dict) + dependencies: dict[ReferencePath, set[Union[ReferencePath, ClassName]]] = field(factory=dict) + classes_by_name: dict[ClassName, Property] = field(factory=dict) + models_to_process: list[ModelProperty] = field(factory=list) + errors: list[ParseError] = field(factory=list) - def add_dependencies(self, ref_path: ReferencePath, roots: Set[Union[ReferencePath, ClassName]]) -> None: + def add_dependencies(self, ref_path: ReferencePath, roots: set[Union[ReferencePath, ClassName]]) -> None: """Record new dependencies on the given ReferencePath Args: @@ -143,9 +143,9 @@ def update_schemas_with_data( class Parameters: """Structure for containing all defined, shareable, and reusable parameters""" - classes_by_reference: Dict[ReferencePath, Parameter] = field(factory=dict) - classes_by_name: Dict[ClassName, Parameter] = field(factory=dict) - errors: List[ParseError] = field(factory=list) + classes_by_reference: dict[ReferencePath, Parameter] = field(factory=dict) + classes_by_name: dict[ClassName, Parameter] = field(factory=dict) + errors: list[ParseError] = field(factory=list) def parameter_from_data( @@ -154,7 +154,7 @@ def parameter_from_data( data: Union[oai.Reference, oai.Parameter], parameters: Parameters, config: Config, -) -> Tuple[Union[Parameter, ParameterError], Parameters]: +) -> tuple[Union[Parameter, ParameterError], Parameters]: """Generates parameters from an OpenAPI Parameter spec.""" if isinstance(data, oai.Reference): diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/string.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/string.py index 7595398c5653..e40c1eee6894 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/string.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/string.py @@ -23,7 +23,7 @@ class StringProperty(PropertyProtocol): example: str | None _type_string: ClassVar[str] = "str" _json_type_string: ClassVar[str] = "str" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { oai.ParameterLocation.QUERY, oai.ParameterLocation.PATH, oai.ParameterLocation.COOKIE, diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/union.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/union.py index 407c089f8a79..8b7b02a4804f 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/union.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/union.py @@ -23,13 +23,13 @@ class UnionProperty(PropertyProtocol): python_name: PythonIdentifier description: str | None example: str | None - inner_properties: List[PropertyProtocol] + inner_properties: list[PropertyProtocol] template: ClassVar[str] = "union_property.py.jinja" @classmethod def build( cls, *, data: oai.Schema, name: str, required: bool, schemas: Schemas, parent_name: str, config: Config - ) -> Tuple[UnionProperty | PropertyError, Schemas]: + ) -> tuple[UnionProperty | PropertyError, Schemas]: """ Create a `UnionProperty` the right way. @@ -47,7 +47,7 @@ def build( """ from . import property_from_data - sub_properties: List[PropertyProtocol] = [] + sub_properties: list[PropertyProtocol] = [] type_list_data = [] if isinstance(data.type, list): @@ -67,7 +67,7 @@ def build( return PropertyError(detail=f"Invalid property in union {name}", data=sub_prop_data), schemas sub_properties.append(sub_prop) - def flatten_union_properties(sub_properties: List[PropertyProtocol]) -> list[PropertyProtocol]: + def flatten_union_properties(sub_properties: list[PropertyProtocol]) -> list[PropertyProtocol]: flattened = [] for sub_prop in sub_properties: if isinstance(sub_prop, UnionProperty): @@ -106,14 +106,14 @@ def convert_value(self, value: Any) -> Value | None | PropertyError: return value_or_error return value_or_error - def _get_inner_type_strings(self, json: bool, multipart: bool) -> Set[str]: + def _get_inner_type_strings(self, json: bool, multipart: bool) -> set[str]: return { p.get_type_string(no_optional=True, json=json, multipart=multipart, quoted=not p.is_base_type) for p in self.inner_properties } @staticmethod - def _get_type_string_from_inner_type_strings(inner_types: Set[str]) -> str: + def _get_type_string_from_inner_type_strings(inner_types: set[str]) -> str: if len(inner_types) == 1: return inner_types.pop() return f"Union[{', '.join(sorted(inner_types))}]" @@ -124,7 +124,7 @@ def get_base_type_string(self, *, quoted: bool = False) -> str: def get_base_json_type_string(self, *, quoted: bool = False) -> str: return self._get_type_string_from_inner_type_strings(self._get_inner_type_strings(json=True, multipart=False)) - def get_type_strings_in_union(self, *, no_optional: bool = False, json: bool, multipart: bool) -> Set[str]: + def get_type_strings_in_union(self, *, no_optional: bool = False, json: bool, multipart: bool) -> set[str]: """ Get the set of all the types that should appear within the `Union` representing this property. @@ -161,7 +161,7 @@ def get_type_string( type_strings_in_union = self.get_type_strings_in_union(no_optional=no_optional, json=json, multipart=multipart) return self._get_type_string_from_inner_type_strings(type_strings_in_union) - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere @@ -175,7 +175,7 @@ def get_imports(self, *, prefix: str) -> Set[str]: imports.add("from typing import cast, Union") return imports - def get_lazy_imports(self, *, prefix: str) -> Set[str]: + def get_lazy_imports(self, *, prefix: str) -> set[str]: lazy_imports = super().get_lazy_imports(prefix=prefix) for inner_prop in self.inner_properties: lazy_imports.update(inner_prop.get_lazy_imports(prefix=prefix)) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py index 6b344c3bf745..86d7d6a0abeb 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py @@ -24,7 +24,7 @@ class UuidProperty(PropertyProtocol): _type_string: ClassVar[str] = "UUID" _json_type_string: ClassVar[str] = "str" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { oai.ParameterLocation.QUERY, oai.ParameterLocation.PATH, oai.ParameterLocation.COOKIE, @@ -67,7 +67,7 @@ def convert_value(cls, value: Any) -> Value | None | PropertyError: return Value(python_code=f"UUID('{value}')", raw_value=value) return PropertyError(f"Invalid UUID value: {value}") - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere diff --git a/chaotic-openapi/chaotic_openapi/front/parser/responses.py b/chaotic-openapi/chaotic_openapi/front/parser/responses.py index 26ebfa4af742..17c8a6ef143f 100644 --- a/chaotic-openapi/chaotic_openapi/front/parser/responses.py +++ b/chaotic-openapi/chaotic_openapi/front/parser/responses.py @@ -1,11 +1,11 @@ __all__ = ["Response", "response_from_data"] from http import HTTPStatus -from typing import Optional, TypedDict, Union, Tuple +from typing import Optional, TypedDict, Union from attrs import define -from openapi_python_client import utils +from .. import utils from .. import Config from .. import schema as oai @@ -86,7 +86,7 @@ def response_from_data( schemas: Schemas, parent_name: str, config: Config, -) -> Tuple[Union[Response, ParseError], Schemas]: +) -> tuple[Union[Response, ParseError], Schemas]: """Generate a Response from the OpenAPI dictionary representation of it""" response_name = f"response_{status_code}" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md index 3d92b4d018df..f58b369093dc 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md @@ -34,9 +34,9 @@ the following schema classes are actually just a typing of `Dict`: | Schema Type | Implementation | | ----------- | -------------- | -| Callback | `Callback = Dict[str, PathItem]` | -| Paths | `Paths = Dict[str, PathItem]` | -| Responses | `Responses = Dict[str, Union[Response, Reference]]` | -| SecurityRequirement | `SecurityRequirement = Dict[str, List[str]]` | +| Callback | `Callback = Dict[str, PathItem]` | +| Paths | `Paths = Dict[str, PathItem]` | +| Responses | `Responses = Dict[str, Union[Response, Reference]]` | +| SecurityRequirement | `SecurityRequirement = Dict[str, List[str]]` | On creating such schema instances, please use python's `dict` type instead to instantiate. diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py index 51fdc454e27c..f4593cc8d9b2 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py @@ -1,11 +1,11 @@ -from typing import TYPE_CHECKING, Dict +from typing import TYPE_CHECKING if TYPE_CHECKING: # pragma: no cover from .path_item import PathItem else: PathItem = "PathItem" -Callback = Dict[str, PathItem] +Callback = dict[str, PathItem] """ A map of possible out-of band callbacks related to the parent operation. Each value in the map is a [Path Item Object](#pathItemObject) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py index 003a04b3b5d5..babe262657a5 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py @@ -1,4 +1,4 @@ -from typing import Optional, Union, Dict +from typing import Optional, Union from pydantic import BaseModel, ConfigDict @@ -25,15 +25,15 @@ class Components(BaseModel): - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#componentsObject """ - schemas: Optional[Dict[str, Union[Schema, Reference]]] = None - responses: Optional[Dict[str, Union[Response, Reference]]] = None - parameters: Optional[Dict[str, Union[Parameter, Reference]]] = None - examples: Optional[Dict[str, Union[Example, Reference]]] = None - requestBodies: Optional[Dict[str, Union[RequestBody, Reference]]] = None - headers: Optional[Dict[str, Union[Header, Reference]]] = None - securitySchemes: Optional[Dict[str, Union[SecurityScheme, Reference]]] = None - links: Optional[Dict[str, Union[Link, Reference]]] = None - callbacks: Optional[Dict[str, Union[Callback, Reference]]] = None + schemas: Optional[dict[str, Union[Schema, Reference]]] = None + responses: Optional[dict[str, Union[Response, Reference]]] = None + parameters: Optional[dict[str, Union[Parameter, Reference]]] = None + examples: Optional[dict[str, Union[Example, Reference]]] = None + requestBodies: Optional[dict[str, Union[RequestBody, Reference]]] = None + headers: Optional[dict[str, Union[Header, Reference]]] = None + securitySchemes: Optional[dict[str, Union[SecurityScheme, Reference]]] = None + links: Optional[dict[str, Union[Link, Reference]]] = None + callbacks: Optional[dict[str, Union[Callback, Reference]]] = None model_config = ConfigDict( # `Callback` contains an unresolvable forward reference, will rebuild in `__init__.py`: defer_build=True, diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py index 939271bdeab7..9f36773ba435 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py @@ -1,4 +1,4 @@ -from typing import Optional, Dict +from typing import Optional from pydantic import BaseModel, ConfigDict @@ -19,7 +19,7 @@ class Discriminator(BaseModel): """ propertyName: str - mapping: Optional[Dict[str, str]] = None + mapping: Optional[dict[str, str]] = None model_config = ConfigDict( extra="allow", json_schema_extra={ diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py index 609654f57572..ebf6295dc56a 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Optional, Union, Dict +from typing import TYPE_CHECKING, Optional, Union from pydantic import BaseModel, ConfigDict @@ -17,7 +17,7 @@ class Encoding(BaseModel): """ contentType: Optional[str] = None - headers: Optional[Dict[str, Union["Header", Reference]]] = None + headers: Optional[dict[str, Union["Header", Reference]]] = None style: Optional[str] = None explode: bool = False allowReserved: bool = False diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py index 609ae3ff9032..69cdf29c09dc 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py @@ -1,4 +1,4 @@ -from typing import Any, Optional, Dict +from typing import Any, Optional from pydantic import BaseModel, ConfigDict @@ -25,7 +25,7 @@ class Link(BaseModel): operationRef: Optional[str] = None operationId: Optional[str] = None - parameters: Optional[Dict[str, Any]] = None + parameters: Optional[dict[str, Any]] = None requestBody: Optional[Any] = None description: Optional[str] = None server: Optional[Server] = None diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py index aa81247e5f85..95f9ede147c9 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py @@ -1,4 +1,4 @@ -from typing import Any, Optional, Union, Dict +from typing import Any, Optional, Union from pydantic import BaseModel, ConfigDict, Field @@ -18,8 +18,8 @@ class MediaType(BaseModel): media_type_schema: Optional[Union[Reference, Schema]] = Field(default=None, alias="schema") example: Optional[Any] = None - examples: Optional[Dict[str, Union[Example, Reference]]] = None - encoding: Optional[Dict[str, Encoding]] = None + examples: Optional[dict[str, Union[Example, Reference]]] = None + encoding: Optional[dict[str, Encoding]] = None model_config = ConfigDict( # `Encoding` is not build yet, will rebuild in `__init__.py`: defer_build=True, diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py index ea02439b2da0..16e3660901b7 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py @@ -1,4 +1,4 @@ -from typing import Optional, Dict +from typing import Optional from pydantic import BaseModel, ConfigDict @@ -15,7 +15,7 @@ class OAuthFlow(BaseModel): authorizationUrl: Optional[str] = None tokenUrl: Optional[str] = None refreshUrl: Optional[str] = None - scopes: Dict[str, str] + scopes: dict[str, str] model_config = ConfigDict( extra="allow", json_schema_extra={ diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py index 818e9ebf3214..e66ea942ccfb 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py @@ -1,4 +1,4 @@ -from typing import Optional, List +from typing import Optional from pydantic import BaseModel, ConfigDict, field_validator @@ -22,11 +22,11 @@ class OpenAPI(BaseModel): """ info: Info - servers: List[Server] = [Server(url="/")] + servers: list[Server] = [Server(url="/")] paths: Paths components: Optional[Components] = None - security: Optional[List[SecurityRequirement]] = None - tags: Optional[List[Tag]] = None + security: Optional[list[SecurityRequirement]] = None + tags: Optional[list[Tag]] = None externalDocs: Optional[ExternalDocumentation] = None openapi: str model_config = ConfigDict( diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py index e2d2924e0b13..ebf5e1faa10c 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py @@ -1,4 +1,4 @@ -from typing import Optional, Union, List, Dict +from typing import Optional, Union from pydantic import BaseModel, ConfigDict, Field @@ -20,19 +20,19 @@ class Operation(BaseModel): - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operationObject """ - tags: Optional[List[str]] = None + tags: Optional[list[str]] = None summary: Optional[str] = None description: Optional[str] = None externalDocs: Optional[ExternalDocumentation] = None operationId: Optional[str] = None - parameters: Optional[List[Union[Parameter, Reference]]] = None + parameters: Optional[list[Union[Parameter, Reference]]] = None request_body: Optional[Union[RequestBody, Reference]] = Field(None, alias="requestBody") responses: Responses - callbacks: Optional[Dict[str, Callback]] = None + callbacks: Optional[dict[str, Callback]] = None deprecated: bool = False - security: Optional[List[SecurityRequirement]] = None - servers: Optional[List[Server]] = None + security: Optional[list[SecurityRequirement]] = None + servers: Optional[list[Server]] = None model_config = ConfigDict( # `Callback` contains an unresolvable forward reference, will rebuild in `__init__.py`: defer_build=True, diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py index 981f7b375136..6f6fe9342001 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py @@ -1,4 +1,4 @@ -from typing import Any, Optional, Union, Dict +from typing import Any, Optional, Union from pydantic import BaseModel, ConfigDict, Field @@ -32,8 +32,8 @@ class Parameter(BaseModel): allowReserved: bool = False param_schema: Optional[Union[Reference, Schema]] = Field(default=None, alias="schema") example: Optional[Any] = None - examples: Optional[Dict[str, Union[Example, Reference]]] = None - content: Optional[Dict[str, MediaType]] = None + examples: Optional[dict[str, Union[Example, Reference]]] = None + content: Optional[dict[str, MediaType]] = None model_config = ConfigDict( # `MediaType` is not build yet, will rebuild in `__init__.py`: defer_build=True, diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py index 7dd06a3fcae2..8c1eab6ea75d 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Optional, Union, List +from typing import TYPE_CHECKING, Optional, Union from pydantic import BaseModel, ConfigDict, Field @@ -33,8 +33,8 @@ class PathItem(BaseModel): head: Optional["Operation"] = None patch: Optional["Operation"] = None trace: Optional["Operation"] = None - servers: Optional[List[Server]] = None - parameters: Optional[List[Union[Parameter, Reference]]] = None + servers: Optional[list[Server]] = None + parameters: Optional[list[Union[Parameter, Reference]]] = None model_config = ConfigDict( # `Operation` is an unresolvable forward reference, will rebuild in `__init__.py`: defer_build=True, diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py index d8861238305f..86c1dfd19d3c 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py @@ -1,7 +1,6 @@ from .path_item import PathItem -from typing import Dict -Paths = Dict[str, PathItem] +Paths = dict[str, PathItem] """ Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py index b1464e47e1dd..8cd9bb52744f 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py @@ -1,4 +1,4 @@ -from typing import Optional, Dict +from typing import Optional from pydantic import BaseModel, ConfigDict @@ -14,7 +14,7 @@ class RequestBody(BaseModel): """ description: Optional[str] = None - content: Dict[str, MediaType] + content: dict[str, MediaType] required: bool = False model_config = ConfigDict( # `MediaType` is not build yet, will rebuild in `__init__.py`: diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py index bb20fad84d8e..b7ec0d3579ec 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py @@ -1,4 +1,4 @@ -from typing import Optional, Union, Dict +from typing import Optional, Union from pydantic import BaseModel, ConfigDict @@ -19,9 +19,9 @@ class Response(BaseModel): """ description: str - headers: Optional[Dict[str, Union[Header, Reference]]] = None - content: Optional[Dict[str, MediaType]] = None - links: Optional[Dict[str, Union[Link, Reference]]] = None + headers: Optional[dict[str, Union[Header, Reference]]] = None + content: Optional[dict[str, MediaType]] = None + links: Optional[dict[str, Union[Link, Reference]]] = None model_config = ConfigDict( # `MediaType` is not build yet, will rebuild in `__init__.py`: defer_build=True, diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py index 719e772e62e4..17ddc13fedaf 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py @@ -1,9 +1,9 @@ -from typing import Union, Dict +from typing import Union from .reference import Reference from .response import Response -Responses = Dict[str, Union[Response, Reference]] +Responses = dict[str, Union[Response, Reference]] """ A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py index 30e4d18e52dd..99c64eb51120 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py @@ -1,4 +1,4 @@ -from typing import Any, Optional, Union, List, Dict +from typing import Any, Optional, Union from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr, model_validator @@ -34,17 +34,17 @@ class Schema(BaseModel): uniqueItems: Optional[bool] = None maxProperties: Optional[int] = Field(default=None, ge=0) minProperties: Optional[int] = Field(default=None, ge=0) - required: Optional[List[str]] = Field(default=None) - enum: Union[None, List[Any]] = Field(default=None, min_length=1) + required: Optional[list[str]] = Field(default=None) + enum: Union[None, list[Any]] = Field(default=None, min_length=1) const: Union[None, StrictStr, StrictInt, StrictFloat, StrictBool] = None - type: Union[DataType, List[DataType], None] = Field(default=None) - allOf: List[Union[Reference, "Schema"]] = Field(default_factory=list) - oneOf: List[Union[Reference, "Schema"]] = Field(default_factory=list) - anyOf: List[Union[Reference, "Schema"]] = Field(default_factory=list) + type: Union[DataType, list[DataType], None] = Field(default=None) + allOf: list[Union[Reference, "Schema"]] = Field(default_factory=list) + oneOf: list[Union[Reference, "Schema"]] = Field(default_factory=list) + anyOf: list[Union[Reference, "Schema"]] = Field(default_factory=list) schema_not: Optional[Union[Reference, "Schema"]] = Field(default=None, alias="not") items: Optional[Union[Reference, "Schema"]] = None - prefixItems: List[Union[Reference, "Schema"]] = Field(default_factory=list) - properties: Optional[Dict[str, Union[Reference, "Schema"]]] = None + prefixItems: list[Union[Reference, "Schema"]] = Field(default_factory=list) + properties: Optional[dict[str, Union[Reference, "Schema"]]] = None additionalProperties: Optional[Union[bool, Reference, "Schema"]] = None description: Optional[str] = None schema_format: Optional[str] = Field(default=None, alias="format") diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py index 04fe5fe31239..58a487dc7acb 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py @@ -1,6 +1,4 @@ -from typing import Dict, List - -SecurityRequirement = Dict[str, List[str]] +SecurityRequirement = dict[str, list[str]] """ Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py index 17d1cf39f7cf..6bc21766cd69 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py @@ -1,4 +1,4 @@ -from typing import Optional, Dict +from typing import Optional from pydantic import BaseModel, ConfigDict @@ -15,7 +15,7 @@ class Server(BaseModel): url: str description: Optional[str] = None - variables: Optional[Dict[str, ServerVariable]] = None + variables: Optional[dict[str, ServerVariable]] = None model_config = ConfigDict( extra="allow", json_schema_extra={ diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py index 2bbcba461dcd..8a869c40ebcb 100644 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py +++ b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py @@ -1,4 +1,4 @@ -from typing import Optional, List +from typing import Optional from pydantic import BaseModel, ConfigDict @@ -11,7 +11,7 @@ class ServerVariable(BaseModel): - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#serverVariableObject """ - enum: Optional[List[str]] = None + enum: Optional[list[str]] = None default: str description: Optional[str] = None model_config = ConfigDict(extra="allow") diff --git a/chaotic-openapi/chaotic_openapi/front/opa.yaml b/chaotic-openapi/chaotic_openapi/opa.yaml similarity index 100% rename from chaotic-openapi/chaotic_openapi/front/opa.yaml rename to chaotic-openapi/chaotic_openapi/opa.yaml From 270ccc2d9130efab7d6f7495e2b6a190b4e569f4 Mon Sep 17 00:00:00 2001 From: Artem Khromov Date: Mon, 20 Jan 2025 00:04:04 +0300 Subject: [PATCH 3/5] Better --- chaotic-openapi/chaotic_openapi/alo.py | 6 +- .../chaotic_openapi/front/__init__.py | 361 -- chaotic-openapi/chaotic_openapi/front/cli.py | 49 - .../chaotic_openapi/front/config.py | 123 - .../chaotic_openapi/front/parser/__init__.py | 5 - .../chaotic_openapi/front/parser/bodies.py | 146 - .../chaotic_openapi/front/parser/errors.py | 46 - .../chaotic_openapi/front/parser/openapi.py | 541 --- .../front/parser/properties/__init__.py | 459 --- .../front/parser/properties/any.py | 51 - .../front/parser/properties/boolean.py | 67 - .../front/parser/properties/const.py | 118 - .../front/parser/properties/date.py | 73 - .../front/parser/properties/datetime.py | 75 - .../front/parser/properties/enum_property.py | 209 - .../front/parser/properties/file.py | 67 - .../front/parser/properties/float.py | 71 - .../front/parser/properties/int.py | 73 - .../front/parser/properties/list_property.py | 160 - .../properties/literal_enum_property.py | 191 - .../parser/properties/merge_properties.py | 198 - .../front/parser/properties/model_property.py | 444 --- .../front/parser/properties/none.py | 61 - .../front/parser/properties/property.py | 41 - .../front/parser/properties/protocol.py | 187 - .../front/parser/properties/schemas.py | 242 -- .../front/parser/properties/string.py | 68 - .../front/parser/properties/union.py | 191 - .../front/parser/properties/uuid.py | 80 - .../chaotic_openapi/front/parser/responses.py | 150 - .../chaotic_openapi/front/schema/3.0.3.md | 3454 ---------------- .../chaotic_openapi/front/schema/3.1.0.md | 3468 ----------------- .../chaotic_openapi/front/schema/__init__.py | 31 - .../chaotic_openapi/front/schema/data_type.py | 18 - .../schema/openapi_schema_pydantic/LICENSE | 21 - .../schema/openapi_schema_pydantic/README.md | 42 - .../openapi_schema_pydantic/__init__.py | 83 - .../openapi_schema_pydantic/callback.py | 15 - .../openapi_schema_pydantic/components.py | 103 - .../schema/openapi_schema_pydantic/contact.py | 24 - .../openapi_schema_pydantic/discriminator.py | 36 - .../openapi_schema_pydantic/encoding.py | 41 - .../schema/openapi_schema_pydantic/example.py | 30 - .../external_documentation.py | 18 - .../schema/openapi_schema_pydantic/header.py | 33 - .../schema/openapi_schema_pydantic/info.py | 44 - .../schema/openapi_schema_pydantic/license.py | 21 - .../schema/openapi_schema_pydantic/link.py | 43 - .../openapi_schema_pydantic/media_type.py | 57 - .../openapi_schema_pydantic/oauth_flow.py | 34 - .../openapi_schema_pydantic/oauth_flows.py | 21 - .../openapi_schema_pydantic/open_api.py | 49 - .../openapi_schema_pydantic/operation.py | 89 - .../openapi_schema_pydantic/parameter.py | 89 - .../openapi_schema_pydantic/path_item.py | 76 - .../schema/openapi_schema_pydantic/paths.py | 13 - .../openapi_schema_pydantic/reference.py | 26 - .../openapi_schema_pydantic/request_body.py | 70 - .../openapi_schema_pydantic/response.py | 61 - .../openapi_schema_pydantic/responses.py | 23 - .../schema/openapi_schema_pydantic/schema.py | 208 - .../security_requirement.py | 18 - .../security_scheme.py | 49 - .../schema/openapi_schema_pydantic/server.py | 39 - .../server_variable.py | 17 - .../schema/openapi_schema_pydantic/tag.py | 23 - .../schema/openapi_schema_pydantic/xml.py | 32 - .../front/schema/parameter_location.py | 25 - .../chaotic_openapi/front/utils.py | 122 - 69 files changed, 3 insertions(+), 13216 deletions(-) delete mode 100644 chaotic-openapi/chaotic_openapi/front/__init__.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/cli.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/config.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/__init__.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/bodies.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/errors.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/openapi.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/any.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/const.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/date.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/file.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/float.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/int.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/none.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/property.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/string.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/union.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/parser/responses.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/3.0.3.md delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/3.1.0.md delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/__init__.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/data_type.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/LICENSE delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/__init__.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/contact.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/example.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/external_documentation.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/header.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/info.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/license.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flows.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/reference.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_scheme.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/tag.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/xml.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/schema/parameter_location.py delete mode 100644 chaotic-openapi/chaotic_openapi/front/utils.py diff --git a/chaotic-openapi/chaotic_openapi/alo.py b/chaotic-openapi/chaotic_openapi/alo.py index cc8c99c504cd..3b0fddb63db8 100644 --- a/chaotic-openapi/chaotic_openapi/alo.py +++ b/chaotic-openapi/chaotic_openapi/alo.py @@ -1,6 +1,6 @@ from typing import Any, Union, Dict -from front.parser.openapi import GeneratorData -from front.config import Config, ConfigFile, MetaType +from openapi_python_client.parser.openapi import GeneratorData +from openapi_python_client.config import Config, ConfigFile, MetaType from pathlib import Path def parse(data_dict: Dict[str, Any], config: Config): @@ -9,7 +9,7 @@ def parse(data_dict: Dict[str, Any], config: Config): def config(): return Config.from_sources(ConfigFile(), MetaType.NONE, Path("opa.yaml"), 'utf-8', False, None) -from front import _get_document +from openapi_python_client import _get_document conf = config() diff --git a/chaotic-openapi/chaotic_openapi/front/__init__.py b/chaotic-openapi/chaotic_openapi/front/__init__.py deleted file mode 100644 index 411caaa2d2a8..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/__init__.py +++ /dev/null @@ -1,361 +0,0 @@ -"""Generate modern Python clients from OpenAPI""" - -import json -import mimetypes -import shutil -import subprocess -from collections.abc import Sequence -from importlib.metadata import version -from pathlib import Path -from subprocess import CalledProcessError -from typing import Any, Optional, Union, List, Dict - -import httpcore -import httpx -from jinja2 import BaseLoader, ChoiceLoader, Environment, FileSystemLoader, PackageLoader -from ruamel.yaml import YAML -from ruamel.yaml.error import YAMLError - -from . import utils - -from .config import Config, ConfigFile, MetaType -from .parser import GeneratorData, import_string_from_class -from .parser.errors import ErrorLevel, GeneratorError -from .parser.properties import LiteralEnumProperty - -# __version__ = version(__package__) - - -TEMPLATE_FILTERS = { - "snakecase": utils.snake_case, - "kebabcase": utils.kebab_case, - "pascalcase": utils.pascal_case, - "any": any, -} - - -class Project: - """Represents a Python project (the top level file-tree) to generate""" - - def __init__( - self, - *, - openapi: GeneratorData, - config: Config, - custom_template_path: Optional[Path] = None, - ) -> None: - self.openapi: GeneratorData = openapi - self.config = config - - package_loader = PackageLoader(__package__) - loader: BaseLoader - if custom_template_path is not None: - loader = ChoiceLoader( - [ - FileSystemLoader(str(custom_template_path)), - package_loader, - ] - ) - else: - loader = package_loader - self.env: Environment = Environment( - loader=loader, - trim_blocks=True, - lstrip_blocks=True, - extensions=["jinja2.ext.loopcontrols"], - keep_trailing_newline=True, - ) - - self.project_name: str = config.project_name_override or f"{utils.kebab_case(openapi.title).lower()}-client" - self.package_name: str = config.package_name_override or self.project_name.replace("-", "_") - self.project_dir: Path # Where the generated code will be placed - self.package_dir: Path # Where the generated Python module will be placed (same as project_dir if no meta) - - if config.output_path is not None: - self.project_dir = config.output_path - elif config.meta_type == MetaType.NONE: - self.project_dir = Path.cwd() / self.package_name - else: - self.project_dir = Path.cwd() / self.project_name - - if config.meta_type == MetaType.NONE: - self.package_dir = self.project_dir - else: - self.package_dir = self.project_dir / self.package_name - - self.package_description: str = utils.remove_string_escapes( - f"A client library for accessing {self.openapi.title}" - ) - self.version: str = config.package_version_override or openapi.version - - self.env.filters.update(TEMPLATE_FILTERS) - self.env.globals.update( - utils=utils, - python_identifier=lambda x: utils.PythonIdentifier(x, config.field_prefix), - class_name=lambda x: utils.ClassName(x, config.field_prefix), - package_name=self.package_name, - package_dir=self.package_dir, - package_description=self.package_description, - package_version=self.version, - project_name=self.project_name, - project_dir=self.project_dir, - openapi=self.openapi, - endpoint_collections_by_tag=self.openapi.endpoint_collections_by_tag, - ) - self.errors: List[GeneratorError] = [] - - def build(self) -> Sequence[GeneratorError]: - """Create the project from templates""" - - print(f"Generating {self.project_dir}") - try: - self.project_dir.mkdir() - except FileExistsError: - if not self.config.overwrite: - return [GeneratorError(detail="Directory already exists. Delete it or use the --overwrite option.")] - self._create_package() - self._build_metadata() - self._build_models() - self._build_api() - self._run_post_hooks() - return self._get_errors() - - def _run_post_hooks(self) -> None: - for command in self.config.post_hooks: - self._run_command(command) - - def _run_command(self, cmd: str) -> None: - cmd_name = cmd.split(" ")[0] - command_exists = shutil.which(cmd_name) - if not command_exists: - self.errors.append( - GeneratorError( - level=ErrorLevel.WARNING, header="Skipping Integration", detail=f"{cmd_name} is not in PATH" - ) - ) - return - try: - cwd = self.project_dir - subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, check=True) - except CalledProcessError as err: - self.errors.append( - GeneratorError( - level=ErrorLevel.ERROR, - header=f"{cmd_name} failed", - detail=err.stderr.decode() or err.output.decode(), - ) - ) - - def _get_errors(self) -> List[GeneratorError]: - errors: List[GeneratorError] = [] - for collection in self.openapi.endpoint_collections_by_tag.values(): - errors.extend(collection.parse_errors) - errors.extend(self.openapi.errors) - errors.extend(self.errors) - return errors - - def _create_package(self) -> None: - if self.package_dir != self.project_dir: - self.package_dir.mkdir(exist_ok=True) - # Package __init__.py - package_init = self.package_dir / "__init__.py" - - package_init_template = self.env.get_template("package_init.py.jinja") - package_init.write_text(package_init_template.render(), encoding=self.config.file_encoding) - - if self.config.meta_type != MetaType.NONE: - pytyped = self.package_dir / "py.typed" - pytyped.write_text("# Marker file for PEP 561", encoding=self.config.file_encoding) - - types_template = self.env.get_template("types.py.jinja") - types_path = self.package_dir / "types.py" - types_path.write_text(types_template.render(), encoding=self.config.file_encoding) - - def _build_metadata(self) -> None: - if self.config.meta_type == MetaType.NONE: - return - - self._build_pyproject_toml() - if self.config.meta_type == MetaType.SETUP: - self._build_setup_py() - - # README.md - readme = self.project_dir / "README.md" - readme_template = self.env.get_template("README.md.jinja") - readme.write_text( - readme_template.render(poetry=self.config.meta_type == MetaType.POETRY), - encoding=self.config.file_encoding, - ) - - # .gitignore - git_ignore_path = self.project_dir / ".gitignore" - git_ignore_template = self.env.get_template(".gitignore.jinja") - git_ignore_path.write_text(git_ignore_template.render(), encoding=self.config.file_encoding) - - def _build_pyproject_toml(self) -> None: - template = "pyproject.toml.jinja" - pyproject_template = self.env.get_template(template) - pyproject_path = self.project_dir / "pyproject.toml" - pyproject_path.write_text( - pyproject_template.render(meta=self.config.meta_type), - encoding=self.config.file_encoding, - ) - - def _build_setup_py(self) -> None: - template = self.env.get_template("setup.py.jinja") - path = self.project_dir / "setup.py" - path.write_text( - template.render(), - encoding=self.config.file_encoding, - ) - - def _build_models(self) -> None: - # Generate models - models_dir = self.package_dir / "models" - shutil.rmtree(models_dir, ignore_errors=True) - models_dir.mkdir() - models_init = models_dir / "__init__.py" - imports = [] - alls = [] - - model_template = self.env.get_template("model.py.jinja") - for model in self.openapi.models: - module_path = models_dir / f"{model.class_info.module_name}.py" - module_path.write_text(model_template.render(model=model), encoding=self.config.file_encoding) - imports.append(import_string_from_class(model.class_info)) - alls.append(model.class_info.name) - - # Generate enums - str_enum_template = self.env.get_template("str_enum.py.jinja") - int_enum_template = self.env.get_template("int_enum.py.jinja") - literal_enum_template = self.env.get_template("literal_enum.py.jinja") - for enum in self.openapi.enums: - module_path = models_dir / f"{enum.class_info.module_name}.py" - if isinstance(enum, LiteralEnumProperty): - module_path.write_text(literal_enum_template.render(enum=enum), encoding=self.config.file_encoding) - elif enum.value_type is int: - module_path.write_text(int_enum_template.render(enum=enum), encoding=self.config.file_encoding) - else: - module_path.write_text(str_enum_template.render(enum=enum), encoding=self.config.file_encoding) - imports.append(import_string_from_class(enum.class_info)) - alls.append(enum.class_info.name) - - models_init_template = self.env.get_template("models_init.py.jinja") - models_init.write_text( - models_init_template.render(imports=imports, alls=alls), encoding=self.config.file_encoding - ) - - def _build_api(self) -> None: - # Generate Client - client_path = self.package_dir / "client.py" - client_template = self.env.get_template("client.py.jinja") - client_path.write_text(client_template.render(), encoding=self.config.file_encoding) - - # Generate included Errors - errors_path = self.package_dir / "errors.py" - errors_template = self.env.get_template("errors.py.jinja") - errors_path.write_text(errors_template.render(), encoding=self.config.file_encoding) - - # Generate endpoints - api_dir = self.package_dir / "api" - shutil.rmtree(api_dir, ignore_errors=True) - api_dir.mkdir() - api_init_path = api_dir / "__init__.py" - api_init_template = self.env.get_template("api_init.py.jinja") - api_init_path.write_text(api_init_template.render(), encoding=self.config.file_encoding) - - endpoint_collections_by_tag = self.openapi.endpoint_collections_by_tag - endpoint_template = self.env.get_template( - "endpoint_module.py.jinja", globals={"isbool": lambda obj: obj.get_base_type_string() == "bool"} - ) - for tag, collection in endpoint_collections_by_tag.items(): - tag_dir = api_dir / tag - tag_dir.mkdir() - - endpoint_init_path = tag_dir / "__init__.py" - endpoint_init_template = self.env.get_template("endpoint_init.py.jinja") - endpoint_init_path.write_text( - endpoint_init_template.render(endpoint_collection=collection), - encoding=self.config.file_encoding, - ) - - for endpoint in collection.endpoints: - module_path = tag_dir / f"{utils.PythonIdentifier(endpoint.name, self.config.field_prefix)}.py" - module_path.write_text( - endpoint_template.render( - endpoint=endpoint, - ), - encoding=self.config.file_encoding, - ) - - -def _get_project_for_url_or_path( - config: Config, - custom_template_path: Optional[Path] = None, -) -> Union[Project, GeneratorError]: - data_dict = _get_document(source=config.document_source, timeout=config.http_timeout) - if isinstance(data_dict, GeneratorError): - return data_dict - openapi = GeneratorData.from_dict(data_dict, config=config) - if isinstance(openapi, GeneratorError): - return openapi - return Project( - openapi=openapi, - custom_template_path=custom_template_path, - config=config, - ) - - -def generate( - *, - config: Config, - custom_template_path: Optional[Path] = None, -) -> Sequence[GeneratorError]: - """ - Generate the client library - - Returns: - A list containing any errors encountered when generating. - """ - project = _get_project_for_url_or_path( - custom_template_path=custom_template_path, - config=config, - ) - if isinstance(project, GeneratorError): - return [project] - return project.build() - - -def _load_yaml_or_json(data: bytes, content_type: Optional[str]) -> Union[Dict[str, Any], GeneratorError]: - if content_type == "application/json": - try: - return json.loads(data.decode()) - except ValueError as err: - return GeneratorError(header=f"Invalid JSON from provided source: {err}") - else: - try: - yaml = YAML(typ="safe") - return yaml.load(data) - except YAMLError as err: - return GeneratorError(header=f"Invalid YAML from provided source: {err}") - - -def _get_document(*, source: Union[str, Path], timeout: int) -> Union[Dict[str, Any], GeneratorError]: - yaml_bytes: bytes - content_type: Optional[str] - if isinstance(source, str): - try: - response = httpx.get(source, timeout=timeout) - yaml_bytes = response.content - if "content-type" in response.headers: - content_type = response.headers["content-type"].split(";")[0] - else: # pragma: no cover - content_type = mimetypes.guess_type(source, strict=True)[0] - - except (httpx.HTTPError, httpcore.NetworkError): - return GeneratorError(header="Could not get OpenAPI document from provided URL") - else: - yaml_bytes = source.read_bytes() - content_type = mimetypes.guess_type(source.absolute().as_uri(), strict=True)[0] - - return _load_yaml_or_json(yaml_bytes, content_type) diff --git a/chaotic-openapi/chaotic_openapi/front/cli.py b/chaotic-openapi/chaotic_openapi/front/cli.py deleted file mode 100644 index 6cfe3ba68bf1..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/cli.py +++ /dev/null @@ -1,49 +0,0 @@ -import codecs -from collections.abc import Sequence -from pathlib import Path -from pprint import pformat -from typing import Optional, Union - -import typer - -from openapi_python_client import MetaType -from openapi_python_client.config import Config, ConfigFile -from openapi_python_client.parser.errors import ErrorLevel, GeneratorError, ParseError - -def _process_config( - *, - url: Optional[str], - path: Optional[Path], - config_path: Optional[Path], - meta_type: MetaType, - file_encoding: str, - overwrite: bool, - output_path: Optional[Path], -) -> Config: - source: Union[Path, str] - if url and not path: - source = url - elif path and not url: - source = path - elif url and path: - typer.secho("Provide either --url or --path, not both", fg=typer.colors.RED) - raise typer.Exit(code=1) - else: - typer.secho("You must either provide --url or --path", fg=typer.colors.RED) - raise typer.Exit(code=1) - - try: - codecs.getencoder(file_encoding) - except LookupError as err: - typer.secho(f"Unknown encoding : {file_encoding}", fg=typer.colors.RED) - raise typer.Exit(code=1) from err - - if not config_path: - config_file = ConfigFile() - else: - try: - config_file = ConfigFile.load_from_path(path=config_path) - except Exception as err: - raise typer.BadParameter("Unable to parse config") from err - - return Config.from_sources(config_file, meta_type, source, file_encoding, overwrite, output_path=output_path) diff --git a/chaotic-openapi/chaotic_openapi/front/config.py b/chaotic-openapi/chaotic_openapi/front/config.py deleted file mode 100644 index 82b4e05640a5..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/config.py +++ /dev/null @@ -1,123 +0,0 @@ -import json -import mimetypes -from enum import Enum -from pathlib import Path -from typing import Optional, Union, Dict, List - -from attr import define -from pydantic import BaseModel -from ruamel.yaml import YAML - - -class ClassOverride(BaseModel): - """An override of a single generated class. - - See https://github.com/openapi-generators/openapi-python-client#class_overrides - """ - - class_name: Optional[str] = None - module_name: Optional[str] = None - - -class MetaType(str, Enum): - """The types of metadata supported for project generation.""" - - NONE = "none" - POETRY = "poetry" - SETUP = "setup" - PDM = "pdm" - - -class ConfigFile(BaseModel): - """Contains any configurable values passed via a config file. - - See https://github.com/openapi-generators/openapi-python-client#configuration - """ - - class_overrides: Optional[Dict[str, ClassOverride]] = None - content_type_overrides: Optional[Dict[str, str]] = None - project_name_override: Optional[str] = None - package_name_override: Optional[str] = None - package_version_override: Optional[str] = None - use_path_prefixes_for_title_model_names: bool = True - post_hooks: Optional[List[str]] = None - field_prefix: str = "field_" - generate_all_tags: bool = False - http_timeout: int = 5 - literal_enums: bool = False - - @staticmethod - def load_from_path(path: Path) -> "ConfigFile": - """Creates a Config from provided JSON or YAML file and sets a bunch of globals from it""" - mime = mimetypes.guess_type(path.absolute().as_uri(), strict=True)[0] - if mime == "application/json": - config_data = json.loads(path.read_text()) - else: - yaml = YAML(typ="safe") - config_data = yaml.load(path) - config = ConfigFile(**config_data) - return config - - -@define -class Config: - """Contains all the config values for the generator, from files, defaults, and CLI arguments.""" - - meta_type: MetaType - class_overrides: Dict[str, ClassOverride] - project_name_override: Optional[str] - package_name_override: Optional[str] - package_version_override: Optional[str] - use_path_prefixes_for_title_model_names: bool - post_hooks: List[str] - field_prefix: str - generate_all_tags: bool - http_timeout: int - literal_enums: bool - document_source: Union[Path, str] - file_encoding: str - content_type_overrides: Dict[str, str] - overwrite: bool - output_path: Optional[Path] - - @staticmethod - def from_sources( - config_file: ConfigFile, - meta_type: MetaType, - document_source: Union[Path, str], - file_encoding: str, - overwrite: bool, - output_path: Optional[Path], - ) -> "Config": - if config_file.post_hooks is not None: - post_hooks = config_file.post_hooks - elif meta_type == MetaType.NONE: - post_hooks = [ - "ruff check . --fix --extend-select=I", - "ruff format .", - ] - else: - post_hooks = [ - "ruff check --fix .", - "ruff format .", - ] - - config = Config( - meta_type=meta_type, - class_overrides=config_file.class_overrides or {}, - content_type_overrides=config_file.content_type_overrides or {}, - project_name_override=config_file.project_name_override, - package_name_override=config_file.package_name_override, - package_version_override=config_file.package_version_override, - use_path_prefixes_for_title_model_names=config_file.use_path_prefixes_for_title_model_names, - post_hooks=post_hooks, - field_prefix=config_file.field_prefix, - generate_all_tags=config_file.generate_all_tags, - http_timeout=config_file.http_timeout, - literal_enums=config_file.literal_enums, - document_source=document_source, - file_encoding=file_encoding, - overwrite=overwrite, - output_path=output_path, - ) - return config diff --git a/chaotic-openapi/chaotic_openapi/front/parser/__init__.py b/chaotic-openapi/chaotic_openapi/front/parser/__init__.py deleted file mode 100644 index 9cdeb36fd76f..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Classes representing the data in the OpenAPI schema""" - -__all__ = ["GeneratorData", "import_string_from_class"] - -from .openapi import GeneratorData, import_string_from_class diff --git a/chaotic-openapi/chaotic_openapi/front/parser/bodies.py b/chaotic-openapi/chaotic_openapi/front/parser/bodies.py deleted file mode 100644 index 514b6f0f7cd8..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/bodies.py +++ /dev/null @@ -1,146 +0,0 @@ -import sys -from typing import Union - -import attr - -from .properties import ( - ModelProperty, - Property, - Schemas, - property_from_data, -) - -from .. import schema as oai -from ..config import Config -from ..utils import get_content_type -from .errors import ErrorLevel, ParseError - -if sys.version_info >= (3, 11): - from enum import StrEnum - - class BodyType(StrEnum): - JSON = "json" - DATA = "data" - FILES = "files" - CONTENT = "content" -else: - from enum import Enum - - class BodyType(str, Enum): - JSON = "json" - DATA = "data" - FILES = "files" - CONTENT = "content" - - -@attr.define -class Body: - content_type: str - prop: Property - body_type: BodyType - - -def body_from_data( - *, - data: oai.Operation, - schemas: Schemas, - request_bodies: dict[str, Union[oai.RequestBody, oai.Reference]], - config: Config, - endpoint_name: str, -) -> tuple[list[Union[Body, ParseError]], Schemas]: - """Adds form or JSON body to Endpoint if included in data""" - body = _resolve_reference(data.request_body, request_bodies) - if isinstance(body, ParseError): - return [body], schemas - if body is None: - return [], schemas - - bodies: list[Union[Body, ParseError]] = [] - body_content = body.content - prefix_type_names = len(body_content) > 1 - - for content_type, media_type in body_content.items(): - simplified_content_type = get_content_type(content_type, config) - if simplified_content_type is None: - bodies.append( - ParseError( - detail="Invalid content type", - data=body, - level=ErrorLevel.WARNING, - ) - ) - continue - media_type_schema = media_type.media_type_schema - if media_type_schema is None: - bodies.append( - ParseError( - detail="Missing schema", - data=body, - level=ErrorLevel.WARNING, - ) - ) - continue - if simplified_content_type == "application/x-www-form-urlencoded": - body_type = BodyType.DATA - elif simplified_content_type == "multipart/form-data": - body_type = BodyType.FILES - elif simplified_content_type == "application/octet-stream": - body_type = BodyType.CONTENT - elif simplified_content_type == "application/json" or simplified_content_type.endswith("+json"): - body_type = BodyType.JSON - else: - bodies.append( - ParseError( - detail=f"Unsupported content type {simplified_content_type}", - data=body, - level=ErrorLevel.WARNING, - ) - ) - continue - prop, schemas = property_from_data( - name="body", - required=True, - data=media_type_schema, - schemas=schemas, - parent_name=f"{endpoint_name}_{body_type}" if prefix_type_names else endpoint_name, - config=config, - ) - if isinstance(prop, ParseError): - bodies.append(prop) - continue - if isinstance(prop, ModelProperty) and body_type == BodyType.FILES: - # Regardless of if we just made this property or found it, it now needs the `to_multipart` method - prop = attr.evolve(prop, is_multipart_body=True) - schemas = attr.evolve( - schemas, - classes_by_name={ - **schemas.classes_by_name, - prop.class_info.name: prop, - }, - models_to_process=[*schemas.models_to_process, prop], - ) - bodies.append( - Body( - content_type=content_type, - prop=prop, - body_type=body_type, - ) - ) - - return bodies, schemas - - -def _resolve_reference( - body: Union[oai.RequestBody, oai.Reference, None], request_bodies: dict[str, Union[oai.RequestBody, oai.Reference]] -) -> Union[oai.RequestBody, ParseError, None]: - if body is None: - return None - references_seen = [] - while isinstance(body, oai.Reference) and body.ref not in references_seen: - references_seen.append(body.ref) - body = request_bodies.get(body.ref.split("/")[-1]) - if isinstance(body, oai.Reference): - return ParseError(detail="Circular $ref in request body", data=body) - if body is None and references_seen: - return ParseError(detail=f"Could not resolve $ref {references_seen[-1]} in request body") - return body diff --git a/chaotic-openapi/chaotic_openapi/front/parser/errors.py b/chaotic-openapi/chaotic_openapi/front/parser/errors.py deleted file mode 100644 index 36322f0cfbc5..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/errors.py +++ /dev/null @@ -1,46 +0,0 @@ -from dataclasses import dataclass -from enum import Enum -from typing import Optional - -__all__ = ["ErrorLevel", "GeneratorError", "ParameterError", "ParseError", "PropertyError"] - -from pydantic import BaseModel - - -class ErrorLevel(Enum): - """The level of an error""" - - WARNING = "WARNING" # Client is still generated but missing some pieces - ERROR = "ERROR" # Client could not be generated - - -@dataclass -class GeneratorError: - """Base data struct containing info on an error that occurred""" - - detail: Optional[str] = None - level: ErrorLevel = ErrorLevel.ERROR - header: str = "Unable to generate the client" - - -@dataclass -class ParseError(GeneratorError): - """An error raised when there's a problem parsing an OpenAPI document""" - - level: ErrorLevel = ErrorLevel.WARNING - data: Optional[BaseModel] = None - header: str = "Unable to parse this part of your OpenAPI document: " - - -@dataclass -class PropertyError(ParseError): - """Error raised when there's a problem creating a Property""" - - header = "Problem creating a Property: " - - -@dataclass -class ParameterError(ParseError): - """Error raised when there's a problem creating a Parameter.""" - - header = "Problem creating a Parameter: " diff --git a/chaotic-openapi/chaotic_openapi/front/parser/openapi.py b/chaotic-openapi/chaotic_openapi/front/parser/openapi.py deleted file mode 100644 index 117b2ee30c5a..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/openapi.py +++ /dev/null @@ -1,541 +0,0 @@ -import re -from collections.abc import Iterator -from copy import deepcopy -from dataclasses import dataclass, field -from http import HTTPStatus -from typing import Any, Optional, Protocol, Union - -from pydantic import ValidationError - -from .. import schema as oai -from .. import utils -from ..config import Config -from ..utils import PythonIdentifier -from .bodies import Body, body_from_data -from .errors import GeneratorError, ParseError, PropertyError -from .properties import ( - Class, - EnumProperty, - LiteralEnumProperty, - ModelProperty, - Parameters, - Property, - Schemas, - build_parameters, - build_schemas, - property_from_data, -) -from .properties.schemas import parameter_from_reference -from .responses import Response, response_from_data - -_PATH_PARAM_REGEX = re.compile("{([a-zA-Z_-][a-zA-Z0-9_-]*)}") - - -def import_string_from_class(class_: Class, prefix: str = "") -> str: - """Create a string which is used to import a reference""" - return f"from {prefix}.{class_.module_name} import {class_.name}" - - -@dataclass -class EndpointCollection: - """A bunch of endpoints grouped under a tag that will become a module""" - - tag: str - endpoints: list["Endpoint"] = field(default_factory=list) - parse_errors: list[ParseError] = field(default_factory=list) - - @staticmethod - def from_data( - *, - data: dict[str, oai.PathItem], - schemas: Schemas, - parameters: Parameters, - request_bodies: dict[str, Union[oai.RequestBody, oai.Reference]], - config: Config, - ) -> tuple[dict[utils.PythonIdentifier, "EndpointCollection"], Schemas, Parameters]: - """Parse the openapi paths data to get EndpointCollections by tag""" - endpoints_by_tag: dict[utils.PythonIdentifier, EndpointCollection] = {} - - methods = ["get", "put", "post", "delete", "options", "head", "patch", "trace"] - - for path, path_data in data.items(): - for method in methods: - operation: Optional[oai.Operation] = getattr(path_data, method) - if operation is None: - continue - - tags = [utils.PythonIdentifier(value=tag, prefix="tag") for tag in operation.tags or ["default"]] - if not config.generate_all_tags: - tags = tags[:1] - - collections = [endpoints_by_tag.setdefault(tag, EndpointCollection(tag=tag)) for tag in tags] - - endpoint, schemas, parameters = Endpoint.from_data( - data=operation, - path=path, - method=method, - tags=tags, - schemas=schemas, - parameters=parameters, - request_bodies=request_bodies, - config=config, - ) - # Add `PathItem` parameters - if not isinstance(endpoint, ParseError): - endpoint, schemas, parameters = Endpoint.add_parameters( - endpoint=endpoint, - data=path_data, - schemas=schemas, - parameters=parameters, - config=config, - ) - if not isinstance(endpoint, ParseError): - endpoint = Endpoint.sort_parameters(endpoint=endpoint) - if isinstance(endpoint, ParseError): - endpoint.header = f"WARNING parsing {method.upper()} {path} within {'/'.join(tags)}. Endpoint will not be generated." - for collection in collections: - collection.parse_errors.append(endpoint) - continue - for error in endpoint.errors: - error.header = f"WARNING parsing {method.upper()} {path} within {'/'.join(tags)}." - for collection in collections: - collection.parse_errors.append(error) - for collection in collections: - collection.endpoints.append(endpoint) - - return endpoints_by_tag, schemas, parameters - - -def generate_operation_id(*, path: str, method: str) -> str: - """Generate an operationId from a path""" - clean_path = path.replace("{", "").replace("}", "").replace("/", "_") - if clean_path.startswith("_"): - clean_path = clean_path[1:] - if clean_path.endswith("_"): - clean_path = clean_path[:-1] - return f"{method}_{clean_path}" - - -models_relative_prefix: str = "..." - - -class RequestBodyParser(Protocol): - __name__: str = "RequestBodyParser" - - def __call__( - self, *, body: oai.RequestBody, schemas: Schemas, parent_name: str, config: Config - ) -> tuple[Union[Property, PropertyError, None], Schemas]: ... # pragma: no cover - - -@dataclass -class Endpoint: - """ - Describes a single endpoint on the server - """ - - path: str - method: str - description: Optional[str] - name: str - requires_security: bool - tags: list[PythonIdentifier] - summary: Optional[str] = "" - relative_imports: set[str] = field(default_factory=set) - query_parameters: list[Property] = field(default_factory=list) - path_parameters: list[Property] = field(default_factory=list) - header_parameters: list[Property] = field(default_factory=list) - cookie_parameters: list[Property] = field(default_factory=list) - responses: list[Response] = field(default_factory=list) - bodies: list[Body] = field(default_factory=list) - errors: list[ParseError] = field(default_factory=list) - - @staticmethod - def _add_responses( - *, endpoint: "Endpoint", data: oai.Responses, schemas: Schemas, config: Config - ) -> tuple["Endpoint", Schemas]: - endpoint = deepcopy(endpoint) - for code, response_data in data.items(): - status_code: HTTPStatus - try: - status_code = HTTPStatus(int(code)) - except ValueError: - endpoint.errors.append( - ParseError( - detail=( - f"Invalid response status code {code} (not a valid HTTP " - f"status code), response will be omitted from generated " - f"client" - ) - ) - ) - continue - - response, schemas = response_from_data( - status_code=status_code, - data=response_data, - schemas=schemas, - parent_name=endpoint.name, - config=config, - ) - if isinstance(response, ParseError): - detail_suffix = "" if response.detail is None else f" ({response.detail})" - endpoint.errors.append( - ParseError( - detail=( - f"Cannot parse response for status code {status_code}{detail_suffix}, " - f"response will be omitted from generated client" - ), - data=response.data, - ) - ) - continue - - # No reasons to use lazy imports in endpoints, so add lazy imports to relative here. - endpoint.relative_imports |= response.prop.get_lazy_imports(prefix=models_relative_prefix) - endpoint.relative_imports |= response.prop.get_imports(prefix=models_relative_prefix) - endpoint.responses.append(response) - return endpoint, schemas - - @staticmethod - def add_parameters( - *, - endpoint: "Endpoint", - data: Union[oai.Operation, oai.PathItem], - schemas: Schemas, - parameters: Parameters, - config: Config, - ) -> tuple[Union["Endpoint", ParseError], Schemas, Parameters]: - """Process the defined `parameters` for an Endpoint. - - Any existing parameters will be ignored, so earlier instances of a parameter take precedence. PathItem - parameters should therefore be added __after__ operation parameters. - - Args: - endpoint: The endpoint to add parameters to. - data: The Operation or PathItem to add parameters from. - schemas: The cumulative Schemas of processing so far which should contain details for any references. - parameters: The cumulative Parameters of processing so far which should contain details for any references. - config: User-provided config for overrides within parameters. - - Returns: - `(result, schemas, parameters)` where `result` is either an updated Endpoint containing the parameters or a - ParseError describing what went wrong. `schemas` is an updated version of the `schemas` input, adding any - new enums or classes. `parameters` is an updated version of the `parameters` input, adding new parameters. - - See Also: - - https://swagger.io/docs/specification/describing-parameters/ - - https://swagger.io/docs/specification/paths-and-operations/ - """ - # There isn't much value in breaking down this function further other than to satisfy the linter. - - if data.parameters is None: - return endpoint, schemas, parameters - - endpoint = deepcopy(endpoint) - - unique_parameters: set[tuple[str, oai.ParameterLocation]] = set() - parameters_by_location: dict[str, list[Property]] = { - oai.ParameterLocation.QUERY: endpoint.query_parameters, - oai.ParameterLocation.PATH: endpoint.path_parameters, - oai.ParameterLocation.HEADER: endpoint.header_parameters, - oai.ParameterLocation.COOKIE: endpoint.cookie_parameters, - } - - for param in data.parameters: - # Obtain the parameter from the reference or just the parameter itself - param_or_error = parameter_from_reference(param=param, parameters=parameters) - if isinstance(param_or_error, ParseError): - return param_or_error, schemas, parameters - param = param_or_error # noqa: PLW2901 - - if param.param_schema is None: - continue - - unique_param = (param.name, param.param_in) - if unique_param in unique_parameters: - return ( - ParseError( - data=data, - detail=( - "Parameters MUST NOT contain duplicates. " - "A unique parameter is defined by a combination of a name and location. " - f"Duplicated parameters named `{param.name}` detected in `{param.param_in}`." - ), - ), - schemas, - parameters, - ) - - unique_parameters.add(unique_param) - - if any( - other_param for other_param in parameters_by_location[param.param_in] if other_param.name == param.name - ): - # Defined at the operation level, ignore it here - continue - - prop, new_schemas = property_from_data( - name=param.name, - required=param.required, - data=param.param_schema, - schemas=schemas, - parent_name=endpoint.name, - config=config, - ) - - if isinstance(prop, ParseError): - return ( - ParseError( - detail=f"cannot parse parameter of endpoint {endpoint.name}: {prop.detail}", - data=prop.data, - ), - schemas, - parameters, - ) - - schemas = new_schemas - - location_error = prop.validate_location(param.param_in) - if location_error is not None: - location_error.data = param - return location_error, schemas, parameters - - # No reasons to use lazy imports in endpoints, so add lazy imports to relative here. - endpoint.relative_imports.update(prop.get_lazy_imports(prefix=models_relative_prefix)) - endpoint.relative_imports.update(prop.get_imports(prefix=models_relative_prefix)) - parameters_by_location[param.param_in].append(prop) - - return endpoint._check_parameters_for_conflicts(config=config), schemas, parameters - - def _check_parameters_for_conflicts( - self, - *, - config: Config, - previously_modified_params: Optional[set[tuple[oai.ParameterLocation, str]]] = None, - ) -> Union["Endpoint", ParseError]: - """Check for conflicting parameters - - For parameters that have the same python_name but are in different locations, append the location to the - python_name. For parameters that have the same name but are in the same location, use their raw name without - snake casing instead. - - Function stops when there's a conflict that can't be resolved or all parameters are guaranteed to have a - unique python_name. - """ - modified_params = previously_modified_params or set() - used_python_names: dict[PythonIdentifier, tuple[oai.ParameterLocation, Property]] = {} - reserved_names = ["client", "url"] - for parameter in self.iter_all_parameters(): - location, prop = parameter - - if prop.python_name in reserved_names: - prop.set_python_name(new_name=f"{prop.python_name}_{location}", config=config) - modified_params.add((location, prop.name)) - continue - - conflicting = used_python_names.pop(prop.python_name, None) - if conflicting is None: - used_python_names[prop.python_name] = parameter - continue - conflicting_location, conflicting_prop = conflicting - if (conflicting_location, conflicting_prop.name) in modified_params or ( - location, - prop.name, - ) in modified_params: - return ParseError( - detail=f"Parameters with same Python identifier {conflicting_prop.python_name} detected", - ) - - if location != conflicting_location: - conflicting_prop.set_python_name( - new_name=f"{conflicting_prop.python_name}_{conflicting_location}", config=config - ) - prop.set_python_name(new_name=f"{prop.python_name}_{location}", config=config) - elif conflicting_prop.name != prop.name: # Use the name to differentiate - conflicting_prop.set_python_name(new_name=conflicting_prop.name, config=config, skip_snake_case=True) - prop.set_python_name(new_name=prop.name, config=config, skip_snake_case=True) - - modified_params.add((location, conflicting_prop.name)) - modified_params.add((conflicting_location, conflicting_prop.name)) - used_python_names[prop.python_name] = parameter - used_python_names[conflicting_prop.python_name] = conflicting - - if len(modified_params) > 0 and modified_params != previously_modified_params: - return self._check_parameters_for_conflicts(config=config, previously_modified_params=modified_params) - return self - - @staticmethod - def sort_parameters(*, endpoint: "Endpoint") -> Union["Endpoint", ParseError]: - """ - Sorts the path parameters of an `endpoint` so that they match the order declared in `endpoint.path`. - - Args: - endpoint: The endpoint to sort the parameters of. - - Returns: - Either an updated `endpoint` with sorted path parameters or a `ParseError` if something was wrong with - the path parameters and they could not be sorted. - """ - endpoint = deepcopy(endpoint) - parameters_from_path = re.findall(_PATH_PARAM_REGEX, endpoint.path) - try: - endpoint.path_parameters.sort( - key=lambda param: parameters_from_path.index(param.name), - ) - except ValueError: - pass # We're going to catch the difference down below - - if parameters_from_path != [param.name for param in endpoint.path_parameters]: - return ParseError( - detail=f"Incorrect path templating for {endpoint.path} (Path parameters do not match with path)", - ) - for parameter in endpoint.path_parameters: - endpoint.path = endpoint.path.replace(f"{{{parameter.name}}}", f"{{{parameter.python_name}}}") - return endpoint - - @staticmethod - def from_data( - *, - data: oai.Operation, - path: str, - method: str, - tags: list[PythonIdentifier], - schemas: Schemas, - parameters: Parameters, - request_bodies: dict[str, Union[oai.RequestBody, oai.Reference]], - config: Config, - ) -> tuple[Union["Endpoint", ParseError], Schemas, Parameters]: - """Construct an endpoint from the OpenAPI data""" - - if data.operationId is None: - name = generate_operation_id(path=path, method=method) - else: - name = data.operationId - - endpoint = Endpoint( - path=path, - method=method, - summary=utils.remove_string_escapes(data.summary) if data.summary else "", - description=utils.remove_string_escapes(data.description) if data.description else "", - name=name, - requires_security=bool(data.security), - tags=tags, - ) - - result, schemas, parameters = Endpoint.add_parameters( - endpoint=endpoint, - data=data, - schemas=schemas, - parameters=parameters, - config=config, - ) - if isinstance(result, ParseError): - return result, schemas, parameters - result, schemas = Endpoint._add_responses(endpoint=result, data=data.responses, schemas=schemas, config=config) - if isinstance(result, ParseError): - return result, schemas, parameters - bodies, schemas = body_from_data( - data=data, schemas=schemas, config=config, endpoint_name=result.name, request_bodies=request_bodies - ) - body_errors = [] - for body in bodies: - if isinstance(body, ParseError): - body_errors.append(body) - continue - result.bodies.append(body) - result.relative_imports.update(body.prop.get_imports(prefix=models_relative_prefix)) - result.relative_imports.update(body.prop.get_lazy_imports(prefix=models_relative_prefix)) - if len(result.bodies) > 0: - result.errors.extend(body_errors) - elif len(body_errors) > 0: - return ( - ParseError( - header="Endpoint requires a body, but none were parseable.", - detail="\n".join(error.detail or "" for error in body_errors), - ), - schemas, - parameters, - ) - - return result, schemas, parameters - - def response_type(self) -> str: - """Get the Python type of any response from this endpoint""" - types = sorted({response.prop.get_type_string(quoted=False) for response in self.responses}) - if len(types) == 0: - return "Any" - if len(types) == 1: - return self.responses[0].prop.get_type_string(quoted=False) - return f"Union[{', '.join(types)}]" - - def iter_all_parameters(self) -> Iterator[tuple[oai.ParameterLocation, Property]]: - """Iterate through all the parameters of this endpoint""" - yield from ((oai.ParameterLocation.PATH, param) for param in self.path_parameters) - yield from ((oai.ParameterLocation.QUERY, param) for param in self.query_parameters) - yield from ((oai.ParameterLocation.HEADER, param) for param in self.header_parameters) - yield from ((oai.ParameterLocation.COOKIE, param) for param in self.cookie_parameters) - - def list_all_parameters(self) -> list[Property]: - """Return a list of all the parameters of this endpoint""" - return ( - self.path_parameters - + self.query_parameters - + self.header_parameters - + self.cookie_parameters - + [body.prop for body in self.bodies] - ) - - -@dataclass -class GeneratorData: - """All the data needed to generate a client""" - - title: str - description: Optional[str] - version: str - models: Iterator[ModelProperty] - errors: list[ParseError] - endpoint_collections_by_tag: dict[utils.PythonIdentifier, EndpointCollection] - enums: Iterator[Union[EnumProperty, LiteralEnumProperty]] - - @staticmethod - def from_dict(data: dict[str, Any], *, config: Config) -> Union["GeneratorData", GeneratorError]: - """Create an OpenAPI from dict""" - try: - openapi = oai.OpenAPI.model_validate(data) - except ValidationError as err: - detail = str(err) - if "swagger" in data: - detail = ( - "You may be trying to use a Swagger document; this is not supported by this project.\n\n" + detail - ) - return GeneratorError(header="Failed to parse OpenAPI document", detail=detail) - schemas = Schemas() - parameters = Parameters() - if openapi.components and openapi.components.schemas: - schemas = build_schemas(components=openapi.components.schemas, schemas=schemas, config=config) - if openapi.components and openapi.components.parameters: - parameters = build_parameters( - components=openapi.components.parameters, - parameters=parameters, - config=config, - ) - request_bodies = (openapi.components and openapi.components.requestBodies) or {} - endpoint_collections_by_tag, schemas, parameters = EndpointCollection.from_data( - data=openapi.paths, schemas=schemas, parameters=parameters, request_bodies=request_bodies, config=config - ) - - enums = ( - prop for prop in schemas.classes_by_name.values() if isinstance(prop, (EnumProperty, LiteralEnumProperty)) - ) - models = (prop for prop in schemas.classes_by_name.values() if isinstance(prop, ModelProperty)) - - return GeneratorData( - title=openapi.info.title, - description=openapi.info.description, - version=openapi.info.version, - endpoint_collections_by_tag=endpoint_collections_by_tag, - models=models, - errors=schemas.errors + parameters.errors, - enums=enums, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py deleted file mode 100644 index ba667347bd07..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/__init__.py +++ /dev/null @@ -1,459 +0,0 @@ -from __future__ import annotations - -__all__ = [ - "AnyProperty", - "Class", - "EnumProperty", - "LiteralEnumProperty", - "ModelProperty", - "Parameters", - "Property", - "Schemas", - "build_parameters", - "build_schemas", - "property_from_data", -] - -from collections.abc import Iterable - -from attrs import evolve - -from ... import Config, utils -from ... import schema as oai -from ..errors import ParameterError, ParseError, PropertyError -from .any import AnyProperty -from .boolean import BooleanProperty -from .const import ConstProperty -from .date import DateProperty -from .datetime import DateTimeProperty -from .enum_property import EnumProperty -from .file import FileProperty -from .float import FloatProperty -from .int import IntProperty -from .list_property import ListProperty -from .literal_enum_property import LiteralEnumProperty -from .model_property import ModelProperty, process_model -from .none import NoneProperty -from .property import Property -from .schemas import ( - Class, - Parameters, - ReferencePath, - Schemas, - parse_reference_path, - update_parameters_with_data, - update_schemas_with_data, -) -from .string import StringProperty -from .union import UnionProperty -from .uuid import UuidProperty - - -def _string_based_property( - name: str, required: bool, data: oai.Schema, config: Config -) -> StringProperty | DateProperty | DateTimeProperty | FileProperty | UuidProperty | PropertyError: - """Construct a Property from the type "string" """ - string_format = data.schema_format - python_name = utils.PythonIdentifier(value=name, prefix=config.field_prefix) - if string_format == "date-time": - return DateTimeProperty.build( - name=name, - required=required, - default=data.default, - python_name=python_name, - description=data.description, - example=data.example, - ) - if string_format == "date": - return DateProperty.build( - name=name, - required=required, - default=data.default, - python_name=python_name, - description=data.description, - example=data.example, - ) - if string_format == "binary": - return FileProperty.build( - name=name, - required=required, - default=None, - python_name=python_name, - description=data.description, - example=data.example, - ) - if string_format == "uuid": - return UuidProperty.build( - name=name, - required=required, - default=data.default, - python_name=python_name, - description=data.description, - example=data.example, - ) - return StringProperty.build( - name=name, - default=data.default, - required=required, - python_name=python_name, - description=data.description, - example=data.example, - ) - - -def _property_from_ref( - name: str, - required: bool, - parent: oai.Schema | None, - data: oai.Reference, - schemas: Schemas, - config: Config, - roots: set[ReferencePath | utils.ClassName], -) -> tuple[Property | PropertyError, Schemas]: - ref_path = parse_reference_path(data.ref) - if isinstance(ref_path, ParseError): - return PropertyError(data=data, detail=ref_path.detail), schemas - existing = schemas.classes_by_reference.get(ref_path) - if not existing: - return ( - PropertyError(data=data, detail="Could not find reference in parsed models or enums"), - schemas, - ) - - default = existing.convert_value(parent.default) if parent is not None else None - if isinstance(default, PropertyError): - default.data = parent or data - return default, schemas - - prop = evolve( - existing, - required=required, - name=name, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - default=default, # type: ignore # mypy can't tell that default comes from the same class... - ) - - schemas.add_dependencies(ref_path=ref_path, roots=roots) - return prop, schemas - - -def property_from_data( # noqa: PLR0911, PLR0912 - name: str, - required: bool, - data: oai.Reference | oai.Schema, - schemas: Schemas, - parent_name: str, - config: Config, - process_properties: bool = True, - roots: set[ReferencePath | utils.ClassName] | None = None, -) -> tuple[Property | PropertyError, Schemas]: - """Generate a Property from the OpenAPI dictionary representation of it""" - roots = roots or set() - name = utils.remove_string_escapes(name) - if isinstance(data, oai.Reference): - return _property_from_ref( - name=name, - required=required, - parent=None, - data=data, - schemas=schemas, - config=config, - roots=roots, - ) - - sub_data: list[oai.Schema | oai.Reference] = data.allOf + data.anyOf + data.oneOf - # A union of a single reference should just be passed through to that reference (don't create copy class) - if len(sub_data) == 1 and isinstance(sub_data[0], oai.Reference): - prop, schemas = _property_from_ref( - name=name, - required=required, - parent=data, - data=sub_data[0], - schemas=schemas, - config=config, - roots=roots, - ) - # We won't be generating a separate Python class for this schema - references to it will just use - # the class for the schema it's referencing - so we don't add it to classes_by_name; but we do - # add it to models_to_process, if it's a model, because its properties still need to be resolved. - if isinstance(prop, ModelProperty): - schemas = evolve( - schemas, - models_to_process=[*schemas.models_to_process, prop], - ) - return prop, schemas - - if data.type == oai.DataType.BOOLEAN: - return ( - BooleanProperty.build( - name=name, - required=required, - default=data.default, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ), - schemas, - ) - if data.enum: - if config.literal_enums: - return LiteralEnumProperty.build( - data=data, - name=name, - required=required, - schemas=schemas, - parent_name=parent_name, - config=config, - ) - return EnumProperty.build( - data=data, - name=name, - required=required, - schemas=schemas, - parent_name=parent_name, - config=config, - ) - if data.anyOf or data.oneOf or isinstance(data.type, list): - return UnionProperty.build( - data=data, - name=name, - required=required, - schemas=schemas, - parent_name=parent_name, - config=config, - ) - if data.const is not None: - return ( - ConstProperty.build( - name=name, - required=required, - default=data.default, - const=data.const, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - ), - schemas, - ) - if data.type == oai.DataType.STRING: - return ( - _string_based_property(name=name, required=required, data=data, config=config), - schemas, - ) - if data.type == oai.DataType.NUMBER: - return ( - FloatProperty.build( - name=name, - default=data.default, - required=required, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ), - schemas, - ) - if data.type == oai.DataType.INTEGER: - return ( - IntProperty.build( - name=name, - default=data.default, - required=required, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ), - schemas, - ) - if data.type == oai.DataType.NULL: - return ( - NoneProperty( - name=name, - required=required, - default=None, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ), - schemas, - ) - if data.type == oai.DataType.ARRAY: - return ListProperty.build( - data=data, - name=name, - required=required, - schemas=schemas, - parent_name=parent_name, - config=config, - process_properties=process_properties, - roots=roots, - ) - if data.type == oai.DataType.OBJECT or data.allOf or (data.type is None and data.properties): - return ModelProperty.build( - data=data, - name=name, - schemas=schemas, - required=required, - parent_name=parent_name, - config=config, - process_properties=process_properties, - roots=roots, - ) - return ( - AnyProperty.build( - name=name, - required=required, - default=data.default, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ), - schemas, - ) - - -def _create_schemas( - *, - components: dict[str, oai.Reference | oai.Schema], - schemas: Schemas, - config: Config, -) -> Schemas: - to_process: Iterable[tuple[str, oai.Reference | oai.Schema]] = components.items() - still_making_progress = True - errors: list[PropertyError] = [] - - # References could have forward References so keep going as long as we are making progress - while still_making_progress: - still_making_progress = False - errors = [] - next_round = [] - # Only accumulate errors from the last round, since we might fix some along the way - for name, data in to_process: - if isinstance(data, oai.Reference): - schemas.errors.append(PropertyError(data=data, detail="Reference schemas are not supported.")) - continue - ref_path = parse_reference_path(f"#/components/schemas/{name}") - if isinstance(ref_path, ParseError): - schemas.errors.append(PropertyError(detail=ref_path.detail, data=data)) - continue - schemas_or_err = update_schemas_with_data(ref_path=ref_path, data=data, schemas=schemas, config=config) - if isinstance(schemas_or_err, PropertyError): - next_round.append((name, data)) - errors.append(schemas_or_err) - continue - schemas = schemas_or_err - still_making_progress = True - to_process = next_round - - schemas.errors.extend(errors) - return schemas - - -def _propogate_removal(*, root: ReferencePath | utils.ClassName, schemas: Schemas, error: PropertyError) -> None: - if isinstance(root, utils.ClassName): - schemas.classes_by_name.pop(root, None) - return - if root in schemas.classes_by_reference: - error.detail = error.detail or "" - error.detail += f"\n{root}" - del schemas.classes_by_reference[root] - for child in schemas.dependencies.get(root, set()): - _propogate_removal(root=child, schemas=schemas, error=error) - - -def _process_model_errors( - model_errors: list[tuple[ModelProperty, PropertyError]], *, schemas: Schemas -) -> list[PropertyError]: - for model, error in model_errors: - error.detail = error.detail or "" - error.detail += "\n\nFailure to process schema has resulted in the removal of:" - for root in model.roots: - _propogate_removal(root=root, schemas=schemas, error=error) - return [error for _, error in model_errors] - - -def _process_models(*, schemas: Schemas, config: Config) -> Schemas: - to_process = schemas.models_to_process - still_making_progress = True - final_model_errors: list[tuple[ModelProperty, PropertyError]] = [] - latest_model_errors: list[tuple[ModelProperty, PropertyError]] = [] - - # Models which refer to other models in their allOf must be processed after their referenced models - while still_making_progress: - still_making_progress = False - # Only accumulate errors from the last round, since we might fix some along the way - latest_model_errors = [] - next_round = [] - for model_prop in to_process: - schemas_or_err = process_model(model_prop, schemas=schemas, config=config) - if isinstance(schemas_or_err, PropertyError): - schemas_or_err.header = f"\nUnable to process schema {model_prop.name}:" - if isinstance(schemas_or_err.data, oai.Reference) and schemas_or_err.data.ref.endswith( - f"/{model_prop.class_info.name}" - ): - schemas_or_err.detail = schemas_or_err.detail or "" - schemas_or_err.detail += "\n\nRecursive allOf reference found" - final_model_errors.append((model_prop, schemas_or_err)) - continue - latest_model_errors.append((model_prop, schemas_or_err)) - next_round.append(model_prop) - continue - schemas = schemas_or_err - still_making_progress = True - to_process = next_round - - final_model_errors.extend(latest_model_errors) - errors = _process_model_errors(final_model_errors, schemas=schemas) - return evolve(schemas, errors=[*schemas.errors, *errors], models_to_process=to_process) - - -def build_schemas( - *, - components: dict[str, oai.Reference | oai.Schema], - schemas: Schemas, - config: Config, -) -> Schemas: - """Get a list of Schemas from an OpenAPI dict""" - schemas = _create_schemas(components=components, schemas=schemas, config=config) - schemas = _process_models(schemas=schemas, config=config) - return schemas - - -def build_parameters( - *, - components: dict[str, oai.Reference | oai.Parameter], - parameters: Parameters, - config: Config, -) -> Parameters: - """Get a list of Parameters from an OpenAPI dict""" - to_process: Iterable[tuple[str, oai.Reference | oai.Parameter]] = [] - if components is not None: - to_process = components.items() - still_making_progress = True - errors: list[ParameterError] = [] - - # References could have forward References so keep going as long as we are making progress - while still_making_progress: - still_making_progress = False - errors = [] - next_round = [] - # Only accumulate errors from the last round, since we might fix some along the way - for name, data in to_process: - if isinstance(data, oai.Reference): - parameters.errors.append(ParameterError(data=data, detail="Reference parameters are not supported.")) - continue - ref_path = parse_reference_path(f"#/components/parameters/{name}") - if isinstance(ref_path, ParseError): - parameters.errors.append(ParameterError(detail=ref_path.detail, data=data)) - continue - parameters_or_err = update_parameters_with_data( - ref_path=ref_path, data=data, parameters=parameters, config=config - ) - if isinstance(parameters_or_err, ParameterError): - next_round.append((name, data)) - errors.append(parameters_or_err) - continue - parameters = parameters_or_err - still_making_progress = True - to_process = next_round - - parameters.errors.extend(errors) - return parameters diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/any.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/any.py deleted file mode 100644 index b760a156868e..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/any.py +++ /dev/null @@ -1,51 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar - -from attr import define - -from ...utils import PythonIdentifier -from .protocol import PropertyProtocol, Value - - -@define -class AnyProperty(PropertyProtocol): - """A property that can be any type (used for empty schemas)""" - - @classmethod - def build( - cls, - name: str, - required: bool, - default: Any, - python_name: PythonIdentifier, - description: str | None, - example: str | None, - ) -> AnyProperty: - return cls( - name=name, - required=required, - default=AnyProperty.convert_value(default), - python_name=python_name, - description=description, - example=example, - ) - - @classmethod - def convert_value(cls, value: Any) -> Value | None: - from .string import StringProperty - - if value is None: - return value - if isinstance(value, str): - return StringProperty.convert_value(value) - return Value(python_code=str(value), raw_value=value) - - name: str - required: bool - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - _type_string: ClassVar[str] = "Any" - _json_type_string: ClassVar[str] = "Any" diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py deleted file mode 100644 index 5fd4235d75b3..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/boolean.py +++ /dev/null @@ -1,67 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar - -from attr import define - -from ... import schema as oai -from ...utils import PythonIdentifier -from ..errors import PropertyError -from .protocol import PropertyProtocol, Value - - -@define -class BooleanProperty(PropertyProtocol): - """Property for bool""" - - name: str - required: bool - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - - _type_string: ClassVar[str] = "bool" - _json_type_string: ClassVar[str] = "bool" - _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - template: ClassVar[str] = "boolean_property.py.jinja" - - @classmethod - def build( - cls, - name: str, - required: bool, - default: Any, - python_name: PythonIdentifier, - description: str | None, - example: str | None, - ) -> BooleanProperty | PropertyError: - checked_default = cls.convert_value(default) - if isinstance(checked_default, PropertyError): - return checked_default - return cls( - name=name, - required=required, - default=checked_default, - python_name=python_name, - description=description, - example=example, - ) - - @classmethod - def convert_value(cls, value: Any) -> Value | None | PropertyError: - if isinstance(value, Value) or value is None: - return value - if isinstance(value, str): - if value.lower() == "true": - return Value(python_code="True", raw_value=value) - elif value.lower() == "false": - return Value(python_code="False", raw_value=value) - if isinstance(value, bool): - return Value(python_code=str(value), raw_value=value) - return PropertyError(f"Invalid boolean value: {value}") diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/const.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/const.py deleted file mode 100644 index 8b9967f19734..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/const.py +++ /dev/null @@ -1,118 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar, overload - -from attr import define - -from ...utils import PythonIdentifier -from ..errors import PropertyError -from .protocol import PropertyProtocol, Value -from .string import StringProperty - - -@define -class ConstProperty(PropertyProtocol): - """A property representing a const value""" - - name: str - required: bool - value: Value - default: Value | None - python_name: PythonIdentifier - description: str | None - example: None - template: ClassVar[str] = "const_property.py.jinja" - - @classmethod - def build( - cls, - *, - const: str | int | float | bool, - default: Any, - name: str, - python_name: PythonIdentifier, - required: bool, - description: str | None, - ) -> ConstProperty | PropertyError: - """ - Create a `ConstProperty` the right way. - - Args: - const: The `const` value of the schema, indicating the literal value this represents - default: The default value of this property, if any. Must be equal to `const` if set. - name: The name of the property where it appears in the OpenAPI document. - required: Whether this property is required where it's being used. - python_name: The name used to represent this variable/property in generated Python code - description: The description of this property, used for docstrings - """ - value = cls._convert_value(const) - - prop = cls( - value=value, - python_name=python_name, - name=name, - required=required, - default=None, - description=description, - example=None, - ) - converted_default = prop.convert_value(default) - if isinstance(converted_default, PropertyError): - return converted_default - prop.default = converted_default - return prop - - def convert_value(self, value: Any) -> Value | None | PropertyError: - value = self._convert_value(value) - if value is None: - return value - if value != self.value: - return PropertyError( - detail=f"Invalid value for const {self.name}; {value.raw_value} != {self.value.raw_value}" - ) - return value - - @staticmethod - @overload - def _convert_value(value: None) -> None: # type: ignore[misc] - ... # pragma: no cover - - @staticmethod - @overload - def _convert_value(value: Any) -> Value: ... # pragma: no cover - - @staticmethod - def _convert_value(value: Any) -> Value | None: - if value is None or isinstance(value, Value): - return value - if isinstance(value, str): - return StringProperty.convert_value(value) - return Value(python_code=str(value), raw_value=value) - - def get_type_string( - self, - no_optional: bool = False, - json: bool = False, - *, - multipart: bool = False, - quoted: bool = False, - ) -> str: - lit = f"Literal[{self.value.python_code}]" - if not no_optional and not self.required: - return f"Union[{lit}, Unset]" - return lit - - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - if self.required: - return {"from typing import Literal, cast"} - return { - "from typing import Literal, Union, cast", - f"from {prefix}types import UNSET, Unset", - } diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/date.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/date.py deleted file mode 100644 index 7261698ea302..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/date.py +++ /dev/null @@ -1,73 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar - -from attr import define -from dateutil.parser import isoparse - -from ...utils import PythonIdentifier -from ..errors import PropertyError -from .protocol import PropertyProtocol, Value - - -@define -class DateProperty(PropertyProtocol): - """A property of type datetime.date""" - - name: str - required: bool - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - - _type_string: ClassVar[str] = "datetime.date" - _json_type_string: ClassVar[str] = "str" - template: ClassVar[str] = "date_property.py.jinja" - - @classmethod - def build( - cls, - name: str, - required: bool, - default: Any, - python_name: PythonIdentifier, - description: str | None, - example: str | None, - ) -> DateProperty | PropertyError: - checked_default = cls.convert_value(default) - if isinstance(checked_default, PropertyError): - return checked_default - - return DateProperty( - name=name, - required=required, - default=checked_default, - python_name=python_name, - description=description, - example=example, - ) - - @classmethod - def convert_value(cls, value: Any) -> Value | None | PropertyError: - if isinstance(value, Value) or value is None: - return value - if isinstance(value, str): - try: - isoparse(value).date() # make sure it's a valid value - except ValueError as e: - return PropertyError(f"Invalid date: {e}") - return Value(python_code=f"isoparse({value!r}).date()", raw_value=value) - return PropertyError(f"Cannot convert {value} to a date") - - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.update({"import datetime", "from typing import cast", "from dateutil.parser import isoparse"}) - return imports diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py deleted file mode 100644 index 5924d173cda2..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/datetime.py +++ /dev/null @@ -1,75 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar - -from attr import define -from dateutil.parser import isoparse - -from ...utils import PythonIdentifier -from ..errors import PropertyError -from .protocol import PropertyProtocol, Value - - -@define -class DateTimeProperty(PropertyProtocol): - """ - A property of type datetime.datetime - """ - - name: str - required: bool - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - - _type_string: ClassVar[str] = "datetime.datetime" - _json_type_string: ClassVar[str] = "str" - template: ClassVar[str] = "datetime_property.py.jinja" - - @classmethod - def build( - cls, - name: str, - required: bool, - default: Any, - python_name: PythonIdentifier, - description: str | None, - example: str | None, - ) -> DateTimeProperty | PropertyError: - checked_default = cls.convert_value(default) - if isinstance(checked_default, PropertyError): - return checked_default - - return DateTimeProperty( - name=name, - required=required, - default=checked_default, - python_name=python_name, - description=description, - example=example, - ) - - @classmethod - def convert_value(cls, value: Any) -> Value | None | PropertyError: - if value is None or isinstance(value, Value): - return value - if isinstance(value, str): - try: - isoparse(value) # make sure it's a valid value - except ValueError as e: - return PropertyError(f"Invalid datetime: {e}") - return Value(python_code=f"isoparse({value!r})", raw_value=value) - return PropertyError(f"Cannot convert {value} to a datetime") - - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.update({"import datetime", "from typing import cast", "from dateutil.parser import isoparse"}) - return imports diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py deleted file mode 100644 index fc7f20bd924c..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/enum_property.py +++ /dev/null @@ -1,209 +0,0 @@ -from __future__ import annotations - -__all__ = ["EnumProperty", "ValueType"] - -from typing import Any, ClassVar, Union, cast - -from attr import evolve -from attrs import define - -from ... import Config, utils -from ... import schema as oai -from ...schema import DataType -from ..errors import PropertyError -from .none import NoneProperty -from .protocol import PropertyProtocol, Value -from .schemas import Class, Schemas -from .union import UnionProperty - -ValueType = Union[str, int] - - -@define -class EnumProperty(PropertyProtocol): - """A property that should use an enum""" - - name: str - required: bool - default: Value | None - python_name: utils.PythonIdentifier - description: str | None - example: str | None - values: dict[str, ValueType] - class_info: Class - value_type: type[ValueType] - - template: ClassVar[str] = "enum_property.py.jinja" - - _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - - @classmethod - def build( # noqa: PLR0911 - cls, - *, - data: oai.Schema, - name: str, - required: bool, - schemas: Schemas, - parent_name: str, - config: Config, - ) -> tuple[EnumProperty | NoneProperty | UnionProperty | PropertyError, Schemas]: - """ - Create an EnumProperty from schema data. - - Args: - data: The OpenAPI Schema which defines this enum. - name: The name to use for variables which receive this Enum's value (e.g. model property name) - required: Whether or not this Property is required in the calling context - schemas: The Schemas which have been defined so far (used to prevent naming collisions) - enum: The enum from the provided data. Required separately here to prevent extra type checking. - parent_name: The context in which this EnumProperty is defined, used to create more specific class names. - config: The global config for this run of the generator - - Returns: - A tuple containing either the created property or a PropertyError AND update schemas. - """ - - enum = data.enum or [] # The outer function checks for this, but mypy doesn't know that - - # OpenAPI allows for null as an enum value, but it doesn't make sense with how enums are constructed in Python. - # So instead, if null is a possible value, make the property nullable. - # Mypy is not smart enough to know that the type is right though - unchecked_value_list = [value for value in enum if value is not None] # type: ignore - - # It's legal to have an enum that only contains null as a value, we don't bother constructing an enum for that - if len(unchecked_value_list) == 0: - return ( - NoneProperty.build( - name=name, - required=required, - default="None", - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=None, - example=None, - ), - schemas, - ) - - value_types = {type(value) for value in unchecked_value_list} - if len(value_types) > 1: - return PropertyError( - header="Enum values must all be the same type", detail=f"Got {value_types}", data=data - ), schemas - value_type = next(iter(value_types)) - if value_type not in (str, int): - return PropertyError(header=f"Unsupported enum type {value_type}", data=data), schemas - value_list = cast( - Union[list[int], list[str]], unchecked_value_list - ) # We checked this with all the value_types stuff - - if len(value_list) < len(enum): # Only one of the values was None, that becomes a union - data.oneOf = [ - oai.Schema(type=DataType.NULL), - data.model_copy(update={"enum": value_list, "default": data.default}), - ] - data.enum = None - return UnionProperty.build( - data=data, - name=name, - required=required, - schemas=schemas, - parent_name=parent_name, - config=config, - ) - - class_name = data.title or name - if parent_name: - class_name = f"{utils.pascal_case(parent_name)}{utils.pascal_case(class_name)}" - class_info = Class.from_string(string=class_name, config=config) - values = EnumProperty.values_from_list(value_list, class_info) - - if class_info.name in schemas.classes_by_name: - existing = schemas.classes_by_name[class_info.name] - if not isinstance(existing, EnumProperty) or values != existing.values: - return ( - PropertyError( - detail=f"Found conflicting enums named {class_info.name} with incompatible values.", data=data - ), - schemas, - ) - - prop = EnumProperty( - name=name, - required=required, - class_info=class_info, - values=values, - value_type=value_type, - default=None, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ) - checked_default = prop.convert_value(data.default) - if isinstance(checked_default, PropertyError): - checked_default.data = data - return checked_default, schemas - prop = evolve(prop, default=checked_default) - - schemas = evolve(schemas, classes_by_name={**schemas.classes_by_name, class_info.name: prop}) - return prop, schemas - - def convert_value(self, value: Any) -> Value | PropertyError | None: - if value is None or isinstance(value, Value): - return value - if isinstance(value, self.value_type): - inverse_values = {v: k for k, v in self.values.items()} - try: - return Value(python_code=f"{self.class_info.name}.{inverse_values[value]}", raw_value=value) - except KeyError: - return PropertyError(detail=f"Value {value} is not valid for enum {self.name}") - return PropertyError(detail=f"Cannot convert {value} to enum {self.name} of type {self.value_type}") - - def get_base_type_string(self, *, quoted: bool = False) -> str: - return self.class_info.name - - def get_base_json_type_string(self, *, quoted: bool = False) -> str: - return self.value_type.__name__ - - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.add(f"from {prefix}models.{self.class_info.module_name} import {self.class_info.name}") - return imports - - @staticmethod - def values_from_list(values: list[str] | list[int], class_info: Class) -> dict[str, ValueType]: - """Convert a list of values into dict of {name: value}, where value can sometimes be None""" - output: dict[str, ValueType] = {} - - for i, value in enumerate(values): - value = cast(Union[str, int], value) - if isinstance(value, int): - if value < 0: - output[f"VALUE_NEGATIVE_{-value}"] = value - else: - output[f"VALUE_{value}"] = value - continue - if value and value[0].isalpha(): - key = value.upper() - else: - key = f"VALUE_{i}" - if key in output: - raise ValueError( - f"Duplicate key {key} in enum {class_info.module_name}.{class_info.name}; " - f"consider setting literal_enums in your config" - ) - sanitized_key = utils.snake_case(key).upper() - output[sanitized_key] = utils.remove_string_escapes(value) - return output diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/file.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/file.py deleted file mode 100644 index 505876b6370e..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/file.py +++ /dev/null @@ -1,67 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar - -from attr import define - -from ...utils import PythonIdentifier -from ..errors import PropertyError -from .protocol import PropertyProtocol - - -@define -class FileProperty(PropertyProtocol): - """A property used for uploading files""" - - name: str - required: bool - default: None - python_name: PythonIdentifier - description: str | None - example: str | None - - _type_string: ClassVar[str] = "File" - # Return type of File.to_tuple() - _json_type_string: ClassVar[str] = "FileJsonType" - template: ClassVar[str] = "file_property.py.jinja" - - @classmethod - def build( - cls, - name: str, - required: bool, - default: Any, - python_name: PythonIdentifier, - description: str | None, - example: str | None, - ) -> FileProperty | PropertyError: - default_or_err = cls.convert_value(default) - if isinstance(default_or_err, PropertyError): - return default_or_err - - return cls( - name=name, - required=required, - default=default_or_err, - python_name=python_name, - description=description, - example=example, - ) - - @classmethod - def convert_value(cls, value: Any) -> None | PropertyError: - if value is not None: - return PropertyError(detail="File properties cannot have a default value") - return value - - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.update({f"from {prefix}types import File, FileJsonType", "from io import BytesIO"}) - return imports diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/float.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/float.py deleted file mode 100644 index a785db6d4a11..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/float.py +++ /dev/null @@ -1,71 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar - -from attr import define - -from ... import schema as oai -from ...utils import PythonIdentifier -from ..errors import PropertyError -from .protocol import PropertyProtocol, Value - - -@define -class FloatProperty(PropertyProtocol): - """A property of type float""" - - name: str - required: bool - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - - _type_string: ClassVar[str] = "float" - _json_type_string: ClassVar[str] = "float" - _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - template: ClassVar[str] = "float_property.py.jinja" - - @classmethod - def build( - cls, - name: str, - required: bool, - default: Any, - python_name: PythonIdentifier, - description: str | None, - example: str | None, - ) -> FloatProperty | PropertyError: - checked_default = cls.convert_value(default) - if isinstance(checked_default, PropertyError): - return checked_default - - return cls( - name=name, - required=required, - default=checked_default, - python_name=python_name, - description=description, - example=example, - ) - - @classmethod - def convert_value(cls, value: Any) -> Value | None | PropertyError: - if isinstance(value, Value) or value is None: - return value - if isinstance(value, str): - try: - parsed = float(value) - return Value(python_code=str(parsed), raw_value=value) - except ValueError: - return PropertyError(f"Invalid float value: {value}") - if isinstance(value, float): - return Value(python_code=str(value), raw_value=value) - if isinstance(value, int) and not isinstance(value, bool): - return Value(python_code=str(float(value)), raw_value=value) - return PropertyError(f"Cannot convert {value} to a float") diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/int.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/int.py deleted file mode 100644 index 1cd340fbdd76..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/int.py +++ /dev/null @@ -1,73 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar - -from attr import define - -from ... import schema as oai -from ...utils import PythonIdentifier -from ..errors import PropertyError -from .protocol import PropertyProtocol, Value - - -@define -class IntProperty(PropertyProtocol): - """A property of type int""" - - name: str - required: bool - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - - _type_string: ClassVar[str] = "int" - _json_type_string: ClassVar[str] = "int" - _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - template: ClassVar[str] = "int_property.py.jinja" - - @classmethod - def build( - cls, - name: str, - required: bool, - default: Any, - python_name: PythonIdentifier, - description: str | None, - example: str | None, - ) -> IntProperty | PropertyError: - checked_default = cls.convert_value(default) - if isinstance(checked_default, PropertyError): - return checked_default - - return cls( - name=name, - required=required, - default=checked_default, - python_name=python_name, - description=description, - example=example, - ) - - @classmethod - def convert_value(cls, value: Any) -> Value | None | PropertyError: - if value is None or isinstance(value, Value): - return value - converted = value - if isinstance(converted, str): - try: - converted = float(converted) - except ValueError: - return PropertyError(f"Invalid int value: {converted}") - if isinstance(converted, float): - as_int = int(converted) - if converted == as_int: - converted = as_int - if isinstance(converted, int) and not isinstance(converted, bool): - return Value(python_code=str(converted), raw_value=value) - return PropertyError(f"Invalid int value: {value}") diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py deleted file mode 100644 index bf0756fe307c..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/list_property.py +++ /dev/null @@ -1,160 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar - -from attr import define - -from ... import Config, utils -from ... import schema as oai -from ..errors import PropertyError -from .protocol import PropertyProtocol, Value -from .schemas import ReferencePath, Schemas - - -@define -class ListProperty(PropertyProtocol): - """A property representing a list (array) of other properties""" - - name: str - required: bool - default: Value | None - python_name: utils.PythonIdentifier - description: str | None - example: str | None - inner_property: PropertyProtocol - template: ClassVar[str] = "list_property.py.jinja" - - @classmethod - def build( - cls, - *, - data: oai.Schema, - name: str, - required: bool, - schemas: Schemas, - parent_name: str, - config: Config, - process_properties: bool, - roots: set[ReferencePath | utils.ClassName], - ) -> tuple[ListProperty | PropertyError, Schemas]: - """ - Build a ListProperty the right way, use this instead of the normal constructor. - - Args: - data: `oai.Schema` representing this `ListProperty`. - name: The name of this property where it's used. - required: Whether this `ListProperty` can be `Unset` where it's used. - schemas: Collected `Schemas` so far containing any classes or references. - parent_name: The name of the thing containing this property (used for naming inner classes). - config: User-provided config for overriding default behaviors. - process_properties: If the new property is a ModelProperty, determines whether it will be initialized with - property data - roots: The set of `ReferencePath`s and `ClassName`s to remove from the schemas if a child reference becomes - invalid - - Returns: - `(result, schemas)` where `schemas` is an updated version of the input named the same including any inner - classes that were defined and `result` is either the `ListProperty` or a `PropertyError`. - """ - from . import property_from_data - - if data.items is None and not data.prefixItems: - return ( - PropertyError( - data=data, - detail="type array must have items or prefixItems defined", - ), - schemas, - ) - - items = data.prefixItems or [] - if data.items: - items.append(data.items) - - if len(items) == 1: - inner_schema = items[0] - else: - inner_schema = oai.Schema(anyOf=items) - - inner_prop, schemas = property_from_data( - name=f"{name}_item", - required=True, - data=inner_schema, - schemas=schemas, - parent_name=parent_name, - config=config, - process_properties=process_properties, - roots=roots, - ) - if isinstance(inner_prop, PropertyError): - inner_prop.header = f'invalid data in items of array named "{name}"' - return inner_prop, schemas - return ( - ListProperty( - name=name, - required=required, - default=None, - inner_property=inner_prop, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ), - schemas, - ) - - def convert_value(self, value: Any) -> Value | None | PropertyError: - return None # pragma: no cover - - def get_base_type_string(self, *, quoted: bool = False) -> str: - return f"list[{self.inner_property.get_type_string(quoted=not self.inner_property.is_base_type)}]" - - def get_base_json_type_string(self, *, quoted: bool = False) -> str: - return f"list[{self.inner_property.get_type_string(json=True, quoted=not self.inner_property.is_base_type)}]" - - def get_instance_type_string(self) -> str: - """Get a string representation of runtime type that should be used for `isinstance` checks""" - return "list" - - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.update(self.inner_property.get_imports(prefix=prefix)) - imports.add("from typing import cast") - return imports - - def get_lazy_imports(self, *, prefix: str) -> set[str]: - lazy_imports = super().get_lazy_imports(prefix=prefix) - lazy_imports.update(self.inner_property.get_lazy_imports(prefix=prefix)) - return lazy_imports - - def get_type_string( - self, - no_optional: bool = False, - json: bool = False, - *, - multipart: bool = False, - quoted: bool = False, - ) -> str: - """ - Get a string representation of type that should be used when declaring this property - - Args: - no_optional: Do not include Optional or Unset even if the value is optional (needed for isinstance checks) - json: True if the type refers to the property after JSON serialization - """ - if json: - type_string = self.get_base_json_type_string() - elif multipart: - type_string = "tuple[None, bytes, str]" - else: - type_string = self.get_base_type_string() - - if no_optional or self.required: - return type_string - return f"Union[Unset, {type_string}]" diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py deleted file mode 100644 index 669b62f583fa..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/literal_enum_property.py +++ /dev/null @@ -1,191 +0,0 @@ -from __future__ import annotations - -__all__ = ["LiteralEnumProperty"] - -from typing import Any, ClassVar, Union, cast - -from attr import evolve -from attrs import define - -from ... import Config, utils -from ... import schema as oai -from ...schema import DataType -from ..errors import PropertyError -from .none import NoneProperty -from .protocol import PropertyProtocol, Value -from .schemas import Class, Schemas -from .union import UnionProperty - -ValueType = Union[str, int] - - -@define -class LiteralEnumProperty(PropertyProtocol): - """A property that should use a literal enum""" - - name: str - required: bool - default: Value | None - python_name: utils.PythonIdentifier - description: str | None - example: str | None - values: set[ValueType] - class_info: Class - value_type: type[ValueType] - - template: ClassVar[str] = "literal_enum_property.py.jinja" - - _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - - @classmethod - def build( # noqa: PLR0911 - cls, - *, - data: oai.Schema, - name: str, - required: bool, - schemas: Schemas, - parent_name: str, - config: Config, - ) -> tuple[LiteralEnumProperty | NoneProperty | UnionProperty | PropertyError, Schemas]: - """ - Create a LiteralEnumProperty from schema data. - - Args: - data: The OpenAPI Schema which defines this enum. - name: The name to use for variables which receive this Enum's value (e.g. model property name) - required: Whether or not this Property is required in the calling context - schemas: The Schemas which have been defined so far (used to prevent naming collisions) - parent_name: The context in which this LiteralEnumProperty is defined, used to create more specific class names. - config: The global config for this run of the generator - - Returns: - A tuple containing either the created property or a PropertyError AND update schemas. - """ - - enum = data.enum or [] # The outer function checks for this, but mypy doesn't know that - - # OpenAPI allows for null as an enum value, but it doesn't make sense with how enums are constructed in Python. - # So instead, if null is a possible value, make the property nullable. - # Mypy is not smart enough to know that the type is right though - unchecked_value_list = [value for value in enum if value is not None] # type: ignore - - # It's legal to have an enum that only contains null as a value, we don't bother constructing an enum for that - if len(unchecked_value_list) == 0: - return ( - NoneProperty.build( - name=name, - required=required, - default="None", - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=None, - example=None, - ), - schemas, - ) - - value_types = {type(value) for value in unchecked_value_list} - if len(value_types) > 1: - return PropertyError( - header="Enum values must all be the same type", detail=f"Got {value_types}", data=data - ), schemas - value_type = next(iter(value_types)) - if value_type not in (str, int): - return PropertyError(header=f"Unsupported enum type {value_type}", data=data), schemas - value_list = cast( - Union[list[int], list[str]], unchecked_value_list - ) # We checked this with all the value_types stuff - - if len(value_list) < len(enum): # Only one of the values was None, that becomes a union - data.oneOf = [ - oai.Schema(type=DataType.NULL), - data.model_copy(update={"enum": value_list, "default": data.default}), - ] - data.enum = None - return UnionProperty.build( - data=data, - name=name, - required=required, - schemas=schemas, - parent_name=parent_name, - config=config, - ) - - class_name = data.title or name - if parent_name: - class_name = f"{utils.pascal_case(parent_name)}{utils.pascal_case(class_name)}" - class_info = Class.from_string(string=class_name, config=config) - values: set[str | int] = set(value_list) - - if class_info.name in schemas.classes_by_name: - existing = schemas.classes_by_name[class_info.name] - if not isinstance(existing, LiteralEnumProperty) or values != existing.values: - return ( - PropertyError( - detail=f"Found conflicting enums named {class_info.name} with incompatible values.", data=data - ), - schemas, - ) - - prop = LiteralEnumProperty( - name=name, - required=required, - class_info=class_info, - values=values, - value_type=value_type, - default=None, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ) - checked_default = prop.convert_value(data.default) - if isinstance(checked_default, PropertyError): - checked_default.data = data - return checked_default, schemas - prop = evolve(prop, default=checked_default) - - schemas = evolve(schemas, classes_by_name={**schemas.classes_by_name, class_info.name: prop}) - return prop, schemas - - def convert_value(self, value: Any) -> Value | PropertyError | None: - if value is None or isinstance(value, Value): - return value - if isinstance(value, self.value_type): - if value in self.values: - return Value(python_code=repr(value), raw_value=value) - else: - return PropertyError(detail=f"Value {value} is not valid for enum {self.name}") - return PropertyError(detail=f"Cannot convert {value} to enum {self.name} of type {self.value_type}") - - def get_base_type_string(self, *, quoted: bool = False) -> str: - return self.class_info.name - - def get_base_json_type_string(self, *, quoted: bool = False) -> str: - return self.value_type.__name__ - - def get_instance_type_string(self) -> str: - return self.value_type.__name__ - - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.add("from typing import cast") - imports.add(f"from {prefix}models.{self.class_info.module_name} import {self.class_info.name}") - imports.add( - f"from {prefix}models.{self.class_info.module_name} import check_{self.get_class_name_snake_case()}" - ) - return imports - - def get_class_name_snake_case(self) -> str: - return utils.snake_case(self.class_info.name) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py deleted file mode 100644 index f04b67928a37..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/merge_properties.py +++ /dev/null @@ -1,198 +0,0 @@ -from __future__ import annotations - -from .date import DateProperty -from .datetime import DateTimeProperty -from .file import FileProperty -from .literal_enum_property import LiteralEnumProperty - -__all__ = ["merge_properties"] - -from typing import TypeVar, cast - -from attr import evolve - -from ..errors import PropertyError -from . import FloatProperty -from .any import AnyProperty -from .enum_property import EnumProperty -from .int import IntProperty -from .list_property import ListProperty -from .property import Property -from .protocol import PropertyProtocol -from .string import StringProperty - -PropertyT = TypeVar("PropertyT", bound=PropertyProtocol) - - -STRING_WITH_FORMAT_TYPES = (DateProperty, DateTimeProperty, FileProperty) - - -def merge_properties(prop1: Property, prop2: Property) -> Property | PropertyError: # noqa: PLR0911 - """Attempt to create a new property that incorporates the behavior of both. - - This is used when merging schemas with allOf, when two schemas define a property with the same name. - - OpenAPI defines allOf in terms of validation behavior: the input must pass the validation rules - defined in all the listed schemas. Our task here is slightly more difficult, since we must end - up with a single Property object that will be used to generate a single class property in the - generated code. Due to limitations of our internal model, this may not be possible for some - combinations of property attributes that OpenAPI supports (for instance, we have no way to represent - a string property that must match two different regexes). - - Properties can also have attributes that do not represent validation rules, such as "description" - and "example". OpenAPI does not define any overriding/aggregation rules for these in allOf. The - implementation here is, assuming prop1 and prop2 are in the same order that the schemas were in the - allOf, any such attributes that prop2 specifies will override the ones from prop1. - """ - if isinstance(prop2, AnyProperty): - return _merge_common_attributes(prop1, prop2) - - if isinstance(prop1, AnyProperty): - # Use the base type of `prop2`, but keep the override order - return _merge_common_attributes(prop2, prop1, prop2) - - if isinstance(prop1, EnumProperty) or isinstance(prop2, EnumProperty): - return _merge_with_enum(prop1, prop2) - - if isinstance(prop1, LiteralEnumProperty) or isinstance(prop2, LiteralEnumProperty): - return _merge_with_literal_enum(prop1, prop2) - - if (merged := _merge_same_type(prop1, prop2)) is not None: - return merged - - if (merged := _merge_numeric(prop1, prop2)) is not None: - return merged - - if (merged := _merge_string_with_format(prop1, prop2)) is not None: - return merged - - return PropertyError( - detail=f"{prop1.get_type_string(no_optional=True)} can't be merged with {prop2.get_type_string(no_optional=True)}" - ) - - -def _merge_same_type(prop1: Property, prop2: Property) -> Property | None | PropertyError: - if type(prop1) is not type(prop2): - return None - - if prop1 == prop2: - # It's always OK to redefine a property with everything exactly the same - return prop1 - - if isinstance(prop1, ListProperty) and isinstance(prop2, ListProperty): - inner_property = merge_properties(prop1.inner_property, prop2.inner_property) # type: ignore - if isinstance(inner_property, PropertyError): - return PropertyError(detail=f"can't merge list properties: {inner_property.detail}") - prop1.inner_property = inner_property - - # For all other property types, there aren't any special attributes that affect validation, so just - # apply the rules for common attributes like "description". - return _merge_common_attributes(prop1, prop2) - - -def _merge_string_with_format(prop1: Property, prop2: Property) -> Property | None | PropertyError: - """Merge a string that has no format with a string that has a format""" - # Here we need to use the DateProperty/DateTimeProperty/FileProperty as the base so that we preserve - # its class, but keep the correct override order for merging the attributes. - if isinstance(prop1, StringProperty) and isinstance(prop2, STRING_WITH_FORMAT_TYPES): - # Use the more specific class as a base, but keep the correct override order - return _merge_common_attributes(prop2, prop1, prop2) - elif isinstance(prop2, StringProperty) and isinstance(prop1, STRING_WITH_FORMAT_TYPES): - return _merge_common_attributes(prop1, prop2) - else: - return None - - -def _merge_numeric(prop1: Property, prop2: Property) -> IntProperty | None | PropertyError: - """Merge IntProperty with FloatProperty""" - if isinstance(prop1, IntProperty) and isinstance(prop2, (IntProperty, FloatProperty)): - return _merge_common_attributes(prop1, prop2) - elif isinstance(prop2, IntProperty) and isinstance(prop1, (IntProperty, FloatProperty)): - # Use the IntProperty as a base since it's more restrictive, but keep the correct override order - return _merge_common_attributes(prop2, prop1, prop2) - else: - return None - - -def _merge_with_enum(prop1: PropertyProtocol, prop2: PropertyProtocol) -> EnumProperty | PropertyError: - if isinstance(prop1, EnumProperty) and isinstance(prop2, EnumProperty): - # We want the narrowest validation rules that fit both, so use whichever values list is a - # subset of the other. - if _values_are_subset(prop1, prop2): - values = prop1.values - class_info = prop1.class_info - elif _values_are_subset(prop2, prop1): - values = prop2.values - class_info = prop2.class_info - else: - return PropertyError(detail="can't redefine an enum property with incompatible lists of values") - return _merge_common_attributes(evolve(prop1, values=values, class_info=class_info), prop2) - - # If enum values were specified for just one of the properties, use those. - enum_prop = prop1 if isinstance(prop1, EnumProperty) else cast(EnumProperty, prop2) - non_enum_prop = prop2 if isinstance(prop1, EnumProperty) else prop1 - if (isinstance(non_enum_prop, IntProperty) and enum_prop.value_type is int) or ( - isinstance(non_enum_prop, StringProperty) and enum_prop.value_type is str - ): - return _merge_common_attributes(enum_prop, prop1, prop2) - return PropertyError( - detail=f"can't combine enum of type {enum_prop.value_type} with {non_enum_prop.get_type_string(no_optional=True)}" - ) - - -def _merge_with_literal_enum(prop1: PropertyProtocol, prop2: PropertyProtocol) -> LiteralEnumProperty | PropertyError: - if isinstance(prop1, LiteralEnumProperty) and isinstance(prop2, LiteralEnumProperty): - # We want the narrowest validation rules that fit both, so use whichever values list is a - # subset of the other. - if prop1.values <= prop2.values: - values = prop1.values - class_info = prop1.class_info - elif prop2.values <= prop1.values: - values = prop2.values - class_info = prop2.class_info - else: - return PropertyError(detail="can't redefine a literal enum property with incompatible lists of values") - return _merge_common_attributes(evolve(prop1, values=values, class_info=class_info), prop2) - - # If enum values were specified for just one of the properties, use those. - enum_prop = prop1 if isinstance(prop1, LiteralEnumProperty) else cast(LiteralEnumProperty, prop2) - non_enum_prop = prop2 if isinstance(prop1, LiteralEnumProperty) else prop1 - if (isinstance(non_enum_prop, IntProperty) and enum_prop.value_type is int) or ( - isinstance(non_enum_prop, StringProperty) and enum_prop.value_type is str - ): - return _merge_common_attributes(enum_prop, prop1, prop2) - return PropertyError( - detail=f"can't combine literal enum of type {enum_prop.value_type} with {non_enum_prop.get_type_string(no_optional=True)}" - ) - - -def _merge_common_attributes(base: PropertyT, *extend_with: PropertyProtocol) -> PropertyT | PropertyError: - """Create a new instance based on base, overriding basic attributes with values from extend_with, in order. - - For "default", "description", and "example", a non-None value overrides any value from a previously - specified property. The behavior is similar to using the spread operator with dictionaries, except - that None means "not specified". - - For "required", any True value overrides all other values (a property that was previously required - cannot become optional). - """ - current = base - for override in extend_with: - if override.default is not None: - override_default = current.convert_value(override.default.raw_value) - else: - override_default = None - if isinstance(override_default, PropertyError): - return override_default - current = evolve( - current, # type: ignore # can't prove that every property type is an attrs class, but it is - required=current.required or override.required, - default=override_default or current.default, - description=override.description or current.description, - example=override.example or current.example, - ) - return current - - -def _values_are_subset(prop1: EnumProperty, prop2: EnumProperty) -> bool: - return set(prop1.values.items()) <= set(prop2.values.items()) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py deleted file mode 100644 index 76262450113c..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/model_property.py +++ /dev/null @@ -1,444 +0,0 @@ -from __future__ import annotations - -from itertools import chain -from typing import Any, ClassVar, NamedTuple - -from attrs import define, evolve - -from ... import Config, utils -from ... import schema as oai -from ...utils import PythonIdentifier -from ..errors import ParseError, PropertyError -from .any import AnyProperty -from .protocol import PropertyProtocol, Value -from .schemas import Class, ReferencePath, Schemas, parse_reference_path - - -@define -class ModelProperty(PropertyProtocol): - """A property which refers to another Schema""" - - name: str - required: bool - default: Value | None - python_name: utils.PythonIdentifier - example: str | None - class_info: Class - data: oai.Schema - description: str - roots: set[ReferencePath | utils.ClassName] - required_properties: list[Property] | None - optional_properties: list[Property] | None - relative_imports: set[str] | None - lazy_imports: set[str] | None - additional_properties: Property | None - _json_type_string: ClassVar[str] = "dict[str, Any]" - - template: ClassVar[str] = "model_property.py.jinja" - json_is_dict: ClassVar[bool] = True - is_multipart_body: bool = False - - @classmethod - def build( - cls, - *, - data: oai.Schema, - name: str, - schemas: Schemas, - required: bool, - parent_name: str | None, - config: Config, - process_properties: bool, - roots: set[ReferencePath | utils.ClassName], - ) -> tuple[ModelProperty | PropertyError, Schemas]: - """ - A single ModelProperty from its OAI data - - Args: - data: Data of a single Schema - name: Name by which the schema is referenced, such as a model name. - Used to infer the type name if a `title` property is not available. - schemas: Existing Schemas which have already been processed (to check name conflicts) - required: Whether or not this property is required by the parent (affects typing) - parent_name: The name of the property that this property is inside of (affects class naming) - config: Config data for this run of the generator, used to modifying names - roots: Set of strings that identify schema objects on which the new ModelProperty will depend - process_properties: Determines whether the new ModelProperty will be initialized with property data - """ - if not config.use_path_prefixes_for_title_model_names and data.title: - class_string = data.title - else: - title = data.title or name - if parent_name: - class_string = f"{utils.pascal_case(parent_name)}{utils.pascal_case(title)}" - else: - class_string = title - class_info = Class.from_string(string=class_string, config=config) - model_roots = {*roots, class_info.name} - required_properties: list[Property] | None = None - optional_properties: list[Property] | None = None - relative_imports: set[str] | None = None - lazy_imports: set[str] | None = None - additional_properties: Property | None = None - if process_properties: - data_or_err, schemas = _process_property_data( - data=data, schemas=schemas, class_info=class_info, config=config, roots=model_roots - ) - if isinstance(data_or_err, PropertyError): - return data_or_err, schemas - property_data, additional_properties = data_or_err - required_properties = property_data.required_props - optional_properties = property_data.optional_props - relative_imports = property_data.relative_imports - lazy_imports = property_data.lazy_imports - for root in roots: - if isinstance(root, utils.ClassName): - continue - schemas.add_dependencies(root, {class_info.name}) - - prop = ModelProperty( - class_info=class_info, - data=data, - roots=model_roots, - required_properties=required_properties, - optional_properties=optional_properties, - relative_imports=relative_imports, - lazy_imports=lazy_imports, - additional_properties=additional_properties, - description=data.description or "", - default=None, - required=required, - name=name, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - example=data.example, - ) - if class_info.name in schemas.classes_by_name: - error = PropertyError( - data=data, detail=f'Attempted to generate duplicate models with name "{class_info.name}"' - ) - return error, schemas - - schemas = evolve( - schemas, - classes_by_name={**schemas.classes_by_name, class_info.name: prop}, - models_to_process=[*schemas.models_to_process, prop], - ) - return prop, schemas - - @classmethod - def convert_value(cls, value: Any) -> Value | None | PropertyError: - if value is not None: - return PropertyError(detail="ModelProperty cannot have a default value") # pragma: no cover - return None - - def __attrs_post_init__(self) -> None: - if self.relative_imports: - self.set_relative_imports(self.relative_imports) - - @property - def self_import(self) -> str: - """Constructs a self import statement from this ModelProperty's attributes""" - return f"models.{self.class_info.module_name} import {self.class_info.name}" - - def get_base_type_string(self, *, quoted: bool = False) -> str: - return f'"{self.class_info.name}"' if quoted else self.class_info.name - - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.update( - { - "from typing import cast", - } - ) - return imports - - def get_lazy_imports(self, *, prefix: str) -> set[str]: - """Get a set of lazy import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - return {f"from {prefix}{self.self_import}"} - - def set_relative_imports(self, relative_imports: set[str]) -> None: - """Set the relative imports set for this ModelProperty, filtering out self imports - - Args: - relative_imports: The set of relative import strings - """ - object.__setattr__(self, "relative_imports", {ri for ri in relative_imports if self.self_import not in ri}) - - def set_lazy_imports(self, lazy_imports: set[str]) -> None: - """Set the lazy imports set for this ModelProperty, filtering out self imports - - Args: - lazy_imports: The set of lazy import strings - """ - object.__setattr__(self, "lazy_imports", {li for li in lazy_imports if self.self_import not in li}) - - def get_type_string( - self, - no_optional: bool = False, - json: bool = False, - *, - multipart: bool = False, - quoted: bool = False, - ) -> str: - """ - Get a string representation of type that should be used when declaring this property - - Args: - no_optional: Do not include Optional or Unset even if the value is optional (needed for isinstance checks) - json: True if the type refers to the property after JSON serialization - """ - if json: - type_string = self.get_base_json_type_string() - elif multipart: - type_string = "tuple[None, bytes, str]" - else: - type_string = self.get_base_type_string() - - if quoted: - if type_string == self.class_info.name: - type_string = f"'{type_string}'" - - if no_optional or self.required: - return type_string - return f"Union[Unset, {type_string}]" - - -from .property import Property # noqa: E402 - - -def _resolve_naming_conflict(first: Property, second: Property, config: Config) -> PropertyError | None: - first.set_python_name(first.name, config=config, skip_snake_case=True) - second.set_python_name(second.name, config=config, skip_snake_case=True) - if first.python_name == second.python_name: - return PropertyError( - header="Conflicting property names", - detail=f"Properties {first.name} and {second.name} have the same python_name", - ) - return None - - -class _PropertyData(NamedTuple): - optional_props: list[Property] - required_props: list[Property] - relative_imports: set[str] - lazy_imports: set[str] - schemas: Schemas - - -def _process_properties( # noqa: PLR0912, PLR0911 - *, - data: oai.Schema, - schemas: Schemas, - class_name: utils.ClassName, - config: Config, - roots: set[ReferencePath | utils.ClassName], -) -> _PropertyData | PropertyError: - from . import property_from_data - from .merge_properties import merge_properties - - properties: dict[str, Property] = {} - relative_imports: set[str] = set() - lazy_imports: set[str] = set() - required_set = set(data.required or []) - - def _add_if_no_conflict(new_prop: Property) -> PropertyError | None: - nonlocal properties - - name_conflict = properties.get(new_prop.name) - merged_prop = merge_properties(name_conflict, new_prop) if name_conflict else new_prop - if isinstance(merged_prop, PropertyError): - merged_prop.header = f"Found conflicting properties named {new_prop.name} when creating {class_name}" - return merged_prop - - for other_prop in properties.values(): - if other_prop.name == merged_prop.name: - continue # Same property, probably just got merged - if other_prop.python_name != merged_prop.python_name: - continue - naming_error = _resolve_naming_conflict(merged_prop, other_prop, config) - if naming_error is not None: - return naming_error - - properties[merged_prop.name] = merged_prop - return None - - unprocessed_props: list[tuple[str, oai.Reference | oai.Schema]] = ( - list(data.properties.items()) if data.properties else [] - ) - for sub_prop in data.allOf: - if isinstance(sub_prop, oai.Reference): - ref_path = parse_reference_path(sub_prop.ref) - if isinstance(ref_path, ParseError): - return PropertyError(detail=ref_path.detail, data=sub_prop) - sub_model = schemas.classes_by_reference.get(ref_path) - if sub_model is None: - return PropertyError(f"Reference {sub_prop.ref} not found") - if not isinstance(sub_model, ModelProperty): - return PropertyError("Cannot take allOf a non-object") - # Properties of allOf references first should be processed first - if not ( - isinstance(sub_model.required_properties, list) and isinstance(sub_model.optional_properties, list) - ): - return PropertyError(f"Reference {sub_model.name} in allOf was not processed", data=sub_prop) - for prop in chain(sub_model.required_properties, sub_model.optional_properties): - err = _add_if_no_conflict(prop) - if err is not None: - return err - schemas.add_dependencies(ref_path=ref_path, roots=roots) - else: - unprocessed_props.extend(sub_prop.properties.items() if sub_prop.properties else []) - required_set.update(sub_prop.required or []) - - for key, value in unprocessed_props: - prop_required = key in required_set - prop_or_error: Property | (PropertyError | None) - prop_or_error, schemas = property_from_data( - name=key, - required=prop_required, - data=value, - schemas=schemas, - parent_name=class_name, - config=config, - roots=roots, - ) - if not isinstance(prop_or_error, PropertyError): - prop_or_error = _add_if_no_conflict(prop_or_error) - if isinstance(prop_or_error, PropertyError): - return prop_or_error - - required_properties = [] - optional_properties = [] - for prop in properties.values(): - if prop.required: - required_properties.append(prop) - else: - optional_properties.append(prop) - - lazy_imports.update(prop.get_lazy_imports(prefix="..")) - relative_imports.update(prop.get_imports(prefix="..")) - - return _PropertyData( - optional_props=optional_properties, - required_props=required_properties, - relative_imports=relative_imports, - lazy_imports=lazy_imports, - schemas=schemas, - ) - - -ANY_ADDITIONAL_PROPERTY = AnyProperty.build( - name="additional", - required=True, - default=None, - description="", - python_name=PythonIdentifier(value="additional", prefix=""), - example=None, -) - - -def _get_additional_properties( - *, - schema_additional: None | (bool | (oai.Reference | oai.Schema)), - schemas: Schemas, - class_name: utils.ClassName, - config: Config, - roots: set[ReferencePath | utils.ClassName], -) -> tuple[Property | None | PropertyError, Schemas]: - from . import property_from_data - - if schema_additional is None: - return ANY_ADDITIONAL_PROPERTY, schemas - - if isinstance(schema_additional, bool): - if schema_additional: - return ANY_ADDITIONAL_PROPERTY, schemas - return None, schemas - - if isinstance(schema_additional, oai.Schema) and not any(schema_additional.model_dump().values()): - # An empty schema - return ANY_ADDITIONAL_PROPERTY, schemas - - additional_properties, schemas = property_from_data( - name="AdditionalProperty", - required=True, # in the sense that if present in the dict will not be None - data=schema_additional, - schemas=schemas, - parent_name=class_name, - config=config, - roots=roots, - ) - return additional_properties, schemas - - -def _process_property_data( - *, - data: oai.Schema, - schemas: Schemas, - class_info: Class, - config: Config, - roots: set[ReferencePath | utils.ClassName], -) -> tuple[tuple[_PropertyData, Property | None] | PropertyError, Schemas]: - property_data = _process_properties( - data=data, schemas=schemas, class_name=class_info.name, config=config, roots=roots - ) - if isinstance(property_data, PropertyError): - return property_data, schemas - schemas = property_data.schemas - - additional_properties, schemas = _get_additional_properties( - schema_additional=data.additionalProperties, - schemas=schemas, - class_name=class_info.name, - config=config, - roots=roots, - ) - if isinstance(additional_properties, PropertyError): - return additional_properties, schemas - elif additional_properties is None: - pass - else: - property_data.relative_imports.update(additional_properties.get_imports(prefix="..")) - property_data.lazy_imports.update(additional_properties.get_lazy_imports(prefix="..")) - - return (property_data, additional_properties), schemas - - -def process_model(model_prop: ModelProperty, *, schemas: Schemas, config: Config) -> Schemas | PropertyError: - """Populate a ModelProperty instance's property data - Args: - model_prop: The ModelProperty to build property data for - schemas: Existing Schemas - config: Config data for this run of the generator, used to modifying names - Returns: - Either the updated `schemas` input or a `PropertyError` if something went wrong. - """ - data_or_err, schemas = _process_property_data( - data=model_prop.data, - schemas=schemas, - class_info=model_prop.class_info, - config=config, - roots=model_prop.roots, - ) - if isinstance(data_or_err, PropertyError): - return data_or_err - - property_data, additional_properties = data_or_err - - object.__setattr__(model_prop, "required_properties", property_data.required_props) - object.__setattr__(model_prop, "optional_properties", property_data.optional_props) - model_prop.set_relative_imports(property_data.relative_imports) - model_prop.set_lazy_imports(property_data.lazy_imports) - object.__setattr__(model_prop, "additional_properties", additional_properties) - return schemas diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/none.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/none.py deleted file mode 100644 index 9c473693dfb2..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/none.py +++ /dev/null @@ -1,61 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar - -from attr import define - -from ... import schema as oai -from ...utils import PythonIdentifier -from ..errors import PropertyError -from .protocol import PropertyProtocol, Value - - -@define -class NoneProperty(PropertyProtocol): - """A property that can only be None""" - - name: str - required: bool - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - - _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - _type_string: ClassVar[str] = "None" - _json_type_string: ClassVar[str] = "None" - - @classmethod - def build( - cls, - name: str, - required: bool, - default: Any, - python_name: PythonIdentifier, - description: str | None, - example: str | None, - ) -> NoneProperty | PropertyError: - checked_default = cls.convert_value(default) - if isinstance(checked_default, PropertyError): - return checked_default - return cls( - name=name, - required=required, - default=checked_default, - python_name=python_name, - description=description, - example=example, - ) - - @classmethod - def convert_value(cls, value: Any) -> Value | None | PropertyError: - if value is None or isinstance(value, Value): - return value - if isinstance(value, str): - if value == "None": - return Value(python_code=value, raw_value=value) - return PropertyError(f"Value {value} is not valid, only None is allowed") diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/property.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/property.py deleted file mode 100644 index 6e73a01ae425..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/property.py +++ /dev/null @@ -1,41 +0,0 @@ -__all__ = ["Property"] - -from typing import Union - -from typing_extensions import TypeAlias - -from .any import AnyProperty -from .boolean import BooleanProperty -from .const import ConstProperty -from .date import DateProperty -from .datetime import DateTimeProperty -from .enum_property import EnumProperty -from .file import FileProperty -from .float import FloatProperty -from .int import IntProperty -from .list_property import ListProperty -from .literal_enum_property import LiteralEnumProperty -from .model_property import ModelProperty -from .none import NoneProperty -from .string import StringProperty -from .union import UnionProperty -from .uuid import UuidProperty - -Property: TypeAlias = Union[ - AnyProperty, - BooleanProperty, - ConstProperty, - DateProperty, - DateTimeProperty, - EnumProperty, - LiteralEnumProperty, - FileProperty, - FloatProperty, - IntProperty, - ListProperty, - ModelProperty, - NoneProperty, - StringProperty, - UnionProperty, - UuidProperty, -] diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py deleted file mode 100644 index 9a5b51828b04..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/protocol.py +++ /dev/null @@ -1,187 +0,0 @@ -from __future__ import annotations - -__all__ = ["PropertyProtocol", "Value"] - -from abc import abstractmethod -from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, ClassVar, Protocol, TypeVar - -from ... import Config -from ... import schema as oai -from ...utils import PythonIdentifier -from ..errors import ParseError, PropertyError - -if TYPE_CHECKING: # pragma: no cover - from .model_property import ModelProperty -else: - ModelProperty = "ModelProperty" - - -@dataclass -class Value: - """ - Some literal values in OpenAPI documents (like defaults) have to be converted into Python code safely - (with string escaping, for example). We still keep the `raw_value` around for merging `allOf`. - """ - - python_code: str - raw_value: Any - - -PropertyType = TypeVar("PropertyType", bound="PropertyProtocol") - - -class PropertyProtocol(Protocol): - """ - Describes a single property for a schema - - Attributes: - template: Name of the template file (if any) to use for this property. Must be stored in - templates/property_templates and must contain two macros: construct and transform. Construct will be used to - build this property from JSON data (a response from an API). Transform will be used to convert this property - to JSON data (when sending a request to the API). - - Raises: - ValidationError: Raised when the default value fails to be converted to the expected type - """ - - name: str - required: bool - _type_string: ClassVar[str] = "" - _json_type_string: ClassVar[str] = "" # Type of the property after JSON serialization - _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - } - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - - template: ClassVar[str] = "any_property.py.jinja" - json_is_dict: ClassVar[bool] = False - - @abstractmethod - def convert_value(self, value: Any) -> Value | None | PropertyError: - """Convert a string value to a Value object""" - raise NotImplementedError() # pragma: no cover - - def validate_location(self, location: oai.ParameterLocation) -> ParseError | None: - """Returns an error if this type of property is not allowed in the given location""" - if location not in self._allowed_locations: - return ParseError(detail=f"{self.get_type_string()} is not allowed in {location}") - if location == oai.ParameterLocation.PATH and not self.required: - return ParseError(detail="Path parameter must be required") - return None - - def set_python_name(self, new_name: str, config: Config, skip_snake_case: bool = False) -> None: - """Mutates this Property to set a new python_name. - - Required to mutate due to how Properties are stored and the difficulty of updating them in-dict. - `new_name` will be validated before it is set, so `python_name` is not guaranteed to equal `new_name` after - calling this. - """ - object.__setattr__( - self, - "python_name", - PythonIdentifier(value=new_name, prefix=config.field_prefix, skip_snake_case=skip_snake_case), - ) - - def get_base_type_string(self, *, quoted: bool = False) -> str: - """Get the string describing the Python type of this property. Base types no require quoting.""" - return f'"{self._type_string}"' if not self.is_base_type and quoted else self._type_string - - def get_base_json_type_string(self, *, quoted: bool = False) -> str: - """Get the string describing the JSON type of this property. Base types no require quoting.""" - return f'"{self._json_type_string}"' if not self.is_base_type and quoted else self._json_type_string - - def get_type_string( - self, - no_optional: bool = False, - json: bool = False, - *, - multipart: bool = False, - quoted: bool = False, - ) -> str: - """ - Get a string representation of type that should be used when declaring this property - - Args: - no_optional: Do not include Optional or Unset even if the value is optional (needed for isinstance checks) - json: True if the type refers to the property after JSON serialization - multipart: True if the type should be used in a multipart request - quoted: True if the type should be wrapped in quotes (if not a base type) - """ - if json: - type_string = self.get_base_json_type_string(quoted=quoted) - elif multipart: - type_string = "tuple[None, bytes, str]" - else: - type_string = self.get_base_type_string(quoted=quoted) - - if no_optional or self.required: - return type_string - return f"Union[Unset, {type_string}]" - - def get_instance_type_string(self) -> str: - """Get a string representation of runtime type that should be used for `isinstance` checks""" - return self.get_type_string(no_optional=True, quoted=False) - - # noinspection PyUnusedLocal - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = set() - if not self.required: - imports.add("from typing import Union") - imports.add(f"from {prefix}types import UNSET, Unset") - return imports - - def get_lazy_imports(self, *, prefix: str) -> set[str]: - """Get a set of lazy import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - return set() - - def to_string(self) -> str: - """How this should be declared in a dataclass""" - default: str | None - if self.default is not None: - default = self.default.python_code - elif not self.required: - default = "UNSET" - else: - default = None - - if default is not None: - return f"{self.python_name}: {self.get_type_string(quoted=True)} = {default}" - return f"{self.python_name}: {self.get_type_string(quoted=True)}" - - def to_docstring(self) -> str: - """Returns property docstring""" - doc = f"{self.python_name} ({self.get_type_string()}): {self.description or ''}" - if self.default: - doc += f" Default: {self.default.python_code}." - if self.example: - doc += f" Example: {self.example}." - return doc - - @property - def is_base_type(self) -> bool: - """Base types, represented by any other of `Property` than `ModelProperty` should not be quoted.""" - from . import ListProperty, ModelProperty, UnionProperty - - return self.__class__.__name__ not in { - ModelProperty.__name__, - ListProperty.__name__, - UnionProperty.__name__, - } diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py deleted file mode 100644 index 177a86924545..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/schemas.py +++ /dev/null @@ -1,242 +0,0 @@ -__all__ = [ - "Class", - "Parameters", - "ReferencePath", - "Schemas", - "parameter_from_data", - "parameter_from_reference", - "parse_reference_path", - "update_parameters_with_data", - "update_schemas_with_data", -] - -from typing import TYPE_CHECKING, NewType, Union, cast -from urllib.parse import urlparse - -from attrs import define, evolve, field - -from ... import Config -from ... import schema as oai -from ...schema.openapi_schema_pydantic import Parameter -from ...utils import ClassName, PythonIdentifier -from ..errors import ParameterError, ParseError, PropertyError - -if TYPE_CHECKING: # pragma: no cover - from .model_property import ModelProperty - from .property import Property -else: - ModelProperty = "ModelProperty" - Property = "Property" - - -ReferencePath = NewType("ReferencePath", str) - - -def parse_reference_path(ref_path_raw: str) -> Union[ReferencePath, ParseError]: - """ - Takes a raw string provided in a `$ref` and turns it into a validated `_ReferencePath` or a `ParseError` if - validation fails. - - See Also: - - https://swagger.io/docs/specification/using-ref/ - """ - parsed = urlparse(ref_path_raw) - if parsed.scheme or parsed.path: - return ParseError(detail=f"Remote references such as {ref_path_raw} are not supported yet.") - return cast(ReferencePath, parsed.fragment) - - -@define -class Class: - """Represents Python class which will be generated from an OpenAPI schema""" - - name: ClassName - module_name: PythonIdentifier - - @staticmethod - def from_string(*, string: str, config: Config) -> "Class": - """Get a Class from an arbitrary string""" - class_name = string.split("/")[-1] # Get rid of ref path stuff - class_name = ClassName(class_name, config.field_prefix) - override = config.class_overrides.get(class_name) - - if override is not None and override.class_name is not None: - class_name = ClassName(override.class_name, config.field_prefix) - - if override is not None and override.module_name is not None: - module_name = override.module_name - else: - module_name = class_name - module_name = PythonIdentifier(module_name, config.field_prefix) - - return Class(name=class_name, module_name=module_name) - - -@define -class Schemas: - """Structure for containing all defined, shareable, and reusable schemas (attr classes and Enums)""" - - classes_by_reference: dict[ReferencePath, Property] = field(factory=dict) - dependencies: dict[ReferencePath, set[Union[ReferencePath, ClassName]]] = field(factory=dict) - classes_by_name: dict[ClassName, Property] = field(factory=dict) - models_to_process: list[ModelProperty] = field(factory=list) - errors: list[ParseError] = field(factory=list) - - def add_dependencies(self, ref_path: ReferencePath, roots: set[Union[ReferencePath, ClassName]]) -> None: - """Record new dependencies on the given ReferencePath - - Args: - ref_path: The ReferencePath being referenced - roots: A set of identifiers for the objects dependent on the object corresponding to `ref_path` - """ - self.dependencies.setdefault(ref_path, set()) - self.dependencies[ref_path].update(roots) - - -def update_schemas_with_data( - *, ref_path: ReferencePath, data: oai.Schema, schemas: Schemas, config: Config -) -> Union[Schemas, PropertyError]: - """ - Update a `Schemas` using some new reference. - - Args: - ref_path: The output of `parse_reference_path` (validated $ref). - data: The schema of the thing to add to Schemas. - schemas: `Schemas` up until now. - config: User-provided config for overriding default behavior. - - Returns: - Either the updated `schemas` input or a `PropertyError` if something went wrong. - - See Also: - - https://swagger.io/docs/specification/using-ref/ - """ - from . import property_from_data - - prop: Union[PropertyError, Property] - prop, schemas = property_from_data( - data=data, - name=ref_path, - schemas=schemas, - required=True, - parent_name="", - config=config, - # Don't process ModelProperty properties because schemas are still being created - process_properties=False, - roots={ref_path}, - ) - - if isinstance(prop, PropertyError): - prop.detail = f"{prop.header}: {prop.detail}" - prop.header = f"Unable to parse schema {ref_path}" - if isinstance(prop.data, oai.Reference) and prop.data.ref.endswith(ref_path): # pragma: nocover - prop.detail += ( - "\n\nRecursive and circular references are not supported directly in an array schema's 'items' section" - ) - return prop - - schemas = evolve(schemas, classes_by_reference={ref_path: prop, **schemas.classes_by_reference}) - return schemas - - -@define -class Parameters: - """Structure for containing all defined, shareable, and reusable parameters""" - - classes_by_reference: dict[ReferencePath, Parameter] = field(factory=dict) - classes_by_name: dict[ClassName, Parameter] = field(factory=dict) - errors: list[ParseError] = field(factory=list) - - -def parameter_from_data( - *, - name: str, - data: Union[oai.Reference, oai.Parameter], - parameters: Parameters, - config: Config, -) -> tuple[Union[Parameter, ParameterError], Parameters]: - """Generates parameters from an OpenAPI Parameter spec.""" - - if isinstance(data, oai.Reference): - return ParameterError("Unable to resolve another reference"), parameters - - if data.param_schema is None: - return ParameterError("Parameter has no schema"), parameters - - new_param = Parameter( - name=name, - required=data.required, - explode=data.explode, - style=data.style, - param_schema=data.param_schema, - param_in=data.param_in, - ) - parameters = evolve( - parameters, classes_by_name={**parameters.classes_by_name, ClassName(name, config.field_prefix): new_param} - ) - return new_param, parameters - - -def update_parameters_with_data( - *, ref_path: ReferencePath, data: oai.Parameter, parameters: Parameters, config: Config -) -> Union[Parameters, ParameterError]: - """ - Update a `Parameters` using some new reference. - - Args: - ref_path: The output of `parse_reference_path` (validated $ref). - data: The schema of the thing to add to Schemas. - parameters: `Parameters` up until now. - - Returns: - Either the updated `parameters` input or a `PropertyError` if something went wrong. - - See Also: - - https://swagger.io/docs/specification/using-ref/ - """ - param, parameters = parameter_from_data(data=data, name=data.name, parameters=parameters, config=config) - - if isinstance(param, ParameterError): - param.detail = f"{param.header}: {param.detail}" - param.header = f"Unable to parse parameter {ref_path}" - if isinstance(param.data, oai.Reference) and param.data.ref.endswith(ref_path): # pragma: nocover - param.detail += ( - "\n\nRecursive and circular references are not supported. " - "See https://github.com/openapi-generators/openapi-python-client/issues/466" - ) - return param - - parameters = evolve(parameters, classes_by_reference={ref_path: param, **parameters.classes_by_reference}) - return parameters - - -def parameter_from_reference( - *, - param: Union[oai.Reference, Parameter], - parameters: Parameters, -) -> Union[Parameter, ParameterError]: - """ - Returns a Parameter from a Reference or the Parameter itself if one was provided. - - Args: - param: A parameter by `Reference`. - parameters: `Parameters` up until now. - - Returns: - Either the updated `schemas` input or a `PropertyError` if something went wrong. - - See Also: - - https://swagger.io/docs/specification/using-ref/ - """ - if isinstance(param, Parameter): - return param - - ref_path = parse_reference_path(param.ref) - - if isinstance(ref_path, ParseError): - return ParameterError(detail=ref_path.detail) - - _resolved_parameter_class = parameters.classes_by_reference.get(ref_path, None) - if _resolved_parameter_class is None: - return ParameterError(detail=f"Reference `{ref_path}` not found.") - return _resolved_parameter_class diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/string.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/string.py deleted file mode 100644 index e40c1eee6894..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/string.py +++ /dev/null @@ -1,68 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar, overload - -from attr import define - -from ... import schema as oai -from ... import utils -from ...utils import PythonIdentifier -from ..errors import PropertyError -from .protocol import PropertyProtocol, Value - - -@define -class StringProperty(PropertyProtocol): - """A property of type str""" - - name: str - required: bool - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - _type_string: ClassVar[str] = "str" - _json_type_string: ClassVar[str] = "str" - _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - - @classmethod - def build( - cls, - name: str, - required: bool, - default: Any, - python_name: PythonIdentifier, - description: str | None, - example: str | None, - ) -> StringProperty | PropertyError: - checked_default = cls.convert_value(default) - return cls( - name=name, - required=required, - default=checked_default, - python_name=python_name, - description=description, - example=example, - ) - - @classmethod - @overload - def convert_value(cls, value: None) -> None: # type: ignore[misc] - ... # pragma: no cover - - @classmethod - @overload - def convert_value(cls, value: Any) -> Value: ... # pragma: no cover - - @classmethod - def convert_value(cls, value: Any) -> Value | None: - if value is None or isinstance(value, Value): - return value - if not isinstance(value, str): - value = str(value) - return Value(python_code=repr(utils.remove_string_escapes(value)), raw_value=value) diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/union.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/union.py deleted file mode 100644 index 8b7b02a4804f..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/union.py +++ /dev/null @@ -1,191 +0,0 @@ -from __future__ import annotations - -from itertools import chain -from typing import Any, ClassVar, cast - -from attr import define, evolve - -from ... import Config -from ... import schema as oai -from ...utils import PythonIdentifier -from ..errors import ParseError, PropertyError -from .protocol import PropertyProtocol, Value -from .schemas import Schemas - - -@define -class UnionProperty(PropertyProtocol): - """A property representing a Union (anyOf) of other properties""" - - name: str - required: bool - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - inner_properties: list[PropertyProtocol] - template: ClassVar[str] = "union_property.py.jinja" - - @classmethod - def build( - cls, *, data: oai.Schema, name: str, required: bool, schemas: Schemas, parent_name: str, config: Config - ) -> tuple[UnionProperty | PropertyError, Schemas]: - """ - Create a `UnionProperty` the right way. - - Args: - data: The `Schema` describing the `UnionProperty`. - name: The name of the property where it appears in the OpenAPI document. - required: Whether this property is required where it's being used. - schemas: The `Schemas` so far describing existing classes / references. - parent_name: The name of the thing which holds this property (used for renaming inner classes). - config: User-defined config values for modifying inner properties. - - Returns: - `(result, schemas)` where `schemas` is the updated version of the input `schemas` and `result` is the - constructed `UnionProperty` or a `PropertyError` describing what went wrong. - """ - from . import property_from_data - - sub_properties: list[PropertyProtocol] = [] - - type_list_data = [] - if isinstance(data.type, list): - for _type in data.type: - type_list_data.append(data.model_copy(update={"type": _type, "default": None})) - - for i, sub_prop_data in enumerate(chain(data.anyOf, data.oneOf, type_list_data)): - sub_prop, schemas = property_from_data( - name=f"{name}_type_{i}", - required=True, - data=sub_prop_data, - schemas=schemas, - parent_name=parent_name, - config=config, - ) - if isinstance(sub_prop, PropertyError): - return PropertyError(detail=f"Invalid property in union {name}", data=sub_prop_data), schemas - sub_properties.append(sub_prop) - - def flatten_union_properties(sub_properties: list[PropertyProtocol]) -> list[PropertyProtocol]: - flattened = [] - for sub_prop in sub_properties: - if isinstance(sub_prop, UnionProperty): - flattened.extend(flatten_union_properties(sub_prop.inner_properties)) - else: - flattened.append(sub_prop) - return flattened - - sub_properties = flatten_union_properties(sub_properties) - - prop = UnionProperty( - name=name, - required=required, - default=None, - inner_properties=sub_properties, - python_name=PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ) - default_or_error = prop.convert_value(data.default) - if isinstance(default_or_error, PropertyError): - default_or_error.data = data - return default_or_error, schemas - prop = evolve(prop, default=default_or_error) - return prop, schemas - - def convert_value(self, value: Any) -> Value | None | PropertyError: - if value is None or isinstance(value, Value): - return None - value_or_error: Value | PropertyError | None = PropertyError( - detail=f"Invalid default value for union {self.name}" - ) - for sub_prop in self.inner_properties: - value_or_error = sub_prop.convert_value(value) - if not isinstance(value_or_error, PropertyError): - return value_or_error - return value_or_error - - def _get_inner_type_strings(self, json: bool, multipart: bool) -> set[str]: - return { - p.get_type_string(no_optional=True, json=json, multipart=multipart, quoted=not p.is_base_type) - for p in self.inner_properties - } - - @staticmethod - def _get_type_string_from_inner_type_strings(inner_types: set[str]) -> str: - if len(inner_types) == 1: - return inner_types.pop() - return f"Union[{', '.join(sorted(inner_types))}]" - - def get_base_type_string(self, *, quoted: bool = False) -> str: - return self._get_type_string_from_inner_type_strings(self._get_inner_type_strings(json=False, multipart=False)) - - def get_base_json_type_string(self, *, quoted: bool = False) -> str: - return self._get_type_string_from_inner_type_strings(self._get_inner_type_strings(json=True, multipart=False)) - - def get_type_strings_in_union(self, *, no_optional: bool = False, json: bool, multipart: bool) -> set[str]: - """ - Get the set of all the types that should appear within the `Union` representing this property. - - This function is called from the union property macros, thus the public visibility. - - Args: - no_optional: Do not include `None` or `Unset` in this set. - json: If True, this returns the JSON types, not the Python types, of this property. - multipart: If True, this returns the multipart types, not the Python types, of this property. - - Returns: - A set of strings containing the types that should appear within `Union`. - """ - type_strings = self._get_inner_type_strings(json=json, multipart=multipart) - if no_optional: - return type_strings - if not self.required: - type_strings.add("Unset") - return type_strings - - def get_type_string( - self, - no_optional: bool = False, - json: bool = False, - *, - multipart: bool = False, - quoted: bool = False, - ) -> str: - """ - Get a string representation of type that should be used when declaring this property. - This implementation differs slightly from `Property.get_type_string` in order to collapse - nested union types. - """ - type_strings_in_union = self.get_type_strings_in_union(no_optional=no_optional, json=json, multipart=multipart) - return self._get_type_string_from_inner_type_strings(type_strings_in_union) - - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - for inner_prop in self.inner_properties: - imports.update(inner_prop.get_imports(prefix=prefix)) - imports.add("from typing import cast, Union") - return imports - - def get_lazy_imports(self, *, prefix: str) -> set[str]: - lazy_imports = super().get_lazy_imports(prefix=prefix) - for inner_prop in self.inner_properties: - lazy_imports.update(inner_prop.get_lazy_imports(prefix=prefix)) - return lazy_imports - - def validate_location(self, location: oai.ParameterLocation) -> ParseError | None: - """Returns an error if this type of property is not allowed in the given location""" - from ..properties import Property - - for inner_prop in self.inner_properties: - if evolve(cast(Property, inner_prop), required=self.required).validate_location(location) is not None: - return ParseError(detail=f"{self.get_type_string()} is not allowed in {location}") - return None diff --git a/chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py b/chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py deleted file mode 100644 index 86d7d6a0abeb..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/properties/uuid.py +++ /dev/null @@ -1,80 +0,0 @@ -from __future__ import annotations - -from typing import Any, ClassVar -from uuid import UUID - -from attr import define - -from ... import schema as oai -from ...utils import PythonIdentifier -from ..errors import PropertyError -from .protocol import PropertyProtocol, Value - - -@define -class UuidProperty(PropertyProtocol): - """A property of type uuid.UUID""" - - name: str - required: bool - default: Value | None - python_name: PythonIdentifier - description: str | None - example: str | None - - _type_string: ClassVar[str] = "UUID" - _json_type_string: ClassVar[str] = "str" - _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - template: ClassVar[str] = "uuid_property.py.jinja" - - @classmethod - def build( - cls, - name: str, - required: bool, - default: Any, - python_name: PythonIdentifier, - description: str | None, - example: str | None, - ) -> UuidProperty | PropertyError: - checked_default = cls.convert_value(default) - if isinstance(checked_default, PropertyError): - return checked_default - - return cls( - name=name, - required=required, - default=checked_default, - python_name=python_name, - description=description, - example=example, - ) - - @classmethod - def convert_value(cls, value: Any) -> Value | None | PropertyError: - if value is None or isinstance(value, Value): - return value - if isinstance(value, str): - try: - UUID(value) - except ValueError: - return PropertyError(f"Invalid UUID value: {value}") - return Value(python_code=f"UUID('{value}')", raw_value=value) - return PropertyError(f"Invalid UUID value: {value}") - - def get_imports(self, *, prefix: str) -> set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.update({"from uuid import UUID"}) - return imports diff --git a/chaotic-openapi/chaotic_openapi/front/parser/responses.py b/chaotic-openapi/chaotic_openapi/front/parser/responses.py deleted file mode 100644 index 17c8a6ef143f..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/parser/responses.py +++ /dev/null @@ -1,150 +0,0 @@ -__all__ = ["Response", "response_from_data"] - -from http import HTTPStatus -from typing import Optional, TypedDict, Union - -from attrs import define - -from .. import utils - -from .. import Config -from .. import schema as oai -from ..utils import PythonIdentifier -from .errors import ParseError, PropertyError -from .properties import AnyProperty, Property, Schemas, property_from_data - - -class _ResponseSource(TypedDict): - """What data should be pulled from the httpx Response object""" - - attribute: str - return_type: str - - -JSON_SOURCE = _ResponseSource(attribute="response.json()", return_type="Any") -BYTES_SOURCE = _ResponseSource(attribute="response.content", return_type="bytes") -TEXT_SOURCE = _ResponseSource(attribute="response.text", return_type="str") -NONE_SOURCE = _ResponseSource(attribute="None", return_type="None") - - -@define -class Response: - """Describes a single response for an endpoint""" - - status_code: HTTPStatus - prop: Property - source: _ResponseSource - data: Union[oai.Response, oai.Reference] # Original data which created this response, useful for custom templates - - -def _source_by_content_type(content_type: str, config: Config) -> Optional[_ResponseSource]: - parsed_content_type = utils.get_content_type(content_type, config) - if parsed_content_type is None: - return None - - if parsed_content_type.startswith("text/"): - return TEXT_SOURCE - - known_content_types = { - "application/json": JSON_SOURCE, - "application/octet-stream": BYTES_SOURCE, - } - source = known_content_types.get(parsed_content_type) - if source is None and parsed_content_type.endswith("+json"): - # Implements https://www.rfc-editor.org/rfc/rfc6838#section-4.2.8 for the +json suffix - source = JSON_SOURCE - return source - - -def empty_response( - *, - status_code: HTTPStatus, - response_name: str, - config: Config, - data: Union[oai.Response, oai.Reference], -) -> Response: - """Return an untyped response, for when no response type is defined""" - return Response( - data=data, - status_code=status_code, - prop=AnyProperty( - name=response_name, - default=None, - required=True, - python_name=PythonIdentifier(value=response_name, prefix=config.field_prefix), - description=data.description if isinstance(data, oai.Response) else None, - example=None, - ), - source=NONE_SOURCE, - ) - - -def response_from_data( - *, - status_code: HTTPStatus, - data: Union[oai.Response, oai.Reference], - schemas: Schemas, - parent_name: str, - config: Config, -) -> tuple[Union[Response, ParseError], Schemas]: - """Generate a Response from the OpenAPI dictionary representation of it""" - - response_name = f"response_{status_code}" - if isinstance(data, oai.Reference): - return ( - empty_response( - status_code=status_code, - response_name=response_name, - config=config, - data=data, - ), - schemas, - ) - - content = data.content - if not content: - return ( - empty_response( - status_code=status_code, - response_name=response_name, - config=config, - data=data, - ), - schemas, - ) - - for content_type, media_type in content.items(): - source = _source_by_content_type(content_type, config) - if source is not None: - schema_data = media_type.media_type_schema - break - else: - return ( - ParseError(data=data, detail=f"Unsupported content_type {content}"), - schemas, - ) - - if schema_data is None: - return ( - empty_response( - status_code=status_code, - response_name=response_name, - config=config, - data=data, - ), - schemas, - ) - - prop, schemas = property_from_data( - name=response_name, - required=True, - data=schema_data, - schemas=schemas, - parent_name=parent_name, - config=config, - ) - - if isinstance(prop, PropertyError): - return prop, schemas - - return Response(status_code=status_code, prop=prop, source=source, data=data), schemas diff --git a/chaotic-openapi/chaotic_openapi/front/schema/3.0.3.md b/chaotic-openapi/chaotic_openapi/front/schema/3.0.3.md deleted file mode 100644 index e21aa4655495..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/3.0.3.md +++ /dev/null @@ -1,3454 +0,0 @@ -# OpenAPI Specification - -#### Version 3.0.3 - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://tools.ietf.org/html/bcp14) [RFC2119](https://tools.ietf.org/html/rfc2119) [RFC8174](https://tools.ietf.org/html/rfc8174) when, and only when, they appear in all capitals, as shown here. - -This document is licensed under [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). - -## Introduction - -The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. - -An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases. - -## Table of Contents - - -- [Definitions](#definitions) - - [OpenAPI Document](#oasDocument) - - [Path Templating](#pathTemplating) - - [Media Types](#mediaTypes) - - [HTTP Status Codes](#httpCodes) -- [Specification](#specification) - - [Versions](#versions) - - [Format](#format) - - [Document Structure](#documentStructure) - - [Data Types](#dataTypes) - - [Rich Text Formatting](#richText) - - [Relative References In URLs](#relativeReferences) - - [Schema](#schema) - - [OpenAPI Object](#oasObject) - - [Info Object](#infoObject) - - [Contact Object](#contactObject) - - [License Object](#licenseObject) - - [Server Object](#serverObject) - - [Server Variable Object](#serverVariableObject) - - [Components Object](#componentsObject) - - [Paths Object](#pathsObject) - - [Path Item Object](#pathItemObject) - - [Operation Object](#operationObject) - - [External Documentation Object](#externalDocumentationObject) - - [Parameter Object](#parameterObject) - - [Request Body Object](#requestBodyObject) - - [Media Type Object](#mediaTypeObject) - - [Encoding Object](#encodingObject) - - [Responses Object](#responsesObject) - - [Response Object](#responseObject) - - [Callback Object](#callbackObject) - - [Example Object](#exampleObject) - - [Link Object](#linkObject) - - [Header Object](#headerObject) - - [Tag Object](#tagObject) - - [Reference Object](#referenceObject) - - [Schema Object](#schemaObject) - - [Discriminator Object](#discriminatorObject) - - [XML Object](#xmlObject) - - [Security Scheme Object](#securitySchemeObject) - - [OAuth Flows Object](#oauthFlowsObject) - - [OAuth Flow Object](#oauthFlowObject) - - [Security Requirement Object](#securityRequirementObject) - - [Specification Extensions](#specificationExtensions) - - [Security Filtering](#securityFiltering) -- [Appendix A: Revision History](#revisionHistory) - - - - -## Definitions - -##### OpenAPI Document -A document (or set of documents) that defines or describes an API. An OpenAPI definition uses and conforms to the OpenAPI Specification. - -##### Path Templating -Path templating refers to the usage of template expressions, delimited by curly braces ({}), to mark a section of a URL path as replaceable using path parameters. - -Each template expression in the path MUST correspond to a path parameter that is included in the [Path Item](#path-item-object) itself and/or in each of the Path Item's [Operations](#operation-object). - -##### Media Types -Media type definitions are spread across several resources. -The media type definitions SHOULD be in compliance with [RFC6838](https://tools.ietf.org/html/rfc6838). - -Some examples of possible media type definitions: -``` - text/plain; charset=utf-8 - application/json - application/vnd.github+json - application/vnd.github.v3+json - application/vnd.github.v3.raw+json - application/vnd.github.v3.text+json - application/vnd.github.v3.html+json - application/vnd.github.v3.full+json - application/vnd.github.v3.diff - application/vnd.github.v3.patch -``` -##### HTTP Status Codes -The HTTP Status Codes are used to indicate the status of the executed operation. -The available status codes are defined by [RFC7231](https://tools.ietf.org/html/rfc7231#section-6) and registered status codes are listed in the [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml). - -## Specification - -### Versions - -The OpenAPI Specification is versioned using [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html) (semver) and follows the semver specification. - -The `major`.`minor` portion of the semver (for example `3.0`) SHALL designate the OAS feature set. Typically, *`.patch`* versions address errors in this document, not the feature set. Tooling which supports OAS 3.0 SHOULD be compatible with all OAS 3.0.\* versions. The patch version SHOULD NOT be considered by tooling, making no distinction between `3.0.0` and `3.0.1` for example. - -Each new minor version of the OpenAPI Specification SHALL allow any OpenAPI document that is valid against any previous minor version of the Specification, within the same major version, to be updated to the new Specification version with equivalent semantics. Such an update MUST only require changing the `openapi` property to the new minor version. - -For example, a valid OpenAPI 3.0.2 document, upon changing its `openapi` property to `3.1.0`, SHALL be a valid OpenAPI 3.1.0 document, semantically equivalent to the original OpenAPI 3.0.2 document. New minor versions of the OpenAPI Specification MUST be written to ensure this form of backward compatibility. - -An OpenAPI document compatible with OAS 3.\*.\* contains a required [`openapi`](#oasVersion) field which designates the semantic version of the OAS that it uses. (OAS 2.0 documents contain a top-level version field named [`swagger`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swaggerObject) and value `"2.0"`.) - -### Format - -An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either in JSON or YAML format. - -For example, if a field has an array value, the JSON array representation will be used: - -```json -{ - "field": [ 1, 2, 3 ] -} -``` -All field names in the specification are **case sensitive**. -This includes all fields that are used as keys in a map, except where explicitly noted that keys are **case insensitive**. - -The schema exposes two types of fields: Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name. - -Patterned fields MUST have unique names within the containing object. - -In order to preserve the ability to round-trip between YAML and JSON formats, YAML version [1.2](https://yaml.org/spec/1.2/spec.html) is RECOMMENDED along with some additional constraints: - -- Tags MUST be limited to those allowed by the [JSON Schema ruleset](https://yaml.org/spec/1.2/spec.html#id2803231). -- Keys used in YAML maps MUST be limited to a scalar string, as defined by the [YAML Failsafe schema ruleset](https://yaml.org/spec/1.2/spec.html#id2802346). - -**Note:** While APIs may be defined by OpenAPI documents in either YAML or JSON format, the API request and response bodies and other content are not required to be JSON or YAML. - -### Document Structure - -An OpenAPI document MAY be made up of a single document or be divided into multiple, connected parts at the discretion of the user. In the latter case, `$ref` fields MUST be used in the specification to reference those parts as follows from the [JSON Schema](https://json-schema.org) definitions. - -It is RECOMMENDED that the root OpenAPI document be named: `openapi.json` or `openapi.yaml`. - -### Data Types - -Primitive data types in the OAS are based on the types supported by the [JSON Schema Specification Wright Draft 00](https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2). -Note that `integer` as a type is also supported and is defined as a JSON number without a fraction or exponent part. -`null` is not supported as a type (see [`nullable`](#schemaNullable) for an alternative solution). -Models are defined using the [Schema Object](#schemaObject), which is an extended subset of JSON Schema Specification Wright Draft 00. - -Primitives have an optional modifier property: `format`. -OAS uses several known formats to define in fine detail the data type being used. -However, to support documentation needs, the `format` property is an open `string`-valued property, and can have any value. -Formats such as `"email"`, `"uuid"`, and so on, MAY be used even though undefined by this specification. -Types that are not accompanied by a `format` property follow the type definition in the JSON Schema. Tools that do not recognize a specific `format` MAY default back to the `type` alone, as if the `format` is not specified. - -The formats defined by the OAS are: - -[`type`](#dataTypes) | [`format`](#dataTypeFormat) | Comments ------- | -------- | -------- -`integer` | `int32` | signed 32 bits -`integer` | `int64` | signed 64 bits (a.k.a long) -`number` | `float` | | -`number` | `double` | | -`string` | | | -`string` | `byte` | base64 encoded characters -`string` | `binary` | any sequence of octets -`boolean` | | | -`string` | `date` | As defined by `full-date` - [RFC3339](https://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14) -`string` | `date-time` | As defined by `date-time` - [RFC3339](https://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14) -`string` | `password` | A hint to UIs to obscure input. - - -### Rich Text Formatting -Throughout the specification `description` fields are noted as supporting CommonMark markdown formatting. -Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by [CommonMark 0.27](https://spec.commonmark.org/0.27/). Tooling MAY choose to ignore some CommonMark features to address security concerns. - -### Relative References in URLs - -Unless specified otherwise, all properties that are URLs MAY be relative references as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-4.2). -Relative references are resolved using the URLs defined in the [`Server Object`](#serverObject) as a Base URI. - -Relative references used in `$ref` are processed as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03), using the URL of the current document as the base URI. See also the [Reference Object](#referenceObject). - -### Schema - -In the following description, if a field is not explicitly **REQUIRED** or described with a MUST or SHALL, it can be considered OPTIONAL. - -#### OpenAPI Object - -This is the root document object of the [OpenAPI document](#oasDocument). - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -openapi | `string` | **REQUIRED**. This string MUST be the [semantic version number](https://semver.org/spec/v2.0.0.html) of the [OpenAPI Specification version](#versions) that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document. This is *not* related to the API [`info.version`](#infoVersion) string. -info | [Info Object](#infoObject) | **REQUIRED**. Provides metadata about the API. The metadata MAY be used by tooling as required. -servers | [[Server Object](#serverObject)] | An array of Server Objects, which provide connectivity information to a target server. If the `servers` property is not provided, or is an empty array, the default value would be a [Server Object](#serverObject) with a [url](#serverUrl) value of `/`. -paths | [Paths Object](#pathsObject) | **REQUIRED**. The available paths and operations for the API. -components | [Components Object](#componentsObject) | An element to hold various schemas for the specification. -security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement (`{}`) can be included in the array. -tags | [[Tag Object](#tagObject)] | A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](#operationObject) must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. -externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -#### Info Object - -The object provides metadata about the API. -The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -title | `string` | **REQUIRED**. The title of the API. -description | `string` | A short description of the API. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -termsOfService | `string` | A URL to the Terms of Service for the API. MUST be in the format of a URL. -contact | [Contact Object](#contactObject) | The contact information for the exposed API. -license | [License Object](#licenseObject) | The license information for the exposed API. -version | `string` | **REQUIRED**. The version of the OpenAPI document (which is distinct from the [OpenAPI Specification version](#oasVersion) or the API implementation version). - - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Info Object Example - -```json -{ - "title": "Sample Pet Store App", - "description": "This is a sample server for a pet store.", - "termsOfService": "http://example.com/terms/", - "contact": { - "name": "API Support", - "url": "http://www.example.com/support", - "email": "support@example.com" - }, - "license": { - "name": "Apache 2.0", - "url": "https://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "1.0.1" -} -``` - -```yaml -title: Sample Pet Store App -description: This is a sample server for a pet store. -termsOfService: http://example.com/terms/ -contact: - name: API Support - url: http://www.example.com/support - email: support@example.com -license: - name: Apache 2.0 - url: https://www.apache.org/licenses/LICENSE-2.0.html -version: 1.0.1 -``` - -#### Contact Object - -Contact information for the exposed API. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -name | `string` | The identifying name of the contact person/organization. -url | `string` | The URL pointing to the contact information. MUST be in the format of a URL. -email | `string` | The email address of the contact person/organization. MUST be in the format of an email address. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Contact Object Example - -```json -{ - "name": "API Support", - "url": "http://www.example.com/support", - "email": "support@example.com" -} -``` - -```yaml -name: API Support -url: http://www.example.com/support -email: support@example.com -``` - -#### License Object - -License information for the exposed API. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -name | `string` | **REQUIRED**. The license name used for the API. -url | `string` | A URL to the license used for the API. MUST be in the format of a URL. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### License Object Example - -```json -{ - "name": "Apache 2.0", - "url": "https://www.apache.org/licenses/LICENSE-2.0.html" -} -``` - -```yaml -name: Apache 2.0 -url: https://www.apache.org/licenses/LICENSE-2.0.html -``` - -#### Server Object - -An object representing a Server. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -url | `string` | **REQUIRED**. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{`brackets`}`. -description | `string` | An optional string describing the host designated by the URL. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -variables | Map[`string`, [Server Variable Object](#serverVariableObject)] | A map between a variable name and its value. The value is used for substitution in the server's URL template. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Server Object Example - -A single server would be described as: - -```json -{ - "url": "https://development.gigantic-server.com/v1", - "description": "Development server" -} -``` - -```yaml -url: https://development.gigantic-server.com/v1 -description: Development server -``` - -The following shows how multiple servers can be described, for example, at the OpenAPI Object's [`servers`](#oasServers): - -```json -{ - "servers": [ - { - "url": "https://development.gigantic-server.com/v1", - "description": "Development server" - }, - { - "url": "https://staging.gigantic-server.com/v1", - "description": "Staging server" - }, - { - "url": "https://api.gigantic-server.com/v1", - "description": "Production server" - } - ] -} -``` - -```yaml -servers: -- url: https://development.gigantic-server.com/v1 - description: Development server -- url: https://staging.gigantic-server.com/v1 - description: Staging server -- url: https://api.gigantic-server.com/v1 - description: Production server -``` - -The following shows how variables can be used for a server configuration: - -```json -{ - "servers": [ - { - "url": "https://{username}.gigantic-server.com:{port}/{basePath}", - "description": "The production API server", - "variables": { - "username": { - "default": "demo", - "description": "this value is assigned by the service provider, in this example `gigantic-server.com`" - }, - "port": { - "enum": [ - "8443", - "443" - ], - "default": "8443" - }, - "basePath": { - "default": "v2" - } - } - } - ] -} -``` - -```yaml -servers: -- url: https://{username}.gigantic-server.com:{port}/{basePath} - description: The production API server - variables: - username: - # note! no enum here means it is an open value - default: demo - description: this value is assigned by the service provider, in this example `gigantic-server.com` - port: - enum: - - '8443' - - '443' - default: '8443' - basePath: - # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2` - default: v2 -``` - - -#### Server Variable Object - -An object representing a Server Variable for server URL template substitution. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -enum | [`string`] | An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty. -default | `string` | **REQUIRED**. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. Note this behavior is different than the [Schema Object's](#schemaObject) treatment of default values, because in those cases parameter values are optional. If the [`enum`](#serverVariableEnum) is defined, the value SHOULD exist in the enum's values. -description | `string` | An optional description for the server variable. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -#### Components Object - -Holds a set of reusable objects for different aspects of the OAS. -All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. - - -##### Fixed Fields - -Field Name | Type | Description ----|:---|--- - schemas | Map[`string`, [Schema Object](#schemaObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Schema Objects](#schemaObject). - responses | Map[`string`, [Response Object](#responseObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Response Objects](#responseObject). - parameters | Map[`string`, [Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Parameter Objects](#parameterObject). - examples | Map[`string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Example Objects](#exampleObject). - requestBodies | Map[`string`, [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Request Body Objects](#requestBodyObject). - headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Header Objects](#headerObject). - securitySchemes| Map[`string`, [Security Scheme Object](#securitySchemeObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Security Scheme Objects](#securitySchemeObject). - links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Link Objects](#linkObject). - callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Callback Objects](#callbackObject). - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`. - -Field Name Examples: - -``` -User -User_1 -User_Name -user-name -my.org.User -``` - -##### Components Object Example - -```json -"components": { - "schemas": { - "GeneralError": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - }, - "Category": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - } - }, - "Tag": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - } - } - }, - "parameters": { - "skipParam": { - "name": "skip", - "in": "query", - "description": "number of items to skip", - "required": true, - "schema": { - "type": "integer", - "format": "int32" - } - }, - "limitParam": { - "name": "limit", - "in": "query", - "description": "max records to return", - "required": true, - "schema" : { - "type": "integer", - "format": "int32" - } - } - }, - "responses": { - "NotFound": { - "description": "Entity not found." - }, - "IllegalInput": { - "description": "Illegal input for operation." - }, - "GeneralError": { - "description": "General Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GeneralError" - } - } - } - } - }, - "securitySchemes": { - "api_key": { - "type": "apiKey", - "name": "api_key", - "in": "header" - }, - "petstore_auth": { - "type": "oauth2", - "flows": { - "implicit": { - "authorizationUrl": "http://example.org/api/oauth/dialog", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - } - } - } - } -} -``` - -```yaml -components: - schemas: - GeneralError: - type: object - properties: - code: - type: integer - format: int32 - message: - type: string - Category: - type: object - properties: - id: - type: integer - format: int64 - name: - type: string - Tag: - type: object - properties: - id: - type: integer - format: int64 - name: - type: string - parameters: - skipParam: - name: skip - in: query - description: number of items to skip - required: true - schema: - type: integer - format: int32 - limitParam: - name: limit - in: query - description: max records to return - required: true - schema: - type: integer - format: int32 - responses: - NotFound: - description: Entity not found. - IllegalInput: - description: Illegal input for operation. - GeneralError: - description: General Error - content: - application/json: - schema: - $ref: '#/components/schemas/GeneralError' - securitySchemes: - api_key: - type: apiKey - name: api_key - in: header - petstore_auth: - type: oauth2 - flows: - implicit: - authorizationUrl: http://example.org/api/oauth/dialog - scopes: - write:pets: modify pets in your account - read:pets: read your pets -``` - - -#### Paths Object - -Holds the relative paths to the individual endpoints and their operations. -The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. The Paths MAY be empty, due to [ACL constraints](#securityFiltering). - -##### Patterned Fields - -Field Pattern | Type | Description ----|:---:|--- -/{path} | [Path Item Object](#pathItemObject) | A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is **appended** (no relative URL resolution) to the expanded URL from the [`Server Object`](#serverObject)'s `url` field in order to construct the full URL. [Path templating](#pathTemplating) is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Path Templating Matching - -Assuming the following paths, the concrete definition, `/pets/mine`, will be matched first if used: - -``` - /pets/{petId} - /pets/mine -``` - -The following paths are considered identical and invalid: - -``` - /pets/{petId} - /pets/{name} -``` - -The following may lead to ambiguous resolution: - -``` - /{entity}/me - /books/{id} -``` - -##### Paths Object Example - -```json -{ - "/pets": { - "get": { - "description": "Returns all pets from the system that the user has access to", - "responses": { - "200": { - "description": "A list of pets.", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/pet" - } - } - } - } - } - } - } - } -} -``` - -```yaml -/pets: - get: - description: Returns all pets from the system that the user has access to - responses: - '200': - description: A list of pets. - content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/pet' -``` - -#### Path Item Object - -Describes the operations available on a single path. -A Path Item MAY be empty, due to [ACL constraints](#securityFiltering). -The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -$ref | `string` | Allows for an external definition of this path item. The referenced structure MUST be in the format of a [Path Item Object](#pathItemObject). In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. -summary| `string` | An optional, string summary, intended to apply to all operations in this path. -description | `string` | An optional, string description, intended to apply to all operations in this path. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -get | [Operation Object](#operationObject) | A definition of a GET operation on this path. -put | [Operation Object](#operationObject) | A definition of a PUT operation on this path. -post | [Operation Object](#operationObject) | A definition of a POST operation on this path. -delete | [Operation Object](#operationObject) | A definition of a DELETE operation on this path. -options | [Operation Object](#operationObject) | A definition of a OPTIONS operation on this path. -head | [Operation Object](#operationObject) | A definition of a HEAD operation on this path. -patch | [Operation Object](#operationObject) | A definition of a PATCH operation on this path. -trace | [Operation Object](#operationObject) | A definition of a TRACE operation on this path. -servers | [[Server Object](#serverObject)] | An alternative `server` array to service all operations in this path. -parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). - - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Path Item Object Example - -```json -{ - "get": { - "description": "Returns pets based on ID", - "summary": "Find pets by ID", - "operationId": "getPetsById", - "responses": { - "200": { - "description": "pet response", - "content": { - "*/*": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Pet" - } - } - } - } - }, - "default": { - "description": "error payload", - "content": { - "text/html": { - "schema": { - "$ref": "#/components/schemas/ErrorModel" - } - } - } - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to use", - "required": true, - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "style": "simple" - } - ] -} -``` - -```yaml -get: - description: Returns pets based on ID - summary: Find pets by ID - operationId: getPetsById - responses: - '200': - description: pet response - content: - '*/*' : - schema: - type: array - items: - $ref: '#/components/schemas/Pet' - default: - description: error payload - content: - 'text/html': - schema: - $ref: '#/components/schemas/ErrorModel' -parameters: -- name: id - in: path - description: ID of pet to use - required: true - schema: - type: array - items: - type: string - style: simple -``` - -#### Operation Object - -Describes a single API operation on a path. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -tags | [`string`] | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. -summary | `string` | A short summary of what the operation does. -description | `string` | A verbose explanation of the operation behavior. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this operation. -operationId | `string` | Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is **case-sensitive**. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. -parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for this operation. If a parameter is already defined at the [Path Item](#pathItemParameters), the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). -requestBody | [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject) | The request body applicable for this operation. The `requestBody` is only supported in HTTP methods where the HTTP 1.1 specification [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, `requestBody` SHALL be ignored by consumers. -responses | [Responses Object](#responsesObject) | **REQUIRED**. The list of possible responses as they are returned from executing this operation. -callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a [Callback Object](#callbackObject) that describes a request that may be initiated by the API provider and the expected responses. -deprecated | `boolean` | Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`. -security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level [`security`](#oasSecurity). To remove a top-level security declaration, an empty array can be used. -servers | [[Server Object](#serverObject)] | An alternative `server` array to service this operation. If an alternative `server` object is specified at the Path Item Object or Root level, it will be overridden by this value. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Operation Object Example - -```json -{ - "tags": [ - "pet" - ], - "summary": "Updates a pet in the store with form data", - "operationId": "updatePetWithForm", - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be updated", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "type": "object", - "properties": { - "name": { - "description": "Updated name of the pet", - "type": "string" - }, - "status": { - "description": "Updated status of the pet", - "type": "string" - } - }, - "required": ["status"] - } - } - } - }, - "responses": { - "200": { - "description": "Pet updated.", - "content": { - "application/json": {}, - "application/xml": {} - } - }, - "405": { - "description": "Method Not Allowed", - "content": { - "application/json": {}, - "application/xml": {} - } - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] -} -``` - -```yaml -tags: -- pet -summary: Updates a pet in the store with form data -operationId: updatePetWithForm -parameters: -- name: petId - in: path - description: ID of pet that needs to be updated - required: true - schema: - type: string -requestBody: - content: - 'application/x-www-form-urlencoded': - schema: - properties: - name: - description: Updated name of the pet - type: string - status: - description: Updated status of the pet - type: string - required: - - status -responses: - '200': - description: Pet updated. - content: - 'application/json': {} - 'application/xml': {} - '405': - description: Method Not Allowed - content: - 'application/json': {} - 'application/xml': {} -security: -- petstore_auth: - - write:pets - - read:pets -``` - - -#### External Documentation Object - -Allows referencing an external resource for extended documentation. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -description | `string` | A short description of the target documentation. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -url | `string` | **REQUIRED**. The URL for the target documentation. Value MUST be in the format of a URL. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### External Documentation Object Example - -```json -{ - "description": "Find more info here", - "url": "https://example.com" -} -``` - -```yaml -description: Find more info here -url: https://example.com -``` - -#### Parameter Object - -Describes a single operation parameter. - -A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). - -##### Parameter Locations -There are four possible parameter locations specified by the `in` field: -* path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. -* query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. -* header - Custom headers that are expected as part of the request. Note that [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. -* cookie - Used to pass a specific cookie value to the API. - - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -name | `string` | **REQUIRED**. The name of the parameter. Parameter names are *case sensitive*.
  • If [`in`](#parameterIn) is `"path"`, the `name` field MUST correspond to a template expression occurring within the [path](#pathsPath) field in the [Paths Object](#pathsObject). See [Path Templating](#pathTemplating) for further information.
  • If [`in`](#parameterIn) is `"header"` and the `name` field is `"Accept"`, `"Content-Type"` or `"Authorization"`, the parameter definition SHALL be ignored.
  • For all other cases, the `name` corresponds to the parameter name used by the [`in`](#parameterIn) property.
-in | `string` | **REQUIRED**. The location of the parameter. Possible values are `"query"`, `"header"`, `"path"` or `"cookie"`. -description | `string` | A brief description of the parameter. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -required | `boolean` | Determines whether this parameter is mandatory. If the [parameter location](#parameterIn) is `"path"`, this property is **REQUIRED** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. - deprecated | `boolean` | Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`. - allowEmptyValue | `boolean` | Sets the ability to pass empty-valued parameters. This is valid only for `query` parameters and allows sending a parameter with an empty value. Default value is `false`. If [`style`](#parameterStyle) is used, and if behavior is `n/a` (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision. - -The rules for serialization of the parameter are specified in one of two ways. -For simpler scenarios, a [`schema`](#parameterSchema) and [`style`](#parameterStyle) can describe the structure and syntax of the parameter. - -Field Name | Type | Description ----|:---:|--- -style | `string` | Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `query` - `form`; for `path` - `simple`; for `header` - `simple`; for `cookie` - `form`. -explode | `boolean` | When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this property has no effect. When [`style`](#parameterStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. -allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. This property only applies to parameters with an `in` value of `query`. The default value is `false`. -schema | [Schema Object](#schemaObject) \| [Reference Object](#referenceObject) | The schema defining the type used for the parameter. -example | Any | Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` that contains an example, the `example` value SHALL _override_ the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary. -examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` that contains an example, the `examples` value SHALL _override_ the example provided by the schema. - -For more complex scenarios, the [`content`](#parameterContent) property can define the media type and schema of the parameter. -A parameter MUST contain either a `schema` property, or a `content` property, but not both. -When `example` or `examples` are provided in conjunction with the `schema` object, the example MUST follow the prescribed serialization strategy for the parameter. - - -Field Name | Type | Description ----|:---:|--- -content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. - -##### Style Values - -In order to support common ways of serializing simple parameters, a set of `style` values are defined. - -`style` | [`type`](#dataTypes) | `in` | Comments ------------ | ------ | -------- | -------- -matrix | `primitive`, `array`, `object` | `path` | Path-style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7) -label | `primitive`, `array`, `object` | `path` | Label style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.5) -form | `primitive`, `array`, `object` | `query`, `cookie` | Form style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.8). This option replaces `collectionFormat` with a `csv` (when `explode` is false) or `multi` (when `explode` is true) value from OpenAPI 2.0. -simple | `array` | `path`, `header` | Simple style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.2). This option replaces `collectionFormat` with a `csv` value from OpenAPI 2.0. -spaceDelimited | `array` | `query` | Space separated array values. This option replaces `collectionFormat` equal to `ssv` from OpenAPI 2.0. -pipeDelimited | `array` | `query` | Pipe separated array values. This option replaces `collectionFormat` equal to `pipes` from OpenAPI 2.0. -deepObject | `object` | `query` | Provides a simple way of rendering nested objects using form parameters. - - -##### Style Examples - -Assume a parameter named `color` has one of the following values: - -``` - string -> "blue" - array -> ["blue","black","brown"] - object -> { "R": 100, "G": 200, "B": 150 } -``` -The following table shows examples of rendering differences for each value. - -[`style`](#dataTypeFormat) | `explode` | `empty` | `string` | `array` | `object` ------------ | ------ | -------- | -------- | -------- | ------- -matrix | false | ;color | ;color=blue | ;color=blue,black,brown | ;color=R,100,G,200,B,150 -matrix | true | ;color | ;color=blue | ;color=blue;color=black;color=brown | ;R=100;G=200;B=150 -label | false | . | .blue | .blue.black.brown | .R.100.G.200.B.150 -label | true | . | .blue | .blue.black.brown | .R=100.G=200.B=150 -form | false | color= | color=blue | color=blue,black,brown | color=R,100,G,200,B,150 -form | true | color= | color=blue | color=blue&color=black&color=brown | R=100&G=200&B=150 -simple | false | n/a | blue | blue,black,brown | R,100,G,200,B,150 -simple | true | n/a | blue | blue,black,brown | R=100,G=200,B=150 -spaceDelimited | false | n/a | n/a | blue%20black%20brown | R%20100%20G%20200%20B%20150 -pipeDelimited | false | n/a | n/a | blue\|black\|brown | R\|100\|G\|200\|B\|150 -deepObject | true | n/a | n/a | n/a | color[R]=100&color[G]=200&color[B]=150 - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Parameter Object Examples - -A header parameter with an array of 64 bit integer numbers: - -```json -{ - "name": "token", - "in": "header", - "description": "token to be passed as a header", - "required": true, - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int64" - } - }, - "style": "simple" -} -``` - -```yaml -name: token -in: header -description: token to be passed as a header -required: true -schema: - type: array - items: - type: integer - format: int64 -style: simple -``` - -A path parameter of a string value: -```json -{ - "name": "username", - "in": "path", - "description": "username to fetch", - "required": true, - "schema": { - "type": "string" - } -} -``` - -```yaml -name: username -in: path -description: username to fetch -required: true -schema: - type: string -``` - -An optional query parameter of a string value, allowing multiple values by repeating the query parameter: -```json -{ - "name": "id", - "in": "query", - "description": "ID of the object to fetch", - "required": false, - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "style": "form", - "explode": true -} -``` - -```yaml -name: id -in: query -description: ID of the object to fetch -required: false -schema: - type: array - items: - type: string -style: form -explode: true -``` - -A free-form query parameter, allowing undefined parameters of a specific type: -```json -{ - "in": "query", - "name": "freeForm", - "schema": { - "type": "object", - "additionalProperties": { - "type": "integer" - }, - }, - "style": "form" -} -``` - -```yaml -in: query -name: freeForm -schema: - type: object - additionalProperties: - type: integer -style: form -``` - -A complex parameter using `content` to define serialization: - -```json -{ - "in": "query", - "name": "coordinates", - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "lat", - "long" - ], - "properties": { - "lat": { - "type": "number" - }, - "long": { - "type": "number" - } - } - } - } - } -} -``` - -```yaml -in: query -name: coordinates -content: - application/json: - schema: - type: object - required: - - lat - - long - properties: - lat: - type: number - long: - type: number -``` - -#### Request Body Object - -Describes a single request body. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -description | `string` | A brief description of the request body. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -content | Map[`string`, [Media Type Object](#mediaTypeObject)] | **REQUIRED**. The content of the request body. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* -required | `boolean` | Determines if the request body is required in the request. Defaults to `false`. - - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Request Body Examples - -A request body with a referenced model definition. -```json -{ - "description": "user to add to the system", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/User" - }, - "examples": { - "user" : { - "summary": "User Example", - "externalValue": "http://foo.bar/examples/user-example.json" - } - } - }, - "application/xml": { - "schema": { - "$ref": "#/components/schemas/User" - }, - "examples": { - "user" : { - "summary": "User example in XML", - "externalValue": "http://foo.bar/examples/user-example.xml" - } - } - }, - "text/plain": { - "examples": { - "user" : { - "summary": "User example in Plain text", - "externalValue": "http://foo.bar/examples/user-example.txt" - } - } - }, - "*/*": { - "examples": { - "user" : { - "summary": "User example in other format", - "externalValue": "http://foo.bar/examples/user-example.whatever" - } - } - } - } -} -``` - -```yaml -description: user to add to the system -content: - 'application/json': - schema: - $ref: '#/components/schemas/User' - examples: - user: - summary: User Example - externalValue: 'http://foo.bar/examples/user-example.json' - 'application/xml': - schema: - $ref: '#/components/schemas/User' - examples: - user: - summary: User Example in XML - externalValue: 'http://foo.bar/examples/user-example.xml' - 'text/plain': - examples: - user: - summary: User example in text plain format - externalValue: 'http://foo.bar/examples/user-example.txt' - '*/*': - examples: - user: - summary: User example in other format - externalValue: 'http://foo.bar/examples/user-example.whatever' -``` - -A body parameter that is an array of string values: -```json -{ - "description": "user to add to the system", - "content": { - "text/plain": { - "schema": { - "type": "array", - "items": { - "type": "string" - } - } - } - } -} -``` - -```yaml -description: user to add to the system -required: true -content: - text/plain: - schema: - type: array - items: - type: string -``` - - -#### Media Type Object -Each Media Type Object provides schema and examples for the media type identified by its key. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -schema | [Schema Object](#schemaObject) \| [Reference Object](#referenceObject) | The schema defining the content of the request, response, or parameter. -example | Any | Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` which contains an example, the `example` value SHALL _override_ the example provided by the schema. -examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` which contains an example, the `examples` value SHALL _override_ the example provided by the schema. -encoding | Map[`string`, [Encoding Object](#encodingObject)] | A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to `requestBody` objects when the media type is `multipart` or `application/x-www-form-urlencoded`. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Media Type Examples - -```json -{ - "application/json": { - "schema": { - "$ref": "#/components/schemas/Pet" - }, - "examples": { - "cat" : { - "summary": "An example of a cat", - "value": - { - "name": "Fluffy", - "petType": "Cat", - "color": "White", - "gender": "male", - "breed": "Persian" - } - }, - "dog": { - "summary": "An example of a dog with a cat's name", - "value" : { - "name": "Puma", - "petType": "Dog", - "color": "Black", - "gender": "Female", - "breed": "Mixed" - }, - "frog": { - "$ref": "#/components/examples/frog-example" - } - } - } - } -} -``` - -```yaml -application/json: - schema: - $ref: "#/components/schemas/Pet" - examples: - cat: - summary: An example of a cat - value: - name: Fluffy - petType: Cat - color: White - gender: male - breed: Persian - dog: - summary: An example of a dog with a cat's name - value: - name: Puma - petType: Dog - color: Black - gender: Female - breed: Mixed - frog: - $ref: "#/components/examples/frog-example" -``` - -##### Considerations for File Uploads - -In contrast with the 2.0 specification, `file` input/output content in OpenAPI is described with the same semantics as any other schema type. Specifically: - -```yaml -# content transferred with base64 encoding -schema: - type: string - format: base64 -``` - -```yaml -# content transferred in binary (octet-stream): -schema: - type: string - format: binary -``` - -These examples apply to either input payloads of file uploads or response payloads. - -A `requestBody` for submitting a file in a `POST` operation may look like the following example: - -```yaml -requestBody: - content: - application/octet-stream: - schema: - # a binary file of any type - type: string - format: binary -``` - -In addition, specific media types MAY be specified: - -```yaml -# multiple, specific media types may be specified: -requestBody: - content: - # a binary file of type png or jpeg - 'image/jpeg': - schema: - type: string - format: binary - 'image/png': - schema: - type: string - format: binary -``` - -To upload multiple files, a `multipart` media type MUST be used: - -```yaml -requestBody: - content: - multipart/form-data: - schema: - properties: - # The property name 'file' will be used for all files. - file: - type: array - items: - type: string - format: binary - -``` - -##### Support for x-www-form-urlencoded Request Bodies - -To submit content using form url encoding via [RFC1866](https://tools.ietf.org/html/rfc1866), the following -definition may be used: - -```yaml -requestBody: - content: - application/x-www-form-urlencoded: - schema: - type: object - properties: - id: - type: string - format: uuid - address: - # complex types are stringified to support RFC 1866 - type: object - properties: {} -``` - -In this example, the contents in the `requestBody` MUST be stringified per [RFC1866](https://tools.ietf.org/html/rfc1866/) when passed to the server. In addition, the `address` field complex object will be stringified. - -When passing complex objects in the `application/x-www-form-urlencoded` content type, the default serialization strategy of such properties is described in the [`Encoding Object`](#encodingObject)'s [`style`](#encodingStyle) property as `form`. - -##### Special Considerations for `multipart` Content - -It is common to use `multipart/form-data` as a `Content-Type` when transferring request bodies to operations. In contrast to 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content. This supports complex structures as well as supporting mechanisms for multiple file uploads. - -When passing in `multipart` types, boundaries MAY be used to separate sections of the content being transferred — thus, the following default `Content-Type`s are defined for `multipart`: - -* If the property is a primitive, or an array of primitive values, the default Content-Type is `text/plain` -* If the property is complex, or an array of complex values, the default Content-Type is `application/json` -* If the property is a `type: string` with `format: binary` or `format: base64` (aka a file object), the default Content-Type is `application/octet-stream` - - -Examples: - -```yaml -requestBody: - content: - multipart/form-data: - schema: - type: object - properties: - id: - type: string - format: uuid - address: - # default Content-Type for objects is `application/json` - type: object - properties: {} - profileImage: - # default Content-Type for string/binary is `application/octet-stream` - type: string - format: binary - children: - # default Content-Type for arrays is based on the `inner` type (text/plain here) - type: array - items: - type: string - addresses: - # default Content-Type for arrays is based on the `inner` type (object shown, so `application/json` in this example) - type: array - items: - type: '#/components/schemas/Address' -``` - -An `encoding` attribute is introduced to give you control over the serialization of parts of `multipart` request bodies. This attribute is _only_ applicable to `multipart` and `application/x-www-form-urlencoded` request bodies. - -#### Encoding Object - -A single encoding definition applied to a single schema property. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -contentType | `string` | The Content-Type for encoding a specific property. Default value depends on the property type: for `string` with `format` being `binary` – `application/octet-stream`; for other primitive types – `text/plain`; for `object` - `application/json`; for `array` – the default is defined based on the inner type. The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or a comma-separated list of the two types. -headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | A map allowing additional information to be provided as headers, for example `Content-Disposition`. `Content-Type` is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a `multipart`. -style | `string` | Describes how a specific property value will be serialized depending on its type. See [Parameter Object](#parameterObject) for details on the [`style`](#parameterStyle) property. The behavior follows the same values as `query` parameters, including default values. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. -explode | `boolean` | When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When [`style`](#encodingStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. -allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Encoding Object Example - -```yaml -requestBody: - content: - multipart/mixed: - schema: - type: object - properties: - id: - # default is text/plain - type: string - format: uuid - address: - # default is application/json - type: object - properties: {} - historyMetadata: - # need to declare XML format! - description: metadata in XML format - type: object - properties: {} - profileImage: - # default is application/octet-stream, need to declare an image type only! - type: string - format: binary - encoding: - historyMetadata: - # require XML Content-Type in utf-8 encoding - contentType: application/xml; charset=utf-8 - profileImage: - # only accept png/jpeg - contentType: image/png, image/jpeg - headers: - X-Rate-Limit-Limit: - description: The number of allowed requests in the current period - schema: - type: integer -``` - -#### Responses Object - -A container for the expected responses of an operation. -The container maps a HTTP response code to the expected response. - -The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. -However, documentation is expected to cover a successful operation response and any known errors. - -The `default` MAY be used as a default response object for all HTTP codes -that are not covered individually by the specification. - -The `Responses Object` MUST contain at least one response code, and it -SHOULD be the response for a successful operation call. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -default | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. A [Reference Object](#referenceObject) can link to a response that the [OpenAPI Object's components/responses](#componentsResponses) section defines. - -##### Patterned Fields -Field Pattern | Type | Description ----|:---:|--- -[HTTP Status Code](#httpCodes) | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | Any [HTTP status code](#httpCodes) can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. A [Reference Object](#referenceObject) can link to a response that is defined in the [OpenAPI Object's components/responses](#componentsResponses) section. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `[200-299]`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. - - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Responses Object Example - -A 200 response for a successful operation and a default response for others (implying an error): - -```json -{ - "200": { - "description": "a pet to be returned", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Pet" - } - } - } - }, - "default": { - "description": "Unexpected error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorModel" - } - } - } - } -} -``` - -```yaml -'200': - description: a pet to be returned - content: - application/json: - schema: - $ref: '#/components/schemas/Pet' -default: - description: Unexpected error - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorModel' -``` - -#### Response Object -Describes a single response from an API Operation, including design-time, static -`links` to operations based on the response. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -description | `string` | **REQUIRED**. A short description of the response. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | Maps a header name to its definition. [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL be ignored. -content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing descriptions of potential response payloads. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* -links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for [Component Objects](#componentsObject). - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Response Object Examples - -Response of an array of a complex type: - -```json -{ - "description": "A complex object array response", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/VeryComplexType" - } - } - } - } -} -``` - -```yaml -description: A complex object array response -content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/VeryComplexType' -``` - -Response with a string type: - -```json -{ - "description": "A simple string response", - "content": { - "text/plain": { - "schema": { - "type": "string" - } - } - } - -} -``` - -```yaml -description: A simple string response -content: - text/plain: - schema: - type: string -``` - -Plain text response with headers: - -```json -{ - "description": "A simple string response", - "content": { - "text/plain": { - "schema": { - "type": "string", - "example": "whoa!" - } - } - }, - "headers": { - "X-Rate-Limit-Limit": { - "description": "The number of allowed requests in the current period", - "schema": { - "type": "integer" - } - }, - "X-Rate-Limit-Remaining": { - "description": "The number of remaining requests in the current period", - "schema": { - "type": "integer" - } - }, - "X-Rate-Limit-Reset": { - "description": "The number of seconds left in the current period", - "schema": { - "type": "integer" - } - } - } -} -``` - -```yaml -description: A simple string response -content: - text/plain: - schema: - type: string - example: 'whoa!' -headers: - X-Rate-Limit-Limit: - description: The number of allowed requests in the current period - schema: - type: integer - X-Rate-Limit-Remaining: - description: The number of remaining requests in the current period - schema: - type: integer - X-Rate-Limit-Reset: - description: The number of seconds left in the current period - schema: - type: integer -``` - -Response with no return value: - -```json -{ - "description": "object created" -} -``` - -```yaml -description: object created -``` - -#### Callback Object - -A map of possible out-of band callbacks related to the parent operation. -Each value in the map is a [Path Item Object](#pathItemObject) that describes a set of requests that may be initiated by the API provider and the expected responses. -The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. - -##### Patterned Fields -Field Pattern | Type | Description ----|:---:|--- -{expression} | [Path Item Object](#pathItemObject) | A Path Item Object used to define a callback request and expected responses. A [complete example](../examples/v3.0/callback-example.yaml) is available. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Key Expression - -The key that identifies the [Path Item Object](#pathItemObject) is a [runtime expression](#runtimeExpression) that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. -A simple example might be `$request.body#/url`. -However, using a [runtime expression](#runtimeExpression) the complete HTTP message can be accessed. -This includes accessing any part of a body that a JSON Pointer [RFC6901](https://tools.ietf.org/html/rfc6901) can reference. - -For example, given the following HTTP request: - -```http -POST /subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning HTTP/1.1 -Host: example.org -Content-Type: application/json -Content-Length: 187 - -{ - "failedUrl" : "http://clientdomain.com/failed", - "successUrls" : [ - "http://clientdomain.com/fast", - "http://clientdomain.com/medium", - "http://clientdomain.com/slow" - ] -} - -201 Created -Location: http://example.org/subscription/1 -``` - -The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named `eventType` and a query parameter named `queryUrl`. - -Expression | Value ----|:--- -$url | http://example.org/subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning -$method | POST -$request.path.eventType | myevent -$request.query.queryUrl | http://clientdomain.com/stillrunning -$request.header.content-Type | application/json -$request.body#/failedUrl | http://clientdomain.com/failed -$request.body#/successUrls/2 | http://clientdomain.com/medium -$response.header.Location | http://example.org/subscription/1 - - -##### Callback Object Examples - -The following example uses the user provided `queryUrl` query string parameter to define the callback URL. This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook. - -```yaml -myCallback: - '{$request.query.queryUrl}': - post: - requestBody: - description: Callback payload - content: - 'application/json': - schema: - $ref: '#/components/schemas/SomePayload' - responses: - '200': - description: callback successfully processed -``` - -The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the `id` and `email` property in the request body. - -```yaml -transactionCallback: - 'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}': - post: - requestBody: - description: Callback payload - content: - 'application/json': - schema: - $ref: '#/components/schemas/SomePayload' - responses: - '200': - description: callback successfully processed -``` - -#### Example Object - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -summary | `string` | Short description for the example. -description | `string` | Long description for the example. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -value | Any | Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary. -externalValue | `string` | A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -In all cases, the example value is expected to be compatible with the type schema -of its associated value. Tooling implementations MAY choose to -validate compatibility automatically, and reject the example value(s) if incompatible. - -##### Example Object Examples - -In a request body: - -```yaml -requestBody: - content: - 'application/json': - schema: - $ref: '#/components/schemas/Address' - examples: - foo: - summary: A foo example - value: {"foo": "bar"} - bar: - summary: A bar example - value: {"bar": "baz"} - 'application/xml': - examples: - xmlExample: - summary: This is an example in XML - externalValue: 'http://example.org/examples/address-example.xml' - 'text/plain': - examples: - textExample: - summary: This is a text example - externalValue: 'http://foo.bar/examples/address-example.txt' -``` - -In a parameter: - -```yaml -parameters: - - name: 'zipCode' - in: 'query' - schema: - type: 'string' - format: 'zip-code' - examples: - zip-example: - $ref: '#/components/examples/zip-example' -``` - -In a response: - -```yaml -responses: - '200': - description: your car appointment has been booked - content: - application/json: - schema: - $ref: '#/components/schemas/SuccessResponse' - examples: - confirmation-success: - $ref: '#/components/examples/confirmation-success' -``` - - -#### Link Object - -The `Link object` represents a possible design-time link for a response. -The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. - -Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. - -For computing links, and providing instructions to execute them, a [runtime expression](#runtimeExpression) is used for accessing values in an operation and using them as parameters while invoking the linked operation. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -operationRef | `string` | A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an [Operation Object](#operationObject). Relative `operationRef` values MAY be used to locate an existing [Operation Object](#operationObject) in the OpenAPI definition. -operationId | `string` | The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field. -parameters | Map[`string`, Any \| [{expression}](#runtimeExpression)] | A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the [parameter location](#parameterIn) `[{in}.]{name}` for operations that use the same parameter name in different locations (e.g. path.id). -requestBody | Any \| [{expression}](#runtimeExpression) | A literal value or [{expression}](#runtimeExpression) to use as a request body when calling the target operation. -description | `string` | A description of the link. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -server | [Server Object](#serverObject) | A server object to be used by the target operation. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -A linked operation MUST be identified using either an `operationRef` or `operationId`. -In the case of an `operationId`, it MUST be unique and resolved in the scope of the OAS document. -Because of the potential for name clashes, the `operationRef` syntax is preferred -for specifications with external references. - -##### Examples - -Computing a link from a request operation where the `$request.path.id` is used to pass a request parameter to the linked operation. - -```yaml -paths: - /users/{id}: - parameters: - - name: id - in: path - required: true - description: the user identifier, as userId - schema: - type: string - get: - responses: - '200': - description: the user being returned - content: - application/json: - schema: - type: object - properties: - uuid: # the unique user id - type: string - format: uuid - links: - address: - # the target link operationId - operationId: getUserAddress - parameters: - # get the `id` field from the request path parameter named `id` - userId: $request.path.id - # the path item of the linked operation - /users/{userid}/address: - parameters: - - name: userid - in: path - required: true - description: the user identifier, as userId - schema: - type: string - # linked operation - get: - operationId: getUserAddress - responses: - '200': - description: the user's address -``` - -When a runtime expression fails to evaluate, no parameter value is passed to the target operation. - -Values from the response body can be used to drive a linked operation. - -```yaml -links: - address: - operationId: getUserAddressByUUID - parameters: - # get the `uuid` field from the `uuid` field in the response body - userUuid: $response.body#/uuid -``` - -Clients follow all links at their discretion. -Neither permissions, nor the capability to make a successful call to that link, is guaranteed -solely by the existence of a relationship. - - -##### OperationRef Examples - -As references to `operationId` MAY NOT be possible (the `operationId` is an optional -field in an [Operation Object](#operationObject)), references MAY also be made through a relative `operationRef`: - -```yaml -links: - UserRepositories: - # returns array of '#/components/schemas/repository' - operationRef: '#/paths/~12.0~1repositories~1{username}/get' - parameters: - username: $response.body#/username -``` - -or an absolute `operationRef`: - -```yaml -links: - UserRepositories: - # returns array of '#/components/schemas/repository' - operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get' - parameters: - username: $response.body#/username -``` - -Note that in the use of `operationRef`, the _escaped forward-slash_ is necessary when -using JSON references. - - -##### Runtime Expressions - -Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. -This mechanism is used by [Link Objects](#linkObject) and [Callback Objects](#callbackObject). - -The runtime expression is defined by the following [ABNF](https://tools.ietf.org/html/rfc5234) syntax - -```abnf - expression = ( "$url" / "$method" / "$statusCode" / "$request." source / "$response." source ) - source = ( header-reference / query-reference / path-reference / body-reference ) - header-reference = "header." token - query-reference = "query." name - path-reference = "path." name - body-reference = "body" ["#" json-pointer ] - json-pointer = *( "/" reference-token ) - reference-token = *( unescaped / escaped ) - unescaped = %x00-2E / %x30-7D / %x7F-10FFFF - ; %x2F ('/') and %x7E ('~') are excluded from 'unescaped' - escaped = "~" ( "0" / "1" ) - ; representing '~' and '/', respectively - name = *( CHAR ) - token = 1*tchar - tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / - "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA -``` - -Here, `json-pointer` is taken from [RFC 6901](https://tools.ietf.org/html/rfc6901), `char` from [RFC 7159](https://tools.ietf.org/html/rfc7159#section-7) and `token` from [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2.6). - -The `name` identifier is case-sensitive, whereas `token` is not. - -The table below provides examples of runtime expressions and examples of their use in a value: - -##### Examples - -Source Location | example expression | notes ----|:---|:---| -HTTP Method | `$method` | The allowable values for the `$method` will be those for the HTTP operation. -Requested media type | `$request.header.accept` | -Request parameter | `$request.path.id` | Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated. This includes request headers. -Request body property | `$request.body#/user/uuid` | In operations which accept payloads, references may be made to portions of the `requestBody` or the entire body. -Request URL | `$url` | -Response value | `$response.body#/status` | In operations which return payloads, references may be made to portions of the response body or the entire body. -Response header | `$response.header.Server` | Single header values only are available - -Runtime expressions preserve the type of the referenced value. -Expressions can be embedded into string values by surrounding the expression with `{}` curly braces. - -#### Header Object - -The Header Object follows the structure of the [Parameter Object](#parameterObject) with the following changes: - -1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. -1. `in` MUST NOT be specified, it is implicitly in `header`. -1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, [`style`](#parameterStyle)). - -##### Header Object Example - -A simple header of type `integer`: - -```json -{ - "description": "The number of allowed requests in the current period", - "schema": { - "type": "integer" - } -} -``` - -```yaml -description: The number of allowed requests in the current period -schema: - type: integer -``` - -#### Tag Object - -Adds metadata to a single tag that is used by the [Operation Object](#operationObject). -It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -name | `string` | **REQUIRED**. The name of the tag. -description | `string` | A short description for the tag. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this tag. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Tag Object Example - -```json -{ - "name": "pet", - "description": "Pets operations" -} -``` - -```yaml -name: pet -description: Pets operations -``` - - -#### Reference Object - -A simple object to allow referencing other components in the specification, internally and externally. - -The Reference Object is defined by [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) and follows the same structure, behavior and rules. - -For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -$ref | `string` | **REQUIRED**. The reference string. - -This object cannot be extended with additional properties and any properties added SHALL be ignored. - -##### Reference Object Example - -```json -{ - "$ref": "#/components/schemas/Pet" -} -``` - -```yaml -$ref: '#/components/schemas/Pet' -``` - -##### Relative Schema Document Example -```json -{ - "$ref": "Pet.json" -} -``` - -```yaml -$ref: Pet.yaml -``` - -##### Relative Documents With Embedded Schema Example -```json -{ - "$ref": "definitions.json#/Pet" -} -``` - -```yaml -$ref: definitions.yaml#/Pet -``` - -#### Schema Object - -The Schema Object allows the definition of input and output data types. -These types can be objects, but also primitives and arrays. -This object is an extended subset of the [JSON Schema Specification Wright Draft 00](https://json-schema.org/). - -For more information about the properties, see [JSON Schema Core](https://tools.ietf.org/html/draft-wright-json-schema-00) and [JSON Schema Validation](https://tools.ietf.org/html/draft-wright-json-schema-validation-00). -Unless stated otherwise, the property definitions follow the JSON Schema. - -##### Properties - -The following properties are taken directly from the JSON Schema definition and follow the same specifications: - -- title -- multipleOf -- maximum -- exclusiveMaximum -- minimum -- exclusiveMinimum -- maxLength -- minLength -- pattern (This string SHOULD be a valid regular expression, according to the [Ecma-262 Edition 5.1 regular expression](https://www.ecma-international.org/ecma-262/5.1/#sec-15.10.1) dialect) -- maxItems -- minItems -- uniqueItems -- maxProperties -- minProperties -- required -- enum - -The following properties are taken from the JSON Schema definition but their definitions were adjusted to the OpenAPI Specification. -- type - Value MUST be a string. Multiple types via an array are not supported. -- allOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. -- oneOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. -- anyOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. -- not - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. -- items - Value MUST be an object and not an array. Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. `items` MUST be present if the `type` is `array`. -- properties - Property definitions MUST be a [Schema Object](#schemaObject) and not a standard JSON Schema (inline or referenced). -- additionalProperties - Value can be boolean or object. Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. Consistent with JSON Schema, `additionalProperties` defaults to `true`. -- description - [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -- format - See [Data Type Formats](#dataTypeFormat) for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats. -- default - The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level. For example, if `type` is `string`, then `default` can be `"foo"` but cannot be `1`. - -Alternatively, any time a Schema Object can be used, a [Reference Object](#referenceObject) can be used in its place. This allows referencing definitions instead of defining them inline. - -Additional properties defined by the JSON Schema specification that are not mentioned here are strictly unsupported. - -Other than the JSON Schema subset fields, the following fields MAY be used for further schema documentation: - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -nullable | `boolean` | A `true` value adds `"null"` to the allowed type specified by the `type` keyword, only if `type` is explicitly defined within the same Schema Object. Other Schema Object constraints retain their defined behavior, and therefore may disallow the use of `null` as a value. A `false` value leaves the specified or default `type` unmodified. The default value is `false`. -discriminator | [Discriminator Object](#discriminatorObject) | Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See [Composition and Inheritance](#schemaComposition) for more details. -readOnly | `boolean` | Relevant only for Schema `"properties"` definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as `readOnly` being `true` and is in the `required` list, the `required` will take effect on the response only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`. -writeOnly | `boolean` | Relevant only for Schema `"properties"` definitions. Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as `writeOnly` being `true` and is in the `required` list, the `required` will take effect on the request only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`. -xml | [XML Object](#xmlObject) | This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property. -externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this schema. -example | Any | A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. - deprecated | `boolean` | Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is `false`. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -###### Composition and Inheritance (Polymorphism) - -The OpenAPI Specification allows combining and extending model definitions using the `allOf` property of JSON Schema, in effect offering model composition. -`allOf` takes an array of object definitions that are validated *independently* but together compose a single object. - -While composition offers model extensibility, it does not imply a hierarchy between the models. -To support polymorphism, the OpenAPI Specification adds the `discriminator` field. -When used, the `discriminator` will be the name of the property that decides which schema definition validates the structure of the model. -As such, the `discriminator` field MUST be a required field. -There are two ways to define the value of a discriminator for an inheriting instance. -- Use the schema name. -- Override the schema name by overriding the property with a new value. If a new value exists, this takes precedence over the schema name. -As such, inline schema definitions, which do not have a given id, *cannot* be used in polymorphism. - -###### XML Modeling - -The [xml](#schemaXml) property allows extra definitions when translating the JSON definition to XML. -The [XML Object](#xmlObject) contains additional information about the available options. - -##### Schema Object Examples - -###### Primitive Sample - -```json -{ - "type": "string", - "format": "email" -} -``` - -```yaml -type: string -format: email -``` - -###### Simple Model - -```json -{ - "type": "object", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "address": { - "$ref": "#/components/schemas/Address" - }, - "age": { - "type": "integer", - "format": "int32", - "minimum": 0 - } - } -} -``` - -```yaml -type: object -required: -- name -properties: - name: - type: string - address: - $ref: '#/components/schemas/Address' - age: - type: integer - format: int32 - minimum: 0 -``` - -###### Model with Map/Dictionary Properties - -For a simple string to string mapping: - -```json -{ - "type": "object", - "additionalProperties": { - "type": "string" - } -} -``` - -```yaml -type: object -additionalProperties: - type: string -``` - -For a string to model mapping: - -```json -{ - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/ComplexModel" - } -} -``` - -```yaml -type: object -additionalProperties: - $ref: '#/components/schemas/ComplexModel' -``` - -###### Model with Example - -```json -{ - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "required": [ - "name" - ], - "example": { - "name": "Puma", - "id": 1 - } -} -``` - -```yaml -type: object -properties: - id: - type: integer - format: int64 - name: - type: string -required: -- name -example: - name: Puma - id: 1 -``` - -###### Models with Composition - -```json -{ - "components": { - "schemas": { - "ErrorModel": { - "type": "object", - "required": [ - "message", - "code" - ], - "properties": { - "message": { - "type": "string" - }, - "code": { - "type": "integer", - "minimum": 100, - "maximum": 600 - } - } - }, - "ExtendedErrorModel": { - "allOf": [ - { - "$ref": "#/components/schemas/ErrorModel" - }, - { - "type": "object", - "required": [ - "rootCause" - ], - "properties": { - "rootCause": { - "type": "string" - } - } - } - ] - } - } - } -} -``` - -```yaml -components: - schemas: - ErrorModel: - type: object - required: - - message - - code - properties: - message: - type: string - code: - type: integer - minimum: 100 - maximum: 600 - ExtendedErrorModel: - allOf: - - $ref: '#/components/schemas/ErrorModel' - - type: object - required: - - rootCause - properties: - rootCause: - type: string -``` - -###### Models with Polymorphism Support - -```json -{ - "components": { - "schemas": { - "Pet": { - "type": "object", - "discriminator": { - "propertyName": "petType" - }, - "properties": { - "name": { - "type": "string" - }, - "petType": { - "type": "string" - } - }, - "required": [ - "name", - "petType" - ] - }, - "Cat": { - "description": "A representation of a cat. Note that `Cat` will be used as the discriminator value.", - "allOf": [ - { - "$ref": "#/components/schemas/Pet" - }, - { - "type": "object", - "properties": { - "huntingSkill": { - "type": "string", - "description": "The measured skill for hunting", - "default": "lazy", - "enum": [ - "clueless", - "lazy", - "adventurous", - "aggressive" - ] - } - }, - "required": [ - "huntingSkill" - ] - } - ] - }, - "Dog": { - "description": "A representation of a dog. Note that `Dog` will be used as the discriminator value.", - "allOf": [ - { - "$ref": "#/components/schemas/Pet" - }, - { - "type": "object", - "properties": { - "packSize": { - "type": "integer", - "format": "int32", - "description": "the size of the pack the dog is from", - "default": 0, - "minimum": 0 - } - }, - "required": [ - "packSize" - ] - } - ] - } - } - } -} -``` - -```yaml -components: - schemas: - Pet: - type: object - discriminator: - propertyName: petType - properties: - name: - type: string - petType: - type: string - required: - - name - - petType - Cat: ## "Cat" will be used as the discriminator value - description: A representation of a cat - allOf: - - $ref: '#/components/schemas/Pet' - - type: object - properties: - huntingSkill: - type: string - description: The measured skill for hunting - enum: - - clueless - - lazy - - adventurous - - aggressive - required: - - huntingSkill - Dog: ## "Dog" will be used as the discriminator value - description: A representation of a dog - allOf: - - $ref: '#/components/schemas/Pet' - - type: object - properties: - packSize: - type: integer - format: int32 - description: the size of the pack the dog is from - default: 0 - minimum: 0 - required: - - packSize -``` - -#### Discriminator Object - -When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it. - -When using the discriminator, _inline_ schemas will not be considered. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -propertyName | `string` | **REQUIRED**. The name of the property in the payload that will hold the discriminator value. - mapping | Map[`string`, `string`] | An object to hold mappings between payload values and schema names or references. - -The discriminator object is legal only when using one of the composite keywords `oneOf`, `anyOf`, `allOf`. - -In OAS 3.0, a response payload MAY be described to be exactly one of any number of types: - -```yaml -MyResponseType: - oneOf: - - $ref: '#/components/schemas/Cat' - - $ref: '#/components/schemas/Dog' - - $ref: '#/components/schemas/Lizard' -``` - -which means the payload _MUST_, by validation, match exactly one of the schemas described by `Cat`, `Dog`, or `Lizard`. In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use: - - -```yaml -MyResponseType: - oneOf: - - $ref: '#/components/schemas/Cat' - - $ref: '#/components/schemas/Dog' - - $ref: '#/components/schemas/Lizard' - discriminator: - propertyName: petType -``` - -The expectation now is that a property with name `petType` _MUST_ be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload: - -```json -{ - "id": 12345, - "petType": "Cat" -} -``` - -Will indicate that the `Cat` schema be used in conjunction with this payload. - -In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used: - -```yaml -MyResponseType: - oneOf: - - $ref: '#/components/schemas/Cat' - - $ref: '#/components/schemas/Dog' - - $ref: '#/components/schemas/Lizard' - - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json' - discriminator: - propertyName: petType - mapping: - dog: '#/components/schemas/Dog' - monster: 'https://gigantic-server.com/schemas/Monster/schema.json' -``` - -Here the discriminator _value_ of `dog` will map to the schema `#/components/schemas/Dog`, rather than the default (implicit) value of `Dog`. If the discriminator _value_ does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison. - -When used in conjunction with the `anyOf` construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload. - -In both the `oneOf` and `anyOf` use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an `allOf` construct may be used as an alternate schema. - -For example: - -```yaml -components: - schemas: - Pet: - type: object - required: - - petType - properties: - petType: - type: string - discriminator: - propertyName: petType - mapping: - dog: Dog - Cat: - allOf: - - $ref: '#/components/schemas/Pet' - - type: object - # all other properties specific to a `Cat` - properties: - name: - type: string - Dog: - allOf: - - $ref: '#/components/schemas/Pet' - - type: object - # all other properties specific to a `Dog` - properties: - bark: - type: string - Lizard: - allOf: - - $ref: '#/components/schemas/Pet' - - type: object - # all other properties specific to a `Lizard` - properties: - lovesRocks: - type: boolean -``` - -a payload like this: - -```json -{ - "petType": "Cat", - "name": "misty" -} -``` - -will indicate that the `Cat` schema be used. Likewise this schema: - -```json -{ - "petType": "dog", - "bark": "soft" -} -``` - -will map to `Dog` because of the definition in the `mappings` element. - - -#### XML Object - -A metadata object that allows for more fine-tuned XML model definitions. - -When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. -See examples for expected behavior. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -name | `string` | Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. -namespace | `string` | The URI of the namespace definition. Value MUST be in the form of an absolute URI. -prefix | `string` | The prefix to be used for the [name](#xmlName). -attribute | `boolean` | Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. -wrapped | `boolean` | MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### XML Object Examples - -The examples of the XML object definitions are included inside a property definition of a [Schema Object](#schemaObject) with a sample of the XML representation of it. - -###### No XML Element - -Basic string property: - -```json -{ - "animals": { - "type": "string" - } -} -``` - -```yaml -animals: - type: string -``` - -```xml -... -``` - -Basic string array property ([`wrapped`](#xmlWrapped) is `false` by default): - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string" - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string -``` - -```xml -... -... -... -``` - -###### XML Name Replacement - -```json -{ - "animals": { - "type": "string", - "xml": { - "name": "animal" - } - } -} -``` - -```yaml -animals: - type: string - xml: - name: animal -``` - -```xml -... -``` - - -###### XML Attribute, Prefix and Namespace - -In this example, a full model definition is shown. - -```json -{ - "Person": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int32", - "xml": { - "attribute": true - } - }, - "name": { - "type": "string", - "xml": { - "namespace": "http://example.com/schema/sample", - "prefix": "sample" - } - } - } - } -} -``` - -```yaml -Person: - type: object - properties: - id: - type: integer - format: int32 - xml: - attribute: true - name: - type: string - xml: - namespace: http://example.com/schema/sample - prefix: sample -``` - -```xml - - example - -``` - -###### XML Arrays - -Changing the element names: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string", - "xml": { - "name": "animal" - } - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - name: animal -``` - -```xml -value -value -``` - -The external `name` property has no effect on the XML: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string", - "xml": { - "name": "animal" - } - }, - "xml": { - "name": "aliens" - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - name: animal - xml: - name: aliens -``` - -```xml -value -value -``` - -Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string" - }, - "xml": { - "wrapped": true - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - wrapped: true -``` - -```xml - - value - value - -``` - -To overcome the naming problem in the example above, the following definition can be used: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string", - "xml": { - "name": "animal" - } - }, - "xml": { - "wrapped": true - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - name: animal - xml: - wrapped: true -``` - -```xml - - value - value - -``` - -Affecting both internal and external names: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string", - "xml": { - "name": "animal" - } - }, - "xml": { - "name": "aliens", - "wrapped": true - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - name: animal - xml: - name: aliens - wrapped: true -``` - -```xml - - value - value - -``` - -If we change the external element but not the internal ones: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string" - }, - "xml": { - "name": "aliens", - "wrapped": true - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - name: aliens - wrapped: true -``` - -```xml - - value - value - -``` - -#### Security Scheme Object - -Defines a security scheme that can be used by the operations. -Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749](https://tools.ietf.org/html/rfc6749), and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06). - -##### Fixed Fields -Field Name | Type | Applies To | Description ----|:---:|---|--- -type | `string` | Any | **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"oauth2"`, `"openIdConnect"`. -description | `string` | Any | A short description for security scheme. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -name | `string` | `apiKey` | **REQUIRED**. The name of the header, query or cookie parameter to be used. -in | `string` | `apiKey` | **REQUIRED**. The location of the API key. Valid values are `"query"`, `"header"` or `"cookie"`. -scheme | `string` | `http` | **REQUIRED**. The name of the HTTP Authorization scheme to be used in the [Authorization header as defined in RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1). The values used SHOULD be registered in the [IANA Authentication Scheme registry](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml). -bearerFormat | `string` | `http` (`"bearer"`) | A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. -flows | [OAuth Flows Object](#oauthFlowsObject) | `oauth2` | **REQUIRED**. An object containing configuration information for the flow types supported. -openIdConnectUrl | `string` | `openIdConnect` | **REQUIRED**. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Security Scheme Object Example - -###### Basic Authentication Sample - -```json -{ - "type": "http", - "scheme": "basic" -} -``` - -```yaml -type: http -scheme: basic -``` - -###### API Key Sample - -```json -{ - "type": "apiKey", - "name": "api_key", - "in": "header" -} -``` - -```yaml -type: apiKey -name: api_key -in: header -``` - -###### JWT Bearer Sample - -```json -{ - "type": "http", - "scheme": "bearer", - "bearerFormat": "JWT", -} -``` - -```yaml -type: http -scheme: bearer -bearerFormat: JWT -``` - -###### Implicit OAuth2 Sample - -```json -{ - "type": "oauth2", - "flows": { - "implicit": { - "authorizationUrl": "https://example.com/api/oauth/dialog", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - } - } -} -``` - -```yaml -type: oauth2 -flows: - implicit: - authorizationUrl: https://example.com/api/oauth/dialog - scopes: - write:pets: modify pets in your account - read:pets: read your pets -``` - -#### OAuth Flows Object - -Allows configuration of the supported OAuth Flows. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -implicit| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Implicit flow -password| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Resource Owner Password flow -clientCredentials| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0. -authorizationCode| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -#### OAuth Flow Object - -Configuration details for a supported OAuth Flow - -##### Fixed Fields -Field Name | Type | Applies To | Description ----|:---:|---|--- -authorizationUrl | `string` | `oauth2` (`"implicit"`, `"authorizationCode"`) | **REQUIRED**. The authorization URL to be used for this flow. This MUST be in the form of a URL. -tokenUrl | `string` | `oauth2` (`"password"`, `"clientCredentials"`, `"authorizationCode"`) | **REQUIRED**. The token URL to be used for this flow. This MUST be in the form of a URL. -refreshUrl | `string` | `oauth2` | The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. -scopes | Map[`string`, `string`] | `oauth2` | **REQUIRED**. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### OAuth Flow Object Examples - -```JSON -{ - "type": "oauth2", - "flows": { - "implicit": { - "authorizationUrl": "https://example.com/api/oauth/dialog", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - }, - "authorizationCode": { - "authorizationUrl": "https://example.com/api/oauth/dialog", - "tokenUrl": "https://example.com/api/oauth/token", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - } - } -} -``` - -```yaml -type: oauth2 -flows: - implicit: - authorizationUrl: https://example.com/api/oauth/dialog - scopes: - write:pets: modify pets in your account - read:pets: read your pets - authorizationCode: - authorizationUrl: https://example.com/api/oauth/dialog - tokenUrl: https://example.com/api/oauth/token - scopes: - write:pets: modify pets in your account - read:pets: read your pets -``` - -#### Security Requirement Object - -Lists the required security schemes to execute this operation. -The name used for each property MUST correspond to a security scheme declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). - -Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. -This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. - -When a list of Security Requirement Objects is defined on the [OpenAPI Object](#oasObject) or [Operation Object](#operationObject), only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. - -##### Patterned Fields - -Field Pattern | Type | Description ----|:---:|--- -{name} | [`string`] | Each name MUST correspond to a security scheme which is declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). If the security scheme is of type `"oauth2"` or `"openIdConnect"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MUST be empty. - -##### Security Requirement Object Examples - -###### Non-OAuth2 Security Requirement - -```json -{ - "api_key": [] -} -``` - -```yaml -api_key: [] -``` - -###### OAuth2 Security Requirement - -```json -{ - "petstore_auth": [ - "write:pets", - "read:pets" - ] -} -``` - -```yaml -petstore_auth: -- write:pets -- read:pets -``` - -###### Optional OAuth2 Security - -Optional OAuth2 security as would be defined in an OpenAPI Object or an Operation Object: - -```json -{ - "security": [ - {}, - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] -} -``` - -```yaml -security: - - {} - - petstore_auth: - - write:pets - - read:pets -``` - -### Specification Extensions - -While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points. - -The extensions properties are implemented as patterned fields that are always prefixed by `"x-"`. - -Field Pattern | Type | Description ----|:---:|--- -^x- | Any | Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. Can have any valid JSON format value. - -The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced). - -### Security Filtering - -Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation. - -The reasoning is to allow an additional layer of access control over the documentation. -While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization. - -Two examples of this: - -1. The [Paths Object](#pathsObject) MAY be empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They'd still have access to the [Info Object](#infoObject) which may contain additional information regarding authentication. -2. The [Path Item Object](#pathItemObject) MAY be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different from hiding the path itself from the [Paths Object](#pathsObject), because the user will be aware of its existence. This allows the documentation provider to finely control what the viewer can see. - -## Appendix A: Revision History - -Version | Date | Notes ---- | --- | --- -3.0.3 | 2020-02-20 | Patch release of the OpenAPI Specification 3.0.3 -3.0.2 | 2018-10-08 | Patch release of the OpenAPI Specification 3.0.2 -3.0.1 | 2017-12-06 | Patch release of the OpenAPI Specification 3.0.1 -3.0.0 | 2017-07-26 | Release of the OpenAPI Specification 3.0.0 -3.0.0-rc2 | 2017-06-16 | rc2 of the 3.0 specification -3.0.0-rc1 | 2017-04-27 | rc1 of the 3.0 specification -3.0.0-rc0 | 2017-02-28 | Implementer's Draft of the 3.0 specification -2.0 | 2015-12-31 | Donation of Swagger 2.0 to the OpenAPI Initiative -2.0 | 2014-09-08 | Release of Swagger 2.0 -1.2 | 2014-03-14 | Initial release of the formal document. -1.1 | 2012-08-22 | Release of Swagger 1.1 -1.0 | 2011-08-10 | First release of the Swagger Specification diff --git a/chaotic-openapi/chaotic_openapi/front/schema/3.1.0.md b/chaotic-openapi/chaotic_openapi/front/schema/3.1.0.md deleted file mode 100644 index 39425bd6b95f..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/3.1.0.md +++ /dev/null @@ -1,3468 +0,0 @@ -# OpenAPI Specification - -#### Version 3.1.0 - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://tools.ietf.org/html/bcp14) [RFC2119](https://tools.ietf.org/html/rfc2119) [RFC8174](https://tools.ietf.org/html/rfc8174) when, and only when, they appear in all capitals, as shown here. - -This document is licensed under [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). - -## Introduction - -The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to HTTP APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. - -An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases. - -## Table of Contents - - -- [Definitions](#definitions) - - [OpenAPI Document](#oasDocument) - - [Path Templating](#pathTemplating) - - [Media Types](#mediaTypes) - - [HTTP Status Codes](#httpCodes) -- [Specification](#specification) - - [Versions](#versions) - - [Format](#format) - - [Document Structure](#documentStructure) - - [Data Types](#dataTypes) - - [Rich Text Formatting](#richText) - - [Relative References In URIs](#relativeReferencesURI) - - [Relative References In URLs](#relativeReferencesURL) - - [Schema](#schema) - - [OpenAPI Object](#oasObject) - - [Info Object](#infoObject) - - [Contact Object](#contactObject) - - [License Object](#licenseObject) - - [Server Object](#serverObject) - - [Server Variable Object](#serverVariableObject) - - [Components Object](#componentsObject) - - [Paths Object](#pathsObject) - - [Path Item Object](#pathItemObject) - - [Operation Object](#operationObject) - - [External Documentation Object](#externalDocumentationObject) - - [Parameter Object](#parameterObject) - - [Request Body Object](#requestBodyObject) - - [Media Type Object](#mediaTypeObject) - - [Encoding Object](#encodingObject) - - [Responses Object](#responsesObject) - - [Response Object](#responseObject) - - [Callback Object](#callbackObject) - - [Example Object](#exampleObject) - - [Link Object](#linkObject) - - [Header Object](#headerObject) - - [Tag Object](#tagObject) - - [Reference Object](#referenceObject) - - [Schema Object](#schemaObject) - - [Discriminator Object](#discriminatorObject) - - [XML Object](#xmlObject) - - [Security Scheme Object](#securitySchemeObject) - - [OAuth Flows Object](#oauthFlowsObject) - - [OAuth Flow Object](#oauthFlowObject) - - [Security Requirement Object](#securityRequirementObject) - - [Specification Extensions](#specificationExtensions) - - [Security Filtering](#securityFiltering) -- [Appendix A: Revision History](#revisionHistory) - - - - -## Definitions - -##### OpenAPI Document -A self-contained or composite resource which defines or describes an API or elements of an API. The OpenAPI document MUST contain at least one [paths](#pathsObject) field, a [components](#oasComponents) field or a [webhooks](#oasWebhooks) field. An OpenAPI document uses and conforms to the OpenAPI Specification. - -##### Path Templating -Path templating refers to the usage of template expressions, delimited by curly braces ({}), to mark a section of a URL path as replaceable using path parameters. - -Each template expression in the path MUST correspond to a path parameter that is included in the [Path Item](#path-item-object) itself and/or in each of the Path Item's [Operations](#operation-object). An exception is if the path item is empty, for example due to ACL constraints, matching path parameters are not required. - -The value for these path parameters MUST NOT contain any unescaped "generic syntax" characters described by [RFC3986](https://tools.ietf.org/html/rfc3986#section-3): forward slashes (`/`), question marks (`?`), or hashes (`#`). - -##### Media Types -Media type definitions are spread across several resources. -The media type definitions SHOULD be in compliance with [RFC6838](https://tools.ietf.org/html/rfc6838). - -Some examples of possible media type definitions: -``` - text/plain; charset=utf-8 - application/json - application/vnd.github+json - application/vnd.github.v3+json - application/vnd.github.v3.raw+json - application/vnd.github.v3.text+json - application/vnd.github.v3.html+json - application/vnd.github.v3.full+json - application/vnd.github.v3.diff - application/vnd.github.v3.patch -``` -##### HTTP Status Codes -The HTTP Status Codes are used to indicate the status of the executed operation. -The available status codes are defined by [RFC7231](https://tools.ietf.org/html/rfc7231#section-6) and registered status codes are listed in the [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml). - -## Specification - -### Versions - -The OpenAPI Specification is versioned using a `major`.`minor`.`patch` versioning scheme. The `major`.`minor` portion of the version string (for example `3.1`) SHALL designate the OAS feature set. *`.patch`* versions address errors in, or provide clarifications to, this document, not the feature set. Tooling which supports OAS 3.1 SHOULD be compatible with all OAS 3.1.\* versions. The patch version SHOULD NOT be considered by tooling, making no distinction between `3.1.0` and `3.1.1` for example. - -Occasionally, non-backwards compatible changes may be made in `minor` versions of the OAS where impact is believed to be low relative to the benefit provided. - -An OpenAPI document compatible with OAS 3.\*.\* contains a required [`openapi`](#oasVersion) field which designates the version of the OAS that it uses. - -### Format - -An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either in JSON or YAML format. - -For example, if a field has an array value, the JSON array representation will be used: - -```json -{ - "field": [ 1, 2, 3 ] -} -``` -All field names in the specification are **case sensitive**. -This includes all fields that are used as keys in a map, except where explicitly noted that keys are **case insensitive**. - -The schema exposes two types of fields: Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name. - -Patterned fields MUST have unique names within the containing object. - -In order to preserve the ability to round-trip between YAML and JSON formats, YAML version [1.2](https://yaml.org/spec/1.2/spec.html) is RECOMMENDED along with some additional constraints: - -- Tags MUST be limited to those allowed by the [JSON Schema ruleset](https://yaml.org/spec/1.2/spec.html#id2803231). -- Keys used in YAML maps MUST be limited to a scalar string, as defined by the [YAML Failsafe schema ruleset](https://yaml.org/spec/1.2/spec.html#id2802346). - -**Note:** While APIs may be defined by OpenAPI documents in either YAML or JSON format, the API request and response bodies and other content are not required to be JSON or YAML. - -### Document Structure - -An OpenAPI document MAY be made up of a single document or be divided into multiple, connected parts at the discretion of the author. In the latter case, [`Reference Objects`](#referenceObject) and [`Schema Object`](#schemaObject) `$ref` keywords are used. - -It is RECOMMENDED that the root OpenAPI document be named: `openapi.json` or `openapi.yaml`. - -### Data Types - -Data types in the OAS are based on the types supported by the [JSON Schema Specification Draft 2020-12](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-4.2.1). -Note that `integer` as a type is also supported and is defined as a JSON number without a fraction or exponent part. -Models are defined using the [Schema Object](#schemaObject), which is a superset of JSON Schema Specification Draft 2020-12. - -As defined by the [JSON Schema Validation vocabulary](https://tools.ietf.org/html/draft-bhutton-json-schema-validation-00#section-7.3), data types can have an optional modifier property: `format`. -OAS defines additional formats to provide fine detail for primitive data types. - -The formats defined by the OAS are: - -[`type`](#dataTypes) | [`format`](#dataTypeFormat) | Comments ------- | -------- | -------- -`integer` | `int32` | signed 32 bits -`integer` | `int64` | signed 64 bits (a.k.a long) -`number` | `float` | | -`number` | `double` | | -`string` | `password` | A hint to UIs to obscure input. - -### Rich Text Formatting -Throughout the specification `description` fields are noted as supporting CommonMark markdown formatting. -Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by [CommonMark 0.27](https://spec.commonmark.org/0.27/). Tooling MAY choose to ignore some CommonMark features to address security concerns. - -### Relative References in URIs - -Unless specified otherwise, all properties that are URIs MAY be relative references as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-4.2). - -Relative references, including those in [`Reference Objects`](#referenceObject), [`PathItem Object`](#pathItemObject) `$ref` fields, [`Link Object`](#linkObject) `operationRef` fields and [`Example Object`](#exampleObject) `externalValue` fields, are resolved using the referring document as the Base URI according to [RFC3986](https://tools.ietf.org/html/rfc3986#section-5.2). - -If a URI contains a fragment identifier, then the fragment should be resolved per the fragment resolution mechanism of the referenced document. If the representation of the referenced document is JSON or YAML, then the fragment identifier SHOULD be interpreted as a JSON-Pointer as per [RFC6901](https://tools.ietf.org/html/rfc6901). - -Relative references in [`Schema Objects`](#schemaObject), including any that appear as `$id` values, use the nearest parent `$id` as a Base URI, as described by [JSON Schema Specification Draft 2020-12](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-8.2). If no parent schema contains an `$id`, then the Base URI MUST be determined according to [RFC3986](https://tools.ietf.org/html/rfc3986#section-5.1). - -### Relative References in URLs - -Unless specified otherwise, all properties that are URLs MAY be relative references as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-4.2). -Unless specified otherwise, relative references are resolved using the URLs defined in the [`Server Object`](#serverObject) as a Base URL. Note that these themselves MAY be relative to the referring document. - -### Schema - -In the following description, if a field is not explicitly **REQUIRED** or described with a MUST or SHALL, it can be considered OPTIONAL. - -#### OpenAPI Object - -This is the root object of the [OpenAPI document](#oasDocument). - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -openapi | `string` | **REQUIRED**. This string MUST be the [version number](#versions) of the OpenAPI Specification that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI document. This is *not* related to the API [`info.version`](#infoVersion) string. -info | [Info Object](#infoObject) | **REQUIRED**. Provides metadata about the API. The metadata MAY be used by tooling as required. - jsonSchemaDialect | `string` | The default value for the `$schema` keyword within [Schema Objects](#schemaObject) contained within this OAS document. This MUST be in the form of a URI. -servers | [[Server Object](#serverObject)] | An array of Server Objects, which provide connectivity information to a target server. If the `servers` property is not provided, or is an empty array, the default value would be a [Server Object](#serverObject) with a [url](#serverUrl) value of `/`. -paths | [Paths Object](#pathsObject) | The available paths and operations for the API. -webhooks | Map[`string`, [Path Item Object](#pathItemObject) \| [Reference Object](#referenceObject)] ] | The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement. Closely related to the `callbacks` feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. An [example](../examples/v3.1/webhook-example.yaml) is available. -components | [Components Object](#componentsObject) | An element to hold various schemas for the document. -security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement (`{}`) can be included in the array. -tags | [[Tag Object](#tagObject)] | A list of tags used by the document with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](#operationObject) must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. -externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation. - - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -#### Info Object - -The object provides metadata about the API. -The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -title | `string` | **REQUIRED**. The title of the API. -summary | `string` | A short summary of the API. -description | `string` | A description of the API. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -termsOfService | `string` | A URL to the Terms of Service for the API. This MUST be in the form of a URL. -contact | [Contact Object](#contactObject) | The contact information for the exposed API. -license | [License Object](#licenseObject) | The license information for the exposed API. -version | `string` | **REQUIRED**. The version of the OpenAPI document (which is distinct from the [OpenAPI Specification version](#oasVersion) or the API implementation version). - - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Info Object Example - -```json -{ - "title": "Sample Pet Store App", - "summary": "A pet store manager.", - "description": "This is a sample server for a pet store.", - "termsOfService": "https://example.com/terms/", - "contact": { - "name": "API Support", - "url": "https://www.example.com/support", - "email": "support@example.com" - }, - "license": { - "name": "Apache 2.0", - "url": "https://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "1.0.1" -} -``` - -```yaml -title: Sample Pet Store App -summary: A pet store manager. -description: This is a sample server for a pet store. -termsOfService: https://example.com/terms/ -contact: - name: API Support - url: https://www.example.com/support - email: support@example.com -license: - name: Apache 2.0 - url: https://www.apache.org/licenses/LICENSE-2.0.html -version: 1.0.1 -``` - -#### Contact Object - -Contact information for the exposed API. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -name | `string` | The identifying name of the contact person/organization. -url | `string` | The URL pointing to the contact information. This MUST be in the form of a URL. -email | `string` | The email address of the contact person/organization. This MUST be in the form of an email address. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Contact Object Example - -```json -{ - "name": "API Support", - "url": "https://www.example.com/support", - "email": "support@example.com" -} -``` - -```yaml -name: API Support -url: https://www.example.com/support -email: support@example.com -``` - -#### License Object - -License information for the exposed API. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -name | `string` | **REQUIRED**. The license name used for the API. -identifier | `string` | An [SPDX](https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60) license expression for the API. The `identifier` field is mutually exclusive of the `url` field. -url | `string` | A URL to the license used for the API. This MUST be in the form of a URL. The `url` field is mutually exclusive of the `identifier` field. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### License Object Example - -```json -{ - "name": "Apache 2.0", - "identifier": "Apache-2.0" -} -``` - -```yaml -name: Apache 2.0 -identifier: Apache-2.0 -``` - -#### Server Object - -An object representing a Server. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -url | `string` | **REQUIRED**. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{`brackets`}`. -description | `string` | An optional string describing the host designated by the URL. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -variables | Map[`string`, [Server Variable Object](#serverVariableObject)] | A map between a variable name and its value. The value is used for substitution in the server's URL template. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Server Object Example - -A single server would be described as: - -```json -{ - "url": "https://development.gigantic-server.com/v1", - "description": "Development server" -} -``` - -```yaml -url: https://development.gigantic-server.com/v1 -description: Development server -``` - -The following shows how multiple servers can be described, for example, at the OpenAPI Object's [`servers`](#oasServers): - -```json -{ - "servers": [ - { - "url": "https://development.gigantic-server.com/v1", - "description": "Development server" - }, - { - "url": "https://staging.gigantic-server.com/v1", - "description": "Staging server" - }, - { - "url": "https://api.gigantic-server.com/v1", - "description": "Production server" - } - ] -} -``` - -```yaml -servers: -- url: https://development.gigantic-server.com/v1 - description: Development server -- url: https://staging.gigantic-server.com/v1 - description: Staging server -- url: https://api.gigantic-server.com/v1 - description: Production server -``` - -The following shows how variables can be used for a server configuration: - -```json -{ - "servers": [ - { - "url": "https://{username}.gigantic-server.com:{port}/{basePath}", - "description": "The production API server", - "variables": { - "username": { - "default": "demo", - "description": "this value is assigned by the service provider, in this example `gigantic-server.com`" - }, - "port": { - "enum": [ - "8443", - "443" - ], - "default": "8443" - }, - "basePath": { - "default": "v2" - } - } - } - ] -} -``` - -```yaml -servers: -- url: https://{username}.gigantic-server.com:{port}/{basePath} - description: The production API server - variables: - username: - # note! no enum here means it is an open value - default: demo - description: this value is assigned by the service provider, in this example `gigantic-server.com` - port: - enum: - - '8443' - - '443' - default: '8443' - basePath: - # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2` - default: v2 -``` - - -#### Server Variable Object - -An object representing a Server Variable for server URL template substitution. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -enum | [`string`] | An enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty. -default | `string` | **REQUIRED**. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. Note this behavior is different than the [Schema Object's](#schemaObject) treatment of default values, because in those cases parameter values are optional. If the [`enum`](#serverVariableEnum) is defined, the value MUST exist in the enum's values. -description | `string` | An optional description for the server variable. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -#### Components Object - -Holds a set of reusable objects for different aspects of the OAS. -All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. - - -##### Fixed Fields - -Field Name | Type | Description ----|:---|--- - schemas | Map[`string`, [Schema Object](#schemaObject)] | An object to hold reusable [Schema Objects](#schemaObject). - responses | Map[`string`, [Response Object](#responseObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Response Objects](#responseObject). - parameters | Map[`string`, [Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Parameter Objects](#parameterObject). - examples | Map[`string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Example Objects](#exampleObject). - requestBodies | Map[`string`, [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Request Body Objects](#requestBodyObject). - headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Header Objects](#headerObject). - securitySchemes| Map[`string`, [Security Scheme Object](#securitySchemeObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Security Scheme Objects](#securitySchemeObject). - links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Link Objects](#linkObject). - callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Callback Objects](#callbackObject). - pathItems | Map[`string`, [Path Item Object](#pathItemObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Path Item Object](#pathItemObject). - - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`. - -Field Name Examples: - -``` -User -User_1 -User_Name -user-name -my.org.User -``` - -##### Components Object Example - -```json -"components": { - "schemas": { - "GeneralError": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - }, - "Category": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - } - }, - "Tag": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - } - } - }, - "parameters": { - "skipParam": { - "name": "skip", - "in": "query", - "description": "number of items to skip", - "required": true, - "schema": { - "type": "integer", - "format": "int32" - } - }, - "limitParam": { - "name": "limit", - "in": "query", - "description": "max records to return", - "required": true, - "schema" : { - "type": "integer", - "format": "int32" - } - } - }, - "responses": { - "NotFound": { - "description": "Entity not found." - }, - "IllegalInput": { - "description": "Illegal input for operation." - }, - "GeneralError": { - "description": "General Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GeneralError" - } - } - } - } - }, - "securitySchemes": { - "api_key": { - "type": "apiKey", - "name": "api_key", - "in": "header" - }, - "petstore_auth": { - "type": "oauth2", - "flows": { - "implicit": { - "authorizationUrl": "https://example.org/api/oauth/dialog", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - } - } - } - } -} -``` - -```yaml -components: - schemas: - GeneralError: - type: object - properties: - code: - type: integer - format: int32 - message: - type: string - Category: - type: object - properties: - id: - type: integer - format: int64 - name: - type: string - Tag: - type: object - properties: - id: - type: integer - format: int64 - name: - type: string - parameters: - skipParam: - name: skip - in: query - description: number of items to skip - required: true - schema: - type: integer - format: int32 - limitParam: - name: limit - in: query - description: max records to return - required: true - schema: - type: integer - format: int32 - responses: - NotFound: - description: Entity not found. - IllegalInput: - description: Illegal input for operation. - GeneralError: - description: General Error - content: - application/json: - schema: - $ref: '#/components/schemas/GeneralError' - securitySchemes: - api_key: - type: apiKey - name: api_key - in: header - petstore_auth: - type: oauth2 - flows: - implicit: - authorizationUrl: https://example.org/api/oauth/dialog - scopes: - write:pets: modify pets in your account - read:pets: read your pets -``` - -#### Paths Object - -Holds the relative paths to the individual endpoints and their operations. -The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. The Paths MAY be empty, due to [Access Control List (ACL) constraints](#securityFiltering). - -##### Patterned Fields - -Field Pattern | Type | Description ----|:---:|--- -/{path} | [Path Item Object](#pathItemObject) | A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is **appended** (no relative URL resolution) to the expanded URL from the [`Server Object`](#serverObject)'s `url` field in order to construct the full URL. [Path templating](#pathTemplating) is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Path Templating Matching - -Assuming the following paths, the concrete definition, `/pets/mine`, will be matched first if used: - -``` - /pets/{petId} - /pets/mine -``` - -The following paths are considered identical and invalid: - -``` - /pets/{petId} - /pets/{name} -``` - -The following may lead to ambiguous resolution: - -``` - /{entity}/me - /books/{id} -``` - -##### Paths Object Example - -```json -{ - "/pets": { - "get": { - "description": "Returns all pets from the system that the user has access to", - "responses": { - "200": { - "description": "A list of pets.", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/pet" - } - } - } - } - } - } - } - } -} -``` - -```yaml -/pets: - get: - description: Returns all pets from the system that the user has access to - responses: - '200': - description: A list of pets. - content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/pet' -``` - -#### Path Item Object - -Describes the operations available on a single path. -A Path Item MAY be empty, due to [ACL constraints](#securityFiltering). -The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -$ref | `string` | Allows for a referenced definition of this path item. The referenced structure MUST be in the form of a [Path Item Object](#pathItemObject). In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving [Relative References](#relativeReferencesURI). -summary| `string` | An optional, string summary, intended to apply to all operations in this path. -description | `string` | An optional, string description, intended to apply to all operations in this path. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -get | [Operation Object](#operationObject) | A definition of a GET operation on this path. -put | [Operation Object](#operationObject) | A definition of a PUT operation on this path. -post | [Operation Object](#operationObject) | A definition of a POST operation on this path. -delete | [Operation Object](#operationObject) | A definition of a DELETE operation on this path. -options | [Operation Object](#operationObject) | A definition of a OPTIONS operation on this path. -head | [Operation Object](#operationObject) | A definition of a HEAD operation on this path. -patch | [Operation Object](#operationObject) | A definition of a PATCH operation on this path. -trace | [Operation Object](#operationObject) | A definition of a TRACE operation on this path. -servers | [[Server Object](#serverObject)] | An alternative `server` array to service all operations in this path. -parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). - - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Path Item Object Example - -```json -{ - "get": { - "description": "Returns pets based on ID", - "summary": "Find pets by ID", - "operationId": "getPetsById", - "responses": { - "200": { - "description": "pet response", - "content": { - "*/*": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Pet" - } - } - } - } - }, - "default": { - "description": "error payload", - "content": { - "text/html": { - "schema": { - "$ref": "#/components/schemas/ErrorModel" - } - } - } - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to use", - "required": true, - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "style": "simple" - } - ] -} -``` - -```yaml -get: - description: Returns pets based on ID - summary: Find pets by ID - operationId: getPetsById - responses: - '200': - description: pet response - content: - '*/*' : - schema: - type: array - items: - $ref: '#/components/schemas/Pet' - default: - description: error payload - content: - 'text/html': - schema: - $ref: '#/components/schemas/ErrorModel' -parameters: -- name: id - in: path - description: ID of pet to use - required: true - schema: - type: array - items: - type: string - style: simple -``` - -#### Operation Object - -Describes a single API operation on a path. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -tags | [`string`] | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. -summary | `string` | A short summary of what the operation does. -description | `string` | A verbose explanation of the operation behavior. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this operation. -operationId | `string` | Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is **case-sensitive**. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. -parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for this operation. If a parameter is already defined at the [Path Item](#pathItemParameters), the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). -requestBody | [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject) | The request body applicable for this operation. The `requestBody` is fully supported in HTTP methods where the HTTP 1.1 specification [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague (such as [GET](https://tools.ietf.org/html/rfc7231#section-4.3.1), [HEAD](https://tools.ietf.org/html/rfc7231#section-4.3.2) and [DELETE](https://tools.ietf.org/html/rfc7231#section-4.3.5)), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible. -responses | [Responses Object](#responsesObject) | The list of possible responses as they are returned from executing this operation. -callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a [Callback Object](#callbackObject) that describes a request that may be initiated by the API provider and the expected responses. -deprecated | `boolean` | Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`. -security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level [`security`](#oasSecurity). To remove a top-level security declaration, an empty array can be used. -servers | [[Server Object](#serverObject)] | An alternative `server` array to service this operation. If an alternative `server` object is specified at the Path Item Object or Root level, it will be overridden by this value. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Operation Object Example - -```json -{ - "tags": [ - "pet" - ], - "summary": "Updates a pet in the store with form data", - "operationId": "updatePetWithForm", - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be updated", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "type": "object", - "properties": { - "name": { - "description": "Updated name of the pet", - "type": "string" - }, - "status": { - "description": "Updated status of the pet", - "type": "string" - } - }, - "required": ["status"] - } - } - } - }, - "responses": { - "200": { - "description": "Pet updated.", - "content": { - "application/json": {}, - "application/xml": {} - } - }, - "405": { - "description": "Method Not Allowed", - "content": { - "application/json": {}, - "application/xml": {} - } - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] -} -``` - -```yaml -tags: -- pet -summary: Updates a pet in the store with form data -operationId: updatePetWithForm -parameters: -- name: petId - in: path - description: ID of pet that needs to be updated - required: true - schema: - type: string -requestBody: - content: - 'application/x-www-form-urlencoded': - schema: - type: object - properties: - name: - description: Updated name of the pet - type: string - status: - description: Updated status of the pet - type: string - required: - - status -responses: - '200': - description: Pet updated. - content: - 'application/json': {} - 'application/xml': {} - '405': - description: Method Not Allowed - content: - 'application/json': {} - 'application/xml': {} -security: -- petstore_auth: - - write:pets - - read:pets -``` - - -#### External Documentation Object - -Allows referencing an external resource for extended documentation. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -description | `string` | A description of the target documentation. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -url | `string` | **REQUIRED**. The URL for the target documentation. This MUST be in the form of a URL. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### External Documentation Object Example - -```json -{ - "description": "Find more info here", - "url": "https://example.com" -} -``` - -```yaml -description: Find more info here -url: https://example.com -``` - -#### Parameter Object - -Describes a single operation parameter. - -A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). - -##### Parameter Locations -There are four possible parameter locations specified by the `in` field: -* path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. -* query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. -* header - Custom headers that are expected as part of the request. Note that [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. -* cookie - Used to pass a specific cookie value to the API. - - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -name | `string` | **REQUIRED**. The name of the parameter. Parameter names are *case sensitive*.
  • If [`in`](#parameterIn) is `"path"`, the `name` field MUST correspond to a template expression occurring within the [path](#pathsPath) field in the [Paths Object](#pathsObject). See [Path Templating](#pathTemplating) for further information.
  • If [`in`](#parameterIn) is `"header"` and the `name` field is `"Accept"`, `"Content-Type"` or `"Authorization"`, the parameter definition SHALL be ignored.
  • For all other cases, the `name` corresponds to the parameter name used by the [`in`](#parameterIn) property.
-in | `string` | **REQUIRED**. The location of the parameter. Possible values are `"query"`, `"header"`, `"path"` or `"cookie"`. -description | `string` | A brief description of the parameter. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -required | `boolean` | Determines whether this parameter is mandatory. If the [parameter location](#parameterIn) is `"path"`, this property is **REQUIRED** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. - deprecated | `boolean` | Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`. - allowEmptyValue | `boolean` | Sets the ability to pass empty-valued parameters. This is valid only for `query` parameters and allows sending a parameter with an empty value. Default value is `false`. If [`style`](#parameterStyle) is used, and if behavior is `n/a` (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision. - -The rules for serialization of the parameter are specified in one of two ways. -For simpler scenarios, a [`schema`](#parameterSchema) and [`style`](#parameterStyle) can describe the structure and syntax of the parameter. - -Field Name | Type | Description ----|:---:|--- -style | `string` | Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `query` - `form`; for `path` - `simple`; for `header` - `simple`; for `cookie` - `form`. -explode | `boolean` | When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this property has no effect. When [`style`](#parameterStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. -allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. This property only applies to parameters with an `in` value of `query`. The default value is `false`. -schema | [Schema Object](#schemaObject) | The schema defining the type used for the parameter. -example | Any | Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` that contains an example, the `example` value SHALL _override_ the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary. -examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` that contains an example, the `examples` value SHALL _override_ the example provided by the schema. - -For more complex scenarios, the [`content`](#parameterContent) property can define the media type and schema of the parameter. -A parameter MUST contain either a `schema` property, or a `content` property, but not both. -When `example` or `examples` are provided in conjunction with the `schema` object, the example MUST follow the prescribed serialization strategy for the parameter. - - -Field Name | Type | Description ----|:---:|--- -content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. - -##### Style Values - -In order to support common ways of serializing simple parameters, a set of `style` values are defined. - -`style` | [`type`](#dataTypes) | `in` | Comments ------------ | ------ | -------- | -------- -matrix | `primitive`, `array`, `object` | `path` | Path-style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7) -label | `primitive`, `array`, `object` | `path` | Label style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.5) -form | `primitive`, `array`, `object` | `query`, `cookie` | Form style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.8). This option replaces `collectionFormat` with a `csv` (when `explode` is false) or `multi` (when `explode` is true) value from OpenAPI 2.0. -simple | `array` | `path`, `header` | Simple style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.2). This option replaces `collectionFormat` with a `csv` value from OpenAPI 2.0. -spaceDelimited | `array`, `object` | `query` | Space separated array or object values. This option replaces `collectionFormat` equal to `ssv` from OpenAPI 2.0. -pipeDelimited | `array`, `object` | `query` | Pipe separated array or object values. This option replaces `collectionFormat` equal to `pipes` from OpenAPI 2.0. -deepObject | `object` | `query` | Provides a simple way of rendering nested objects using form parameters. - - -##### Style Examples - -Assume a parameter named `color` has one of the following values: - -``` - string -> "blue" - array -> ["blue","black","brown"] - object -> { "R": 100, "G": 200, "B": 150 } -``` -The following table shows examples of rendering differences for each value. - -[`style`](#styleValues) | `explode` | `empty` | `string` | `array` | `object` ------------ | ------ | -------- | -------- | -------- | ------- -matrix | false | ;color | ;color=blue | ;color=blue,black,brown | ;color=R,100,G,200,B,150 -matrix | true | ;color | ;color=blue | ;color=blue;color=black;color=brown | ;R=100;G=200;B=150 -label | false | . | .blue | .blue.black.brown | .R.100.G.200.B.150 -label | true | . | .blue | .blue.black.brown | .R=100.G=200.B=150 -form | false | color= | color=blue | color=blue,black,brown | color=R,100,G,200,B,150 -form | true | color= | color=blue | color=blue&color=black&color=brown | R=100&G=200&B=150 -simple | false | n/a | blue | blue,black,brown | R,100,G,200,B,150 -simple | true | n/a | blue | blue,black,brown | R=100,G=200,B=150 -spaceDelimited | false | n/a | n/a | blue%20black%20brown | R%20100%20G%20200%20B%20150 -pipeDelimited | false | n/a | n/a | blue\|black\|brown | R\|100\|G\|200\|B\|150 -deepObject | true | n/a | n/a | n/a | color[R]=100&color[G]=200&color[B]=150 - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Parameter Object Examples - -A header parameter with an array of 64 bit integer numbers: - -```json -{ - "name": "token", - "in": "header", - "description": "token to be passed as a header", - "required": true, - "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int64" - } - }, - "style": "simple" -} -``` - -```yaml -name: token -in: header -description: token to be passed as a header -required: true -schema: - type: array - items: - type: integer - format: int64 -style: simple -``` - -A path parameter of a string value: -```json -{ - "name": "username", - "in": "path", - "description": "username to fetch", - "required": true, - "schema": { - "type": "string" - } -} -``` - -```yaml -name: username -in: path -description: username to fetch -required: true -schema: - type: string -``` - -An optional query parameter of a string value, allowing multiple values by repeating the query parameter: -```json -{ - "name": "id", - "in": "query", - "description": "ID of the object to fetch", - "required": false, - "schema": { - "type": "array", - "items": { - "type": "string" - } - }, - "style": "form", - "explode": true -} -``` - -```yaml -name: id -in: query -description: ID of the object to fetch -required: false -schema: - type: array - items: - type: string -style: form -explode: true -``` - -A free-form query parameter, allowing undefined parameters of a specific type: -```json -{ - "in": "query", - "name": "freeForm", - "schema": { - "type": "object", - "additionalProperties": { - "type": "integer" - }, - }, - "style": "form" -} -``` - -```yaml -in: query -name: freeForm -schema: - type: object - additionalProperties: - type: integer -style: form -``` - -A complex parameter using `content` to define serialization: - -```json -{ - "in": "query", - "name": "coordinates", - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "lat", - "long" - ], - "properties": { - "lat": { - "type": "number" - }, - "long": { - "type": "number" - } - } - } - } - } -} -``` - -```yaml -in: query -name: coordinates -content: - application/json: - schema: - type: object - required: - - lat - - long - properties: - lat: - type: number - long: - type: number -``` - -#### Request Body Object - -Describes a single request body. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -description | `string` | A brief description of the request body. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -content | Map[`string`, [Media Type Object](#mediaTypeObject)] | **REQUIRED**. The content of the request body. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* -required | `boolean` | Determines if the request body is required in the request. Defaults to `false`. - - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Request Body Examples - -A request body with a referenced model definition. -```json -{ - "description": "user to add to the system", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/User" - }, - "examples": { - "user" : { - "summary": "User Example", - "externalValue": "https://foo.bar/examples/user-example.json" - } - } - }, - "application/xml": { - "schema": { - "$ref": "#/components/schemas/User" - }, - "examples": { - "user" : { - "summary": "User example in XML", - "externalValue": "https://foo.bar/examples/user-example.xml" - } - } - }, - "text/plain": { - "examples": { - "user" : { - "summary": "User example in Plain text", - "externalValue": "https://foo.bar/examples/user-example.txt" - } - } - }, - "*/*": { - "examples": { - "user" : { - "summary": "User example in other format", - "externalValue": "https://foo.bar/examples/user-example.whatever" - } - } - } - } -} -``` - -```yaml -description: user to add to the system -content: - 'application/json': - schema: - $ref: '#/components/schemas/User' - examples: - user: - summary: User Example - externalValue: 'https://foo.bar/examples/user-example.json' - 'application/xml': - schema: - $ref: '#/components/schemas/User' - examples: - user: - summary: User example in XML - externalValue: 'https://foo.bar/examples/user-example.xml' - 'text/plain': - examples: - user: - summary: User example in Plain text - externalValue: 'https://foo.bar/examples/user-example.txt' - '*/*': - examples: - user: - summary: User example in other format - externalValue: 'https://foo.bar/examples/user-example.whatever' -``` - -A body parameter that is an array of string values: -```json -{ - "description": "user to add to the system", - "required": true, - "content": { - "text/plain": { - "schema": { - "type": "array", - "items": { - "type": "string" - } - } - } - } -} -``` - -```yaml -description: user to add to the system -required: true -content: - text/plain: - schema: - type: array - items: - type: string -``` - - -#### Media Type Object -Each Media Type Object provides schema and examples for the media type identified by its key. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -schema | [Schema Object](#schemaObject) | The schema defining the content of the request, response, or parameter. -example | Any | Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` which contains an example, the `example` value SHALL _override_ the example provided by the schema. -examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` which contains an example, the `examples` value SHALL _override_ the example provided by the schema. -encoding | Map[`string`, [Encoding Object](#encodingObject)] | A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to `requestBody` objects when the media type is `multipart` or `application/x-www-form-urlencoded`. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Media Type Examples - -```json -{ - "application/json": { - "schema": { - "$ref": "#/components/schemas/Pet" - }, - "examples": { - "cat" : { - "summary": "An example of a cat", - "value": - { - "name": "Fluffy", - "petType": "Cat", - "color": "White", - "gender": "male", - "breed": "Persian" - } - }, - "dog": { - "summary": "An example of a dog with a cat's name", - "value" : { - "name": "Puma", - "petType": "Dog", - "color": "Black", - "gender": "Female", - "breed": "Mixed" - }, - "frog": { - "$ref": "#/components/examples/frog-example" - } - } - } - } -} -``` - -```yaml -application/json: - schema: - $ref: "#/components/schemas/Pet" - examples: - cat: - summary: An example of a cat - value: - name: Fluffy - petType: Cat - color: White - gender: male - breed: Persian - dog: - summary: An example of a dog with a cat's name - value: - name: Puma - petType: Dog - color: Black - gender: Female - breed: Mixed - frog: - $ref: "#/components/examples/frog-example" -``` - -##### Considerations for File Uploads - -In contrast with the 2.0 specification, `file` input/output content in OpenAPI is described with the same semantics as any other schema type. - -In contrast with the 3.0 specification, the `format` keyword has no effect on the content-encoding of the schema. JSON Schema offers a `contentEncoding` keyword, which may be used to specify the `Content-Encoding` for the schema. The `contentEncoding` keyword supports all encodings defined in [RFC4648](https://tools.ietf.org/html/rfc4648), including "base64" and "base64url", as well as "quoted-printable" from [RFC2045](https://tools.ietf.org/html/rfc2045#section-6.7). The encoding specified by the `contentEncoding` keyword is independent of an encoding specified by the `Content-Type` header in the request or response or metadata of a multipart body -- when both are present, the encoding specified in the `contentEncoding` is applied first and then the encoding specified in the `Content-Type` header. - -JSON Schema also offers a `contentMediaType` keyword. However, when the media type is already specified by the Media Type Object's key, or by the `contentType` field of an [Encoding Object](#encodingObject), the `contentMediaType` keyword SHALL be ignored if present. - -Examples: - -Content transferred in binary (octet-stream) MAY omit `schema`: - -```yaml -# a PNG image as a binary file: -content: - image/png: {} -``` - -```yaml -# an arbitrary binary file: -content: - application/octet-stream: {} -``` - -Binary content transferred with base64 encoding: - -```yaml -content: - image/png: - schema: - type: string - contentMediaType: image/png - contentEncoding: base64 -``` - -Note that the `Content-Type` remains `image/png`, describing the semantics of the payload. The JSON Schema `type` and `contentEncoding` fields explain that the payload is transferred as text. The JSON Schema `contentMediaType` is technically redundant, but can be used by JSON Schema tools that may not be aware of the OpenAPI context. - -These examples apply to either input payloads of file uploads or response payloads. - -A `requestBody` for submitting a file in a `POST` operation may look like the following example: - -```yaml -requestBody: - content: - application/octet-stream: {} -``` - -In addition, specific media types MAY be specified: - -```yaml -# multiple, specific media types may be specified: -requestBody: - content: - # a binary file of type png or jpeg - image/jpeg: {} - image/png: {} -``` - -To upload multiple files, a `multipart` media type MUST be used: - -```yaml -requestBody: - content: - multipart/form-data: - schema: - properties: - # The property name 'file' will be used for all files. - file: - type: array - items: {} -``` - -As seen in the section on `multipart/form-data` below, the empty schema for `items` indicates a media type of `application/octet-stream`. - -##### Support for x-www-form-urlencoded Request Bodies - -To submit content using form url encoding via [RFC1866](https://tools.ietf.org/html/rfc1866), the following -definition may be used: - -```yaml -requestBody: - content: - application/x-www-form-urlencoded: - schema: - type: object - properties: - id: - type: string - format: uuid - address: - # complex types are stringified to support RFC 1866 - type: object - properties: {} -``` - -In this example, the contents in the `requestBody` MUST be stringified per [RFC1866](https://tools.ietf.org/html/rfc1866/) when passed to the server. In addition, the `address` field complex object will be stringified. - -When passing complex objects in the `application/x-www-form-urlencoded` content type, the default serialization strategy of such properties is described in the [`Encoding Object`](#encodingObject)'s [`style`](#encodingStyle) property as `form`. - -##### Special Considerations for `multipart` Content - -It is common to use `multipart/form-data` as a `Content-Type` when transferring request bodies to operations. In contrast to 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content. This supports complex structures as well as supporting mechanisms for multiple file uploads. - -In a `multipart/form-data` request body, each schema property, or each element of a schema array property, takes a section in the payload with an internal header as defined by [RFC7578](https://tools.ietf.org/html/rfc7578). The serialization strategy for each property of a `multipart/form-data` request body can be specified in an associated [`Encoding Object`](#encodingObject). - -When passing in `multipart` types, boundaries MAY be used to separate sections of the content being transferred – thus, the following default `Content-Type`s are defined for `multipart`: - -* If the property is a primitive, or an array of primitive values, the default Content-Type is `text/plain` -* If the property is complex, or an array of complex values, the default Content-Type is `application/json` -* If the property is a `type: string` with a `contentEncoding`, the default Content-Type is `application/octet-stream` - -Per the JSON Schema specification, `contentMediaType` without `contentEncoding` present is treated as if `contentEncoding: identity` were present. While useful for embedding text documents such as `text/html` into JSON strings, it is not useful for a `multipart/form-data` part, as it just causes the document to be treated as `text/plain` instead of its actual media type. Use the Encoding Object without `contentMediaType` if no `contentEncoding` is required. - -Examples: - -```yaml -requestBody: - content: - multipart/form-data: - schema: - type: object - properties: - id: - type: string - format: uuid - address: - # default Content-Type for objects is `application/json` - type: object - properties: {} - profileImage: - # Content-Type for application-level encoded resource is `text/plain` - type: string - contentMediaType: image/png - contentEncoding: base64 - children: - # default Content-Type for arrays is based on the _inner_ type (`text/plain` here) - type: array - items: - type: string - addresses: - # default Content-Type for arrays is based on the _inner_ type (object shown, so `application/json` in this example) - type: array - items: - type: object - $ref: '#/components/schemas/Address' -``` - -An `encoding` attribute is introduced to give you control over the serialization of parts of `multipart` request bodies. This attribute is _only_ applicable to `multipart` and `application/x-www-form-urlencoded` request bodies. - -#### Encoding Object - -A single encoding definition applied to a single schema property. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -contentType | `string` | The Content-Type for encoding a specific property. Default value depends on the property type: for `object` - `application/json`; for `array` – the default is defined based on the inner type; for all other cases the default is `application/octet-stream`. The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or a comma-separated list of the two types. -headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | A map allowing additional information to be provided as headers, for example `Content-Disposition`. `Content-Type` is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a `multipart`. -style | `string` | Describes how a specific property value will be serialized depending on its type. See [Parameter Object](#parameterObject) for details on the [`style`](#parameterStyle) property. The behavior follows the same values as `query` parameters, including default values. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of [`contentType`](#encodingContentType) (implicit or explicit) SHALL be ignored. -explode | `boolean` | When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When [`style`](#encodingStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of [`contentType`](#encodingContentType) (implicit or explicit) SHALL be ignored. -allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of [`contentType`](#encodingContentType) (implicit or explicit) SHALL be ignored. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Encoding Object Example - -```yaml -requestBody: - content: - multipart/form-data: - schema: - type: object - properties: - id: - # default is text/plain - type: string - format: uuid - address: - # default is application/json - type: object - properties: {} - historyMetadata: - # need to declare XML format! - description: metadata in XML format - type: object - properties: {} - profileImage: {} - encoding: - historyMetadata: - # require XML Content-Type in utf-8 encoding - contentType: application/xml; charset=utf-8 - profileImage: - # only accept png/jpeg - contentType: image/png, image/jpeg - headers: - X-Rate-Limit-Limit: - description: The number of allowed requests in the current period - schema: - type: integer -``` - -#### Responses Object - -A container for the expected responses of an operation. -The container maps a HTTP response code to the expected response. - -The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. -However, documentation is expected to cover a successful operation response and any known errors. - -The `default` MAY be used as a default response object for all HTTP codes -that are not covered individually by the `Responses Object`. - -The `Responses Object` MUST contain at least one response code, and if only one -response code is provided it SHOULD be the response for a successful operation -call. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -default | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. - -##### Patterned Fields -Field Pattern | Type | Description ----|:---:|--- -[HTTP Status Code](#httpCodes) | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | Any [HTTP status code](#httpCodes) can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `[200-299]`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. - - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Responses Object Example - -A 200 response for a successful operation and a default response for others (implying an error): - -```json -{ - "200": { - "description": "a pet to be returned", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Pet" - } - } - } - }, - "default": { - "description": "Unexpected error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ErrorModel" - } - } - } - } -} -``` - -```yaml -'200': - description: a pet to be returned - content: - application/json: - schema: - $ref: '#/components/schemas/Pet' -default: - description: Unexpected error - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorModel' -``` - -#### Response Object -Describes a single response from an API Operation, including design-time, static -`links` to operations based on the response. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -description | `string` | **REQUIRED**. A description of the response. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | Maps a header name to its definition. [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL be ignored. -content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing descriptions of potential response payloads. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* -links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for [Component Objects](#componentsObject). - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Response Object Examples - -Response of an array of a complex type: - -```json -{ - "description": "A complex object array response", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/VeryComplexType" - } - } - } - } -} -``` - -```yaml -description: A complex object array response -content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/VeryComplexType' -``` - -Response with a string type: - -```json -{ - "description": "A simple string response", - "content": { - "text/plain": { - "schema": { - "type": "string" - } - } - } - -} -``` - -```yaml -description: A simple string response -content: - text/plain: - schema: - type: string -``` - -Plain text response with headers: - -```json -{ - "description": "A simple string response", - "content": { - "text/plain": { - "schema": { - "type": "string", - "example": "whoa!" - } - } - }, - "headers": { - "X-Rate-Limit-Limit": { - "description": "The number of allowed requests in the current period", - "schema": { - "type": "integer" - } - }, - "X-Rate-Limit-Remaining": { - "description": "The number of remaining requests in the current period", - "schema": { - "type": "integer" - } - }, - "X-Rate-Limit-Reset": { - "description": "The number of seconds left in the current period", - "schema": { - "type": "integer" - } - } - } -} -``` - -```yaml -description: A simple string response -content: - text/plain: - schema: - type: string - example: 'whoa!' -headers: - X-Rate-Limit-Limit: - description: The number of allowed requests in the current period - schema: - type: integer - X-Rate-Limit-Remaining: - description: The number of remaining requests in the current period - schema: - type: integer - X-Rate-Limit-Reset: - description: The number of seconds left in the current period - schema: - type: integer -``` - -Response with no return value: - -```json -{ - "description": "object created" -} -``` - -```yaml -description: object created -``` - -#### Callback Object - -A map of possible out-of band callbacks related to the parent operation. -Each value in the map is a [Path Item Object](#pathItemObject) that describes a set of requests that may be initiated by the API provider and the expected responses. -The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. - -To describe incoming requests from the API provider independent from another API call, use the [`webhooks`](#oasWebhooks) field. - -##### Patterned Fields -Field Pattern | Type | Description ----|:---:|--- -{expression} | [Path Item Object](#pathItemObject) \| [Reference Object](#referenceObject) | A Path Item Object, or a reference to one, used to define a callback request and expected responses. A [complete example](../examples/v3.0/callback-example.yaml) is available. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Key Expression - -The key that identifies the [Path Item Object](#pathItemObject) is a [runtime expression](#runtimeExpression) that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. -A simple example might be `$request.body#/url`. -However, using a [runtime expression](#runtimeExpression) the complete HTTP message can be accessed. -This includes accessing any part of a body that a JSON Pointer [RFC6901](https://tools.ietf.org/html/rfc6901) can reference. - -For example, given the following HTTP request: - -```http -POST /subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning HTTP/1.1 -Host: example.org -Content-Type: application/json -Content-Length: 187 - -{ - "failedUrl" : "https://clientdomain.com/failed", - "successUrls" : [ - "https://clientdomain.com/fast", - "https://clientdomain.com/medium", - "https://clientdomain.com/slow" - ] -} - -201 Created -Location: https://example.org/subscription/1 -``` - -The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named `eventType` and a query parameter named `queryUrl`. - -Expression | Value ----|:--- -$url | https://example.org/subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning -$method | POST -$request.path.eventType | myevent -$request.query.queryUrl | https://clientdomain.com/stillrunning -$request.header.content-Type | application/json -$request.body#/failedUrl | https://clientdomain.com/failed -$request.body#/successUrls/2 | https://clientdomain.com/medium -$response.header.Location | https://example.org/subscription/1 - - -##### Callback Object Examples - -The following example uses the user provided `queryUrl` query string parameter to define the callback URL. This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook. - -```yaml -myCallback: - '{$request.query.queryUrl}': - post: - requestBody: - description: Callback payload - content: - 'application/json': - schema: - $ref: '#/components/schemas/SomePayload' - responses: - '200': - description: callback successfully processed -``` - -The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the `id` and `email` property in the request body. - -```yaml -transactionCallback: - 'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}': - post: - requestBody: - description: Callback payload - content: - 'application/json': - schema: - $ref: '#/components/schemas/SomePayload' - responses: - '200': - description: callback successfully processed -``` - -#### Example Object - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -summary | `string` | Short description for the example. -description | `string` | Long description for the example. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -value | Any | Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary. -externalValue | `string` | A URI that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. See the rules for resolving [Relative References](#relativeReferencesURI). - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -In all cases, the example value is expected to be compatible with the type schema -of its associated value. Tooling implementations MAY choose to -validate compatibility automatically, and reject the example value(s) if incompatible. - -##### Example Object Examples - -In a request body: - -```yaml -requestBody: - content: - 'application/json': - schema: - $ref: '#/components/schemas/Address' - examples: - foo: - summary: A foo example - value: {"foo": "bar"} - bar: - summary: A bar example - value: {"bar": "baz"} - 'application/xml': - examples: - xmlExample: - summary: This is an example in XML - externalValue: 'https://example.org/examples/address-example.xml' - 'text/plain': - examples: - textExample: - summary: This is a text example - externalValue: 'https://foo.bar/examples/address-example.txt' -``` - -In a parameter: - -```yaml -parameters: - - name: 'zipCode' - in: 'query' - schema: - type: 'string' - format: 'zip-code' - examples: - zip-example: - $ref: '#/components/examples/zip-example' -``` - -In a response: - -```yaml -responses: - '200': - description: your car appointment has been booked - content: - application/json: - schema: - $ref: '#/components/schemas/SuccessResponse' - examples: - confirmation-success: - $ref: '#/components/examples/confirmation-success' -``` - - -#### Link Object - -The `Link object` represents a possible design-time link for a response. -The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. - -Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. - -For computing links, and providing instructions to execute them, a [runtime expression](#runtimeExpression) is used for accessing values in an operation and using them as parameters while invoking the linked operation. - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -operationRef | `string` | A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an [Operation Object](#operationObject). Relative `operationRef` values MAY be used to locate an existing [Operation Object](#operationObject) in the OpenAPI definition. See the rules for resolving [Relative References](#relativeReferencesURI). -operationId | `string` | The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field. -parameters | Map[`string`, Any \| [{expression}](#runtimeExpression)] | A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the [parameter location](#parameterIn) `[{in}.]{name}` for operations that use the same parameter name in different locations (e.g. path.id). -requestBody | Any \| [{expression}](#runtimeExpression) | A literal value or [{expression}](#runtimeExpression) to use as a request body when calling the target operation. -description | `string` | A description of the link. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -server | [Server Object](#serverObject) | A server object to be used by the target operation. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -A linked operation MUST be identified using either an `operationRef` or `operationId`. -In the case of an `operationId`, it MUST be unique and resolved in the scope of the OAS document. -Because of the potential for name clashes, the `operationRef` syntax is preferred -for OpenAPI documents with external references. - -##### Examples - -Computing a link from a request operation where the `$request.path.id` is used to pass a request parameter to the linked operation. - -```yaml -paths: - /users/{id}: - parameters: - - name: id - in: path - required: true - description: the user identifier, as userId - schema: - type: string - get: - responses: - '200': - description: the user being returned - content: - application/json: - schema: - type: object - properties: - uuid: # the unique user id - type: string - format: uuid - links: - address: - # the target link operationId - operationId: getUserAddress - parameters: - # get the `id` field from the request path parameter named `id` - userId: $request.path.id - # the path item of the linked operation - /users/{userid}/address: - parameters: - - name: userid - in: path - required: true - description: the user identifier, as userId - schema: - type: string - # linked operation - get: - operationId: getUserAddress - responses: - '200': - description: the user's address -``` - -When a runtime expression fails to evaluate, no parameter value is passed to the target operation. - -Values from the response body can be used to drive a linked operation. - -```yaml -links: - address: - operationId: getUserAddressByUUID - parameters: - # get the `uuid` field from the `uuid` field in the response body - userUuid: $response.body#/uuid -``` - -Clients follow all links at their discretion. -Neither permissions, nor the capability to make a successful call to that link, is guaranteed -solely by the existence of a relationship. - - -##### OperationRef Examples - -As references to `operationId` MAY NOT be possible (the `operationId` is an optional -field in an [Operation Object](#operationObject)), references MAY also be made through a relative `operationRef`: - -```yaml -links: - UserRepositories: - # returns array of '#/components/schemas/repository' - operationRef: '#/paths/~12.0~1repositories~1{username}/get' - parameters: - username: $response.body#/username -``` - -or an absolute `operationRef`: - -```yaml -links: - UserRepositories: - # returns array of '#/components/schemas/repository' - operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get' - parameters: - username: $response.body#/username -``` - -Note that in the use of `operationRef`, the _escaped forward-slash_ is necessary when -using JSON references. - - -##### Runtime Expressions - -Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. -This mechanism is used by [Link Objects](#linkObject) and [Callback Objects](#callbackObject). - -The runtime expression is defined by the following [ABNF](https://tools.ietf.org/html/rfc5234) syntax - -```abnf - expression = ( "$url" / "$method" / "$statusCode" / "$request." source / "$response." source ) - source = ( header-reference / query-reference / path-reference / body-reference ) - header-reference = "header." token - query-reference = "query." name - path-reference = "path." name - body-reference = "body" ["#" json-pointer ] - json-pointer = *( "/" reference-token ) - reference-token = *( unescaped / escaped ) - unescaped = %x00-2E / %x30-7D / %x7F-10FFFF - ; %x2F ('/') and %x7E ('~') are excluded from 'unescaped' - escaped = "~" ( "0" / "1" ) - ; representing '~' and '/', respectively - name = *( CHAR ) - token = 1*tchar - tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / - "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA -``` - -Here, `json-pointer` is taken from [RFC6901](https://tools.ietf.org/html/rfc6901), `char` from [RFC7159](https://tools.ietf.org/html/rfc7159#section-7) and `token` from [RFC7230](https://tools.ietf.org/html/rfc7230#section-3.2.6). - -The `name` identifier is case-sensitive, whereas `token` is not. - -The table below provides examples of runtime expressions and examples of their use in a value: - -##### Examples - -Source Location | example expression | notes ----|:---|:---| -HTTP Method | `$method` | The allowable values for the `$method` will be those for the HTTP operation. -Requested media type | `$request.header.accept` | -Request parameter | `$request.path.id` | Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated. This includes request headers. -Request body property | `$request.body#/user/uuid` | In operations which accept payloads, references may be made to portions of the `requestBody` or the entire body. -Request URL | `$url` | -Response value | `$response.body#/status` | In operations which return payloads, references may be made to portions of the response body or the entire body. -Response header | `$response.header.Server` | Single header values only are available - -Runtime expressions preserve the type of the referenced value. -Expressions can be embedded into string values by surrounding the expression with `{}` curly braces. - -#### Header Object - -The Header Object follows the structure of the [Parameter Object](#parameterObject) with the following changes: - -1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. -1. `in` MUST NOT be specified, it is implicitly in `header`. -1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, [`style`](#parameterStyle)). - -##### Header Object Example - -A simple header of type `integer`: - -```json -{ - "description": "The number of allowed requests in the current period", - "schema": { - "type": "integer" - } -} -``` - -```yaml -description: The number of allowed requests in the current period -schema: - type: integer -``` - -#### Tag Object - -Adds metadata to a single tag that is used by the [Operation Object](#operationObject). -It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -name | `string` | **REQUIRED**. The name of the tag. -description | `string` | A description for the tag. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this tag. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Tag Object Example - -```json -{ - "name": "pet", - "description": "Pets operations" -} -``` - -```yaml -name: pet -description: Pets operations -``` - - -#### Reference Object - -A simple object to allow referencing other components in the OpenAPI document, internally and externally. - -The `$ref` string value contains a URI [RFC3986](https://tools.ietf.org/html/rfc3986), which identifies the location of the value being referenced. - -See the rules for resolving [Relative References](#relativeReferencesURI). - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -$ref | `string` | **REQUIRED**. The reference identifier. This MUST be in the form of a URI. -summary | `string` | A short summary which by default SHOULD override that of the referenced component. If the referenced object-type does not allow a `summary` field, then this field has no effect. -description | `string` | A description which by default SHOULD override that of the referenced component. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. If the referenced object-type does not allow a `description` field, then this field has no effect. - -This object cannot be extended with additional properties and any properties added SHALL be ignored. - -Note that this restriction on additional properties is a difference between Reference Objects and [`Schema Objects`](#schemaObject) that contain a `$ref` keyword. - -##### Reference Object Example - -```json -{ - "$ref": "#/components/schemas/Pet" -} -``` - -```yaml -$ref: '#/components/schemas/Pet' -``` - -##### Relative Schema Document Example -```json -{ - "$ref": "Pet.json" -} -``` - -```yaml -$ref: Pet.yaml -``` - -##### Relative Documents With Embedded Schema Example -```json -{ - "$ref": "definitions.json#/Pet" -} -``` - -```yaml -$ref: definitions.yaml#/Pet -``` - -#### Schema Object - -The Schema Object allows the definition of input and output data types. -These types can be objects, but also primitives and arrays. This object is a superset of the [JSON Schema Specification Draft 2020-12](https://tools.ietf.org/html/draft-bhutton-json-schema-00). - -For more information about the properties, see [JSON Schema Core](https://tools.ietf.org/html/draft-bhutton-json-schema-00) and [JSON Schema Validation](https://tools.ietf.org/html/draft-bhutton-json-schema-validation-00). - -Unless stated otherwise, the property definitions follow those of JSON Schema and do not add any additional semantics. -Where JSON Schema indicates that behavior is defined by the application (e.g. for annotations), OAS also defers the definition of semantics to the application consuming the OpenAPI document. - -##### Properties - -The OpenAPI Schema Object [dialect](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-4.3.3) is defined as requiring the [OAS base vocabulary](#baseVocabulary), in addition to the vocabularies as specified in the JSON Schema draft 2020-12 [general purpose meta-schema](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-8). - -The OpenAPI Schema Object dialect for this version of the specification is identified by the URI `https://spec.openapis.org/oas/3.1/dialect/base` (the "OAS dialect schema id"). - -The following properties are taken from the JSON Schema specification but their definitions have been extended by the OAS: - -- description - [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -- format - See [Data Type Formats](#dataTypeFormat) for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats. - -In addition to the JSON Schema properties comprising the OAS dialect, the Schema Object supports keywords from any other vocabularies, or entirely arbitrary properties. - -The OpenAPI Specification's base vocabulary is comprised of the following keywords: - -##### Fixed Fields - -Field Name | Type | Description ----|:---:|--- -discriminator | [Discriminator Object](#discriminatorObject) | Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See [Composition and Inheritance](#schemaComposition) for more details. -xml | [XML Object](#xmlObject) | This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property. -externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this schema. -example | Any | A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary.

**Deprecated:** The `example` property has been deprecated in favor of the JSON Schema `examples` keyword. Use of `example` is discouraged, and later versions of this specification may remove it. - -This object MAY be extended with [Specification Extensions](#specificationExtensions), though as noted, additional properties MAY omit the `x-` prefix within this object. - -###### Composition and Inheritance (Polymorphism) - -The OpenAPI Specification allows combining and extending model definitions using the `allOf` property of JSON Schema, in effect offering model composition. -`allOf` takes an array of object definitions that are validated *independently* but together compose a single object. - -While composition offers model extensibility, it does not imply a hierarchy between the models. -To support polymorphism, the OpenAPI Specification adds the `discriminator` field. -When used, the `discriminator` will be the name of the property that decides which schema definition validates the structure of the model. -As such, the `discriminator` field MUST be a required field. -There are two ways to define the value of a discriminator for an inheriting instance. -- Use the schema name. -- Override the schema name by overriding the property with a new value. If a new value exists, this takes precedence over the schema name. -As such, inline schema definitions, which do not have a given id, *cannot* be used in polymorphism. - -###### XML Modeling - -The [xml](#schemaXml) property allows extra definitions when translating the JSON definition to XML. -The [XML Object](#xmlObject) contains additional information about the available options. - -###### Specifying Schema Dialects - -It is important for tooling to be able to determine which dialect or meta-schema any given resource wishes to be processed with: JSON Schema Core, JSON Schema Validation, OpenAPI Schema dialect, or some custom meta-schema. - -The `$schema` keyword MAY be present in any root Schema Object, and if present MUST be used to determine which dialect should be used when processing the schema. This allows use of Schema Objects which comply with other drafts of JSON Schema than the default Draft 2020-12 support. Tooling MUST support the OAS dialect schema id, and MAY support additional values of `$schema`. - -To allow use of a different default `$schema` value for all Schema Objects contained within an OAS document, a `jsonSchemaDialect` value may be set within the OpenAPI Object. If this default is not set, then the OAS dialect schema id MUST be used for these Schema Objects. The value of `$schema` within a Schema Object always overrides any default. - -When a Schema Object is referenced from an external resource which is not an OAS document (e.g. a bare JSON Schema resource), then the value of the `$schema` keyword for schemas within that resource MUST follow [JSON Schema rules](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-8.1.1). - -##### Schema Object Examples - -###### Primitive Sample - -```json -{ - "type": "string", - "format": "email" -} -``` - -```yaml -type: string -format: email -``` - -###### Simple Model - -```json -{ - "type": "object", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "address": { - "$ref": "#/components/schemas/Address" - }, - "age": { - "type": "integer", - "format": "int32", - "minimum": 0 - } - } -} -``` - -```yaml -type: object -required: -- name -properties: - name: - type: string - address: - $ref: '#/components/schemas/Address' - age: - type: integer - format: int32 - minimum: 0 -``` - -###### Model with Map/Dictionary Properties - -For a simple string to string mapping: - -```json -{ - "type": "object", - "additionalProperties": { - "type": "string" - } -} -``` - -```yaml -type: object -additionalProperties: - type: string -``` - -For a string to model mapping: - -```json -{ - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/ComplexModel" - } -} -``` - -```yaml -type: object -additionalProperties: - $ref: '#/components/schemas/ComplexModel' -``` - -###### Model with Example - -```json -{ - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "required": [ - "name" - ], - "example": { - "name": "Puma", - "id": 1 - } -} -``` - -```yaml -type: object -properties: - id: - type: integer - format: int64 - name: - type: string -required: -- name -example: - name: Puma - id: 1 -``` - -###### Models with Composition - -```json -{ - "components": { - "schemas": { - "ErrorModel": { - "type": "object", - "required": [ - "message", - "code" - ], - "properties": { - "message": { - "type": "string" - }, - "code": { - "type": "integer", - "minimum": 100, - "maximum": 600 - } - } - }, - "ExtendedErrorModel": { - "allOf": [ - { - "$ref": "#/components/schemas/ErrorModel" - }, - { - "type": "object", - "required": [ - "rootCause" - ], - "properties": { - "rootCause": { - "type": "string" - } - } - } - ] - } - } - } -} -``` - -```yaml -components: - schemas: - ErrorModel: - type: object - required: - - message - - code - properties: - message: - type: string - code: - type: integer - minimum: 100 - maximum: 600 - ExtendedErrorModel: - allOf: - - $ref: '#/components/schemas/ErrorModel' - - type: object - required: - - rootCause - properties: - rootCause: - type: string -``` - -###### Models with Polymorphism Support - -```json -{ - "components": { - "schemas": { - "Pet": { - "type": "object", - "discriminator": { - "propertyName": "petType" - }, - "properties": { - "name": { - "type": "string" - }, - "petType": { - "type": "string" - } - }, - "required": [ - "name", - "petType" - ] - }, - "Cat": { - "description": "A representation of a cat. Note that `Cat` will be used as the discriminator value.", - "allOf": [ - { - "$ref": "#/components/schemas/Pet" - }, - { - "type": "object", - "properties": { - "huntingSkill": { - "type": "string", - "description": "The measured skill for hunting", - "default": "lazy", - "enum": [ - "clueless", - "lazy", - "adventurous", - "aggressive" - ] - } - }, - "required": [ - "huntingSkill" - ] - } - ] - }, - "Dog": { - "description": "A representation of a dog. Note that `Dog` will be used as the discriminator value.", - "allOf": [ - { - "$ref": "#/components/schemas/Pet" - }, - { - "type": "object", - "properties": { - "packSize": { - "type": "integer", - "format": "int32", - "description": "the size of the pack the dog is from", - "default": 0, - "minimum": 0 - } - }, - "required": [ - "packSize" - ] - } - ] - } - } - } -} -``` - -```yaml -components: - schemas: - Pet: - type: object - discriminator: - propertyName: petType - properties: - name: - type: string - petType: - type: string - required: - - name - - petType - Cat: ## "Cat" will be used as the discriminator value - description: A representation of a cat - allOf: - - $ref: '#/components/schemas/Pet' - - type: object - properties: - huntingSkill: - type: string - description: The measured skill for hunting - enum: - - clueless - - lazy - - adventurous - - aggressive - required: - - huntingSkill - Dog: ## "Dog" will be used as the discriminator value - description: A representation of a dog - allOf: - - $ref: '#/components/schemas/Pet' - - type: object - properties: - packSize: - type: integer - format: int32 - description: the size of the pack the dog is from - default: 0 - minimum: 0 - required: - - packSize -``` - -#### Discriminator Object - -When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the document of an alternative schema based on the value associated with it. - -When using the discriminator, _inline_ schemas will not be considered. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -propertyName | `string` | **REQUIRED**. The name of the property in the payload that will hold the discriminator value. - mapping | Map[`string`, `string`] | An object to hold mappings between payload values and schema names or references. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -The discriminator object is legal only when using one of the composite keywords `oneOf`, `anyOf`, `allOf`. - -In OAS 3.0, a response payload MAY be described to be exactly one of any number of types: - -```yaml -MyResponseType: - oneOf: - - $ref: '#/components/schemas/Cat' - - $ref: '#/components/schemas/Dog' - - $ref: '#/components/schemas/Lizard' -``` - -which means the payload _MUST_, by validation, match exactly one of the schemas described by `Cat`, `Dog`, or `Lizard`. In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use: - - -```yaml -MyResponseType: - oneOf: - - $ref: '#/components/schemas/Cat' - - $ref: '#/components/schemas/Dog' - - $ref: '#/components/schemas/Lizard' - discriminator: - propertyName: petType -``` - -The expectation now is that a property with name `petType` _MUST_ be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload: - -```json -{ - "id": 12345, - "petType": "Cat" -} -``` - -Will indicate that the `Cat` schema be used in conjunction with this payload. - -In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used: - -```yaml -MyResponseType: - oneOf: - - $ref: '#/components/schemas/Cat' - - $ref: '#/components/schemas/Dog' - - $ref: '#/components/schemas/Lizard' - - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json' - discriminator: - propertyName: petType - mapping: - dog: '#/components/schemas/Dog' - monster: 'https://gigantic-server.com/schemas/Monster/schema.json' -``` - -Here the discriminator _value_ of `dog` will map to the schema `#/components/schemas/Dog`, rather than the default (implicit) value of `Dog`. If the discriminator _value_ does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison. - -When used in conjunction with the `anyOf` construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload. - -In both the `oneOf` and `anyOf` use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an `allOf` construct may be used as an alternate schema. - -For example: - -```yaml -components: - schemas: - Pet: - type: object - required: - - petType - properties: - petType: - type: string - discriminator: - propertyName: petType - mapping: - dog: Dog - Cat: - allOf: - - $ref: '#/components/schemas/Pet' - - type: object - # all other properties specific to a `Cat` - properties: - name: - type: string - Dog: - allOf: - - $ref: '#/components/schemas/Pet' - - type: object - # all other properties specific to a `Dog` - properties: - bark: - type: string - Lizard: - allOf: - - $ref: '#/components/schemas/Pet' - - type: object - # all other properties specific to a `Lizard` - properties: - lovesRocks: - type: boolean -``` - -a payload like this: - -```json -{ - "petType": "Cat", - "name": "misty" -} -``` - -will indicate that the `Cat` schema be used. Likewise this schema: - -```json -{ - "petType": "dog", - "bark": "soft" -} -``` - -will map to `Dog` because of the definition in the `mapping` element. - - -#### XML Object - -A metadata object that allows for more fine-tuned XML model definitions. - -When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. -See examples for expected behavior. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -name | `string` | Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. -namespace | `string` | The URI of the namespace definition. This MUST be in the form of an absolute URI. -prefix | `string` | The prefix to be used for the [name](#xmlName). -attribute | `boolean` | Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. -wrapped | `boolean` | MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### XML Object Examples - -The examples of the XML object definitions are included inside a property definition of a [Schema Object](#schemaObject) with a sample of the XML representation of it. - -###### No XML Element - -Basic string property: - -```json -{ - "animals": { - "type": "string" - } -} -``` - -```yaml -animals: - type: string -``` - -```xml -... -``` - -Basic string array property ([`wrapped`](#xmlWrapped) is `false` by default): - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string" - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string -``` - -```xml -... -... -... -``` - -###### XML Name Replacement - -```json -{ - "animals": { - "type": "string", - "xml": { - "name": "animal" - } - } -} -``` - -```yaml -animals: - type: string - xml: - name: animal -``` - -```xml -... -``` - - -###### XML Attribute, Prefix and Namespace - -In this example, a full model definition is shown. - -```json -{ - "Person": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int32", - "xml": { - "attribute": true - } - }, - "name": { - "type": "string", - "xml": { - "namespace": "https://example.com/schema/sample", - "prefix": "sample" - } - } - } - } -} -``` - -```yaml -Person: - type: object - properties: - id: - type: integer - format: int32 - xml: - attribute: true - name: - type: string - xml: - namespace: https://example.com/schema/sample - prefix: sample -``` - -```xml - - example - -``` - -###### XML Arrays - -Changing the element names: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string", - "xml": { - "name": "animal" - } - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - name: animal -``` - -```xml -value -value -``` - -The external `name` property has no effect on the XML: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string", - "xml": { - "name": "animal" - } - }, - "xml": { - "name": "aliens" - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - name: animal - xml: - name: aliens -``` - -```xml -value -value -``` - -Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string" - }, - "xml": { - "wrapped": true - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - wrapped: true -``` - -```xml - - value - value - -``` - -To overcome the naming problem in the example above, the following definition can be used: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string", - "xml": { - "name": "animal" - } - }, - "xml": { - "wrapped": true - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - name: animal - xml: - wrapped: true -``` - -```xml - - value - value - -``` - -Affecting both internal and external names: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string", - "xml": { - "name": "animal" - } - }, - "xml": { - "name": "aliens", - "wrapped": true - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - name: animal - xml: - name: aliens - wrapped: true -``` - -```xml - - value - value - -``` - -If we change the external element but not the internal ones: - -```json -{ - "animals": { - "type": "array", - "items": { - "type": "string" - }, - "xml": { - "name": "aliens", - "wrapped": true - } - } -} -``` - -```yaml -animals: - type: array - items: - type: string - xml: - name: aliens - wrapped: true -``` - -```xml - - value - value - -``` - -#### Security Scheme Object - -Defines a security scheme that can be used by the operations. - -Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), mutual TLS (use of a client certificate), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749](https://tools.ietf.org/html/rfc6749), and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06). -Please note that as of 2020, the implicit flow is about to be deprecated by [OAuth 2.0 Security Best Current Practice](https://tools.ietf.org/html/draft-ietf-oauth-security-topics). Recommended for most use case is Authorization Code Grant flow with PKCE. - -##### Fixed Fields -Field Name | Type | Applies To | Description ----|:---:|---|--- -type | `string` | Any | **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"mutualTLS"`, `"oauth2"`, `"openIdConnect"`. -description | `string` | Any | A description for security scheme. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. -name | `string` | `apiKey` | **REQUIRED**. The name of the header, query or cookie parameter to be used. -in | `string` | `apiKey` | **REQUIRED**. The location of the API key. Valid values are `"query"`, `"header"` or `"cookie"`. -scheme | `string` | `http` | **REQUIRED**. The name of the HTTP Authorization scheme to be used in the [Authorization header as defined in RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1). The values used SHOULD be registered in the [IANA Authentication Scheme registry](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml). -bearerFormat | `string` | `http` (`"bearer"`) | A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. -flows | [OAuth Flows Object](#oauthFlowsObject) | `oauth2` | **REQUIRED**. An object containing configuration information for the flow types supported. -openIdConnectUrl | `string` | `openIdConnect` | **REQUIRED**. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL. The OpenID Connect standard requires the use of TLS. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### Security Scheme Object Example - -###### Basic Authentication Sample - -```json -{ - "type": "http", - "scheme": "basic" -} -``` - -```yaml -type: http -scheme: basic -``` - -###### API Key Sample - -```json -{ - "type": "apiKey", - "name": "api_key", - "in": "header" -} -``` - -```yaml -type: apiKey -name: api_key -in: header -``` - -###### JWT Bearer Sample - -```json -{ - "type": "http", - "scheme": "bearer", - "bearerFormat": "JWT", -} -``` - -```yaml -type: http -scheme: bearer -bearerFormat: JWT -``` - -###### Implicit OAuth2 Sample - -```json -{ - "type": "oauth2", - "flows": { - "implicit": { - "authorizationUrl": "https://example.com/api/oauth/dialog", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - } - } -} -``` - -```yaml -type: oauth2 -flows: - implicit: - authorizationUrl: https://example.com/api/oauth/dialog - scopes: - write:pets: modify pets in your account - read:pets: read your pets -``` - -#### OAuth Flows Object - -Allows configuration of the supported OAuth Flows. - -##### Fixed Fields -Field Name | Type | Description ----|:---:|--- -implicit| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Implicit flow -password| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Resource Owner Password flow -clientCredentials| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0. -authorizationCode| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -#### OAuth Flow Object - -Configuration details for a supported OAuth Flow - -##### Fixed Fields -Field Name | Type | Applies To | Description ----|:---:|---|--- -authorizationUrl | `string` | `oauth2` (`"implicit"`, `"authorizationCode"`) | **REQUIRED**. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. -tokenUrl | `string` | `oauth2` (`"password"`, `"clientCredentials"`, `"authorizationCode"`) | **REQUIRED**. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. -refreshUrl | `string` | `oauth2` | The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. -scopes | Map[`string`, `string`] | `oauth2` | **REQUIRED**. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty. - -This object MAY be extended with [Specification Extensions](#specificationExtensions). - -##### OAuth Flow Object Examples - -```JSON -{ - "type": "oauth2", - "flows": { - "implicit": { - "authorizationUrl": "https://example.com/api/oauth/dialog", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - }, - "authorizationCode": { - "authorizationUrl": "https://example.com/api/oauth/dialog", - "tokenUrl": "https://example.com/api/oauth/token", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - } - } -} -``` - -```yaml -type: oauth2 -flows: - implicit: - authorizationUrl: https://example.com/api/oauth/dialog - scopes: - write:pets: modify pets in your account - read:pets: read your pets - authorizationCode: - authorizationUrl: https://example.com/api/oauth/dialog - tokenUrl: https://example.com/api/oauth/token - scopes: - write:pets: modify pets in your account - read:pets: read your pets -``` - -#### Security Requirement Object - -Lists the required security schemes to execute this operation. -The name used for each property MUST correspond to a security scheme declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). - -Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. -This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. - -When a list of Security Requirement Objects is defined on the [OpenAPI Object](#oasObject) or [Operation Object](#operationObject), only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. - -##### Patterned Fields - -Field Pattern | Type | Description ----|:---:|--- -{name} | [`string`] | Each name MUST correspond to a security scheme which is declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). If the security scheme is of type `"oauth2"` or `"openIdConnect"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band. - -##### Security Requirement Object Examples - -###### Non-OAuth2 Security Requirement - -```json -{ - "api_key": [] -} -``` - -```yaml -api_key: [] -``` - -###### OAuth2 Security Requirement - -```json -{ - "petstore_auth": [ - "write:pets", - "read:pets" - ] -} -``` - -```yaml -petstore_auth: -- write:pets -- read:pets -``` - -###### Optional OAuth2 Security - -Optional OAuth2 security as would be defined in an OpenAPI Object or an Operation Object: - -```json -{ - "security": [ - {}, - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] -} -``` - -```yaml -security: - - {} - - petstore_auth: - - write:pets - - read:pets -``` - -### Specification Extensions - -While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points. - -The extensions properties are implemented as patterned fields that are always prefixed by `"x-"`. - -Field Pattern | Type | Description ----|:---:|--- -^x- | Any | Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. Field names beginning `x-oai-` and `x-oas-` are reserved for uses defined by the [OpenAPI Initiative](https://www.openapis.org/). The value can be `null`, a primitive, an array or an object. - -The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced). - -### Security Filtering - -Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation. - -The reasoning is to allow an additional layer of access control over the documentation. -While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization. - -Two examples of this: - -1. The [Paths Object](#pathsObject) MAY be present but empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They would still have access to at least the [Info Object](#infoObject) which may contain additional information regarding authentication. -2. The [Path Item Object](#pathItemObject) MAY be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different from hiding the path itself from the [Paths Object](#pathsObject), because the user will be aware of its existence. This allows the documentation provider to finely control what the viewer can see. - - -## Appendix A: Revision History - -Version | Date | Notes ---- | --- | --- -3.1.0 | 2021-02-15 | Release of the OpenAPI Specification 3.1.0 -3.1.0-rc1 | 2020-10-08 | rc1 of the 3.1 specification -3.1.0-rc0 | 2020-06-18 | rc0 of the 3.1 specification -3.0.3 | 2020-02-20 | Patch release of the OpenAPI Specification 3.0.3 -3.0.2 | 2018-10-08 | Patch release of the OpenAPI Specification 3.0.2 -3.0.1 | 2017-12-06 | Patch release of the OpenAPI Specification 3.0.1 -3.0.0 | 2017-07-26 | Release of the OpenAPI Specification 3.0.0 -3.0.0-rc2 | 2017-06-16 | rc2 of the 3.0 specification -3.0.0-rc1 | 2017-04-27 | rc1 of the 3.0 specification -3.0.0-rc0 | 2017-02-28 | Implementer's Draft of the 3.0 specification -2.0 | 2015-12-31 | Donation of Swagger 2.0 to the OpenAPI Initiative -2.0 | 2014-09-08 | Release of Swagger 2.0 -1.2 | 2014-03-14 | Initial release of the formal document. -1.1 | 2012-08-22 | Release of Swagger 1.1 -1.0 | 2011-08-10 | First release of the Swagger Specification diff --git a/chaotic-openapi/chaotic_openapi/front/schema/__init__.py b/chaotic-openapi/chaotic_openapi/front/schema/__init__.py deleted file mode 100644 index 21a90f5fb701..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -__all__ = [ - "DataType", - "MediaType", - "OpenAPI", - "Operation", - "Parameter", - "Parameter", - "ParameterLocation", - "PathItem", - "Reference", - "RequestBody", - "Response", - "Responses", - "Schema", -] - - -from .data_type import DataType -from .openapi_schema_pydantic import ( - MediaType, - OpenAPI, - Operation, - Parameter, - PathItem, - Reference, - RequestBody, - Response, - Responses, - Schema, -) -from .parameter_location import ParameterLocation diff --git a/chaotic-openapi/chaotic_openapi/front/schema/data_type.py b/chaotic-openapi/chaotic_openapi/front/schema/data_type.py deleted file mode 100644 index 1c104142e4f2..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/data_type.py +++ /dev/null @@ -1,18 +0,0 @@ -from enum import Enum - - -class DataType(str, Enum): - """The data type of a schema is defined by the type keyword - - References: - - https://swagger.io/docs/specification/data-models/data-types/ - - https://json-schema.org/draft/2020-12/json-schema-validation.html#name-type - """ - - STRING = "string" - NUMBER = "number" - INTEGER = "integer" - BOOLEAN = "boolean" - ARRAY = "array" - OBJECT = "object" - NULL = "null" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/LICENSE b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/LICENSE deleted file mode 100644 index 19166577b1a3..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Kuimono - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md deleted file mode 100644 index f58b369093dc..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Everything in this directory (including the rest of this file after this paragraph) is a vendored copy of [openapi-schem-pydantic](https://github.com/kuimono/openapi-schema-pydantic) and is licensed under the LICENSE file in this directory. - -Included vendored version is the [following](https://github.com/kuimono/openapi-schema-pydantic/commit/0836b429086917feeb973de3367a7ac4c2b3a665) -Small patches has been applied to it. - -## Alias - -Due to the reserved words in python and pydantic, -the following fields are used with [alias](https://pydantic-docs.helpmanual.io/usage/schema/#field-customisation) feature provided by pydantic: - -| Class | Field name in the class | Alias (as in OpenAPI spec) | -| ----- | ----------------------- | -------------------------- | -| Header[*](#header_param_in) | param_in | in | -| MediaType | media_type_schema | schema | -| Parameter | param_in | in | -| Parameter | param_schema | schema | -| PathItem | ref | $ref | -| Reference | ref | $ref | -| SecurityScheme | security_scheme_in | in | -| Schema | schema_format | format | -| Schema | schema_not | not | - -> The "in" field in Header object is actually a constant (`{"in": "header"}`). - -> For convenience of object creation, the classes mentioned in above -> has configured `allow_population_by_field_name=True`. -> -> Reference: [Pydantic's Model Config](https://pydantic-docs.helpmanual.io/usage/model_config/) - -## Non-pydantic schema types - -Due to the constriants of python typing structure (not able to handle dynamic field names), -the following schema classes are actually just a typing of `Dict`: - -| Schema Type | Implementation | -| ----------- | -------------- | -| Callback | `Callback = Dict[str, PathItem]` | -| Paths | `Paths = Dict[str, PathItem]` | -| Responses | `Responses = Dict[str, Union[Response, Reference]]` | -| SecurityRequirement | `SecurityRequirement = Dict[str, List[str]]` | - -On creating such schema instances, please use python's `dict` type instead to instantiate. diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/__init__.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/__init__.py deleted file mode 100644 index b61cefc66597..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/__init__.py +++ /dev/null @@ -1,83 +0,0 @@ -""" -OpenAPI v3.0.3 schema types, created according to the specification: -https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md - -The type orders are according to the contents of the specification: -https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#table-of-contents -""" - -__all__ = [ - "XML", - "Callback", - "Components", - "Contact", - "Discriminator", - "Encoding", - "Example", - "ExternalDocumentation", - "Header", - "Info", - "License", - "Link", - "MediaType", - "OAuthFlow", - "OAuthFlows", - "OpenAPI", - "Operation", - "Parameter", - "PathItem", - "Paths", - "Reference", - "RequestBody", - "Response", - "Responses", - "Schema", - "SecurityRequirement", - "SecurityScheme", - "Server", - "ServerVariable", - "Tag", -] - - -from .callback import Callback -from .components import Components -from .contact import Contact -from .discriminator import Discriminator -from .encoding import Encoding -from .example import Example -from .external_documentation import ExternalDocumentation -from .header import Header -from .info import Info -from .license import License -from .link import Link -from .media_type import MediaType -from .oauth_flow import OAuthFlow -from .oauth_flows import OAuthFlows -from .open_api import OpenAPI -from .operation import Operation -from .parameter import Parameter -from .path_item import PathItem -from .paths import Paths -from .reference import Reference -from .request_body import RequestBody -from .response import Response -from .responses import Responses -from .schema import Schema -from .security_requirement import SecurityRequirement -from .security_scheme import SecurityScheme -from .server import Server -from .server_variable import ServerVariable -from .tag import Tag -from .xml import XML - -PathItem.model_rebuild() -Operation.model_rebuild() -Components.model_rebuild() -Encoding.model_rebuild() -MediaType.model_rebuild() -OpenAPI.model_rebuild() -Parameter.model_rebuild() -Header.model_rebuild() -RequestBody.model_rebuild() -Response.model_rebuild() diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py deleted file mode 100644 index f4593cc8d9b2..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/callback.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: # pragma: no cover - from .path_item import PathItem -else: - PathItem = "PathItem" - -Callback = dict[str, PathItem] -""" -A map of possible out-of band callbacks related to the parent operation. -Each value in the map is a [Path Item Object](#pathItemObject) -that describes a set of requests that may be initiated by the API provider and the expected responses. -The key value used to identify the path item object is an expression, evaluated at runtime, -that identifies a URL to use for the callback operation. -""" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py deleted file mode 100644 index babe262657a5..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/components.py +++ /dev/null @@ -1,103 +0,0 @@ -from typing import Optional, Union - -from pydantic import BaseModel, ConfigDict - -from .callback import Callback -from .example import Example -from .header import Header -from .link import Link -from .parameter import Parameter -from .reference import Reference -from .request_body import RequestBody -from .response import Response -from .schema import Schema -from .security_scheme import SecurityScheme - - -class Components(BaseModel): - """ - Holds a set of reusable objects for different aspects of the OAS. - All objects defined within the components object will have no effect on the API - unless they are explicitly referenced from properties outside the components object. - - References: - - https://swagger.io/docs/specification/components/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#componentsObject - """ - - schemas: Optional[dict[str, Union[Schema, Reference]]] = None - responses: Optional[dict[str, Union[Response, Reference]]] = None - parameters: Optional[dict[str, Union[Parameter, Reference]]] = None - examples: Optional[dict[str, Union[Example, Reference]]] = None - requestBodies: Optional[dict[str, Union[RequestBody, Reference]]] = None - headers: Optional[dict[str, Union[Header, Reference]]] = None - securitySchemes: Optional[dict[str, Union[SecurityScheme, Reference]]] = None - links: Optional[dict[str, Union[Link, Reference]]] = None - callbacks: Optional[dict[str, Union[Callback, Reference]]] = None - model_config = ConfigDict( - # `Callback` contains an unresolvable forward reference, will rebuild in `__init__.py`: - defer_build=True, - extra="allow", - json_schema_extra={ - "examples": [ - { - "schemas": { - "GeneralError": { - "type": "object", - "properties": { - "code": {"type": "integer", "format": "int32"}, - "message": {"type": "string"}, - }, - }, - "Category": { - "type": "object", - "properties": {"id": {"type": "integer", "format": "int64"}, "name": {"type": "string"}}, - }, - "Tag": { - "type": "object", - "properties": {"id": {"type": "integer", "format": "int64"}, "name": {"type": "string"}}, - }, - }, - "parameters": { - "skipParam": { - "name": "skip", - "in": "query", - "description": "number of items to skip", - "required": True, - "schema": {"type": "integer", "format": "int32"}, - }, - "limitParam": { - "name": "limit", - "in": "query", - "description": "max records to return", - "required": True, - "schema": {"type": "integer", "format": "int32"}, - }, - }, - "responses": { - "NotFound": {"description": "Entity not found."}, - "IllegalInput": {"description": "Illegal input for operation."}, - "GeneralError": { - "description": "General Error", - "content": {"application/json": {"schema": {"$ref": "#/components/schemas/GeneralError"}}}, - }, - }, - "securitySchemes": { - "api_key": {"type": "apiKey", "name": "api_key", "in": "header"}, - "petstore_auth": { - "type": "oauth2", - "flows": { - "implicit": { - "authorizationUrl": "http://example.org/api/oauth/dialog", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets", - }, - } - }, - }, - }, - } - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/contact.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/contact.py deleted file mode 100644 index c04fdbbe0201..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/contact.py +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - - -class Contact(BaseModel): - """ - Contact information for the exposed API. - - See Also: - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#contactObject - """ - - name: Optional[str] = None - url: Optional[str] = None - email: Optional[str] = None - model_config = ConfigDict( - extra="allow", - json_schema_extra={ - "examples": [ - {"name": "API Support", "url": "http://www.example.com/support", "email": "support@example.com"} - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py deleted file mode 100644 index 9f36773ba435..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/discriminator.py +++ /dev/null @@ -1,36 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - - -class Discriminator(BaseModel): - """ - When request bodies or response payloads may be one of a number of different schemas, - a `discriminator` object can be used to aid in serialization, deserialization, and validation. - - The discriminator is a specific object in a schema which is used to inform the consumer of the specification - of an alternative schema based on the value associated with it. - - When using the discriminator, _inline_ schemas will not be considered. - - References: - - https://swagger.io/docs/specification/data-models/inheritance-and-polymorphism/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#discriminatorObject - """ - - propertyName: str - mapping: Optional[dict[str, str]] = None - model_config = ConfigDict( - extra="allow", - json_schema_extra={ - "examples": [ - { - "propertyName": "petType", - "mapping": { - "dog": "#/components/schemas/Dog", - "monster": "https://gigantic-server.com/schemas/Monster/schema.json", - }, - } - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py deleted file mode 100644 index ebf6295dc56a..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/encoding.py +++ /dev/null @@ -1,41 +0,0 @@ -from typing import TYPE_CHECKING, Optional, Union - -from pydantic import BaseModel, ConfigDict - -from .reference import Reference - -if TYPE_CHECKING: # pragma: no cover - from .header import Header - - -class Encoding(BaseModel): - """A single encoding definition applied to a single schema property. - - References: - - https://swagger.io/docs/specification/describing-request-body/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#encodingObject - """ - - contentType: Optional[str] = None - headers: Optional[dict[str, Union["Header", Reference]]] = None - style: Optional[str] = None - explode: bool = False - allowReserved: bool = False - model_config = ConfigDict( - # `Header` is an unresolvable forward reference, will rebuild in `__init__.py`: - defer_build=True, - extra="allow", - json_schema_extra={ - "examples": [ - { - "contentType": "image/png, image/jpeg", - "headers": { - "X-Rate-Limit-Limit": { - "description": "The number of allowed requests in the current period", - "schema": {"type": "integer"}, - } - }, - } - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/example.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/example.py deleted file mode 100644 index 90db2530e0b4..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/example.py +++ /dev/null @@ -1,30 +0,0 @@ -from typing import Any, Optional - -from pydantic import BaseModel, ConfigDict - - -class Example(BaseModel): - """Examples added to parameters / components to help clarify usage. - - References: - - https://swagger.io/docs/specification/adding-examples/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#exampleObject - """ - - summary: Optional[str] = None - description: Optional[str] = None - value: Optional[Any] = None - externalValue: Optional[str] = None - model_config = ConfigDict( - extra="allow", - json_schema_extra={ - "examples": [ - {"summary": "A foo example", "value": {"foo": "bar"}}, - { - "summary": "This is an example in XML", - "externalValue": "http://example.org/examples/address-example.xml", - }, - {"summary": "This is a text example", "externalValue": "http://foo.bar/examples/address-example.txt"}, - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/external_documentation.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/external_documentation.py deleted file mode 100644 index 2c0c39b7cf6f..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/external_documentation.py +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - - -class ExternalDocumentation(BaseModel): - """Allows referencing an external resource for extended documentation. - - References: - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#externalDocumentationObject - """ - - description: Optional[str] = None - url: str - model_config = ConfigDict( - extra="allow", - json_schema_extra={"examples": [{"description": "Find more info here", "url": "https://example.com"}]}, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/header.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/header.py deleted file mode 100644 index 2deb6f3908f1..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/header.py +++ /dev/null @@ -1,33 +0,0 @@ -from pydantic import ConfigDict, Field - -from ..parameter_location import ParameterLocation -from .parameter import Parameter - - -class Header(Parameter): - """ - The Header Object follows the structure of the [Parameter Object](#parameterObject) with the following changes: - - 1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. - 2. `in` MUST NOT be specified, it is implicitly in `header`. - 3. All traits that are affected by the location MUST be applicable to a location of `header` - (for example, [`style`](#parameterStyle)). - - References: - - https://swagger.io/docs/specification/describing-parameters/#header-parameters - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#headerObject - """ - - name: str = Field(default="") - param_in: ParameterLocation = Field(default=ParameterLocation.HEADER, alias="in") - model_config = ConfigDict( - # `Parameter` is not build yet, will rebuild in `__init__.py`: - defer_build=True, - extra="allow", - populate_by_name=True, - json_schema_extra={ - "examples": [ - {"description": "The number of allowed requests in the current period", "schema": {"type": "integer"}} - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/info.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/info.py deleted file mode 100644 index bec1354da663..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/info.py +++ /dev/null @@ -1,44 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - -from .contact import Contact -from .license import License - - -class Info(BaseModel): - """ - The object provides metadata about the API. - The metadata MAY be used by the clients if needed, - and MAY be presented in editing or documentation generation tools for convenience. - - References: - - https://swagger.io/docs/specification/api-general-info/ - -https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#infoObject - """ - - title: str - description: Optional[str] = None - termsOfService: Optional[str] = None - contact: Optional[Contact] = None - license: Optional[License] = None - version: str - model_config = ConfigDict( - extra="allow", - json_schema_extra={ - "examples": [ - { - "title": "Sample Pet Store App", - "description": "This is a sample server for a pet store.", - "termsOfService": "http://example.com/terms/", - "contact": { - "name": "API Support", - "url": "http://www.example.com/support", - "email": "support@example.com", - }, - "license": {"name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html"}, - "version": "1.0.1", - } - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/license.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/license.py deleted file mode 100644 index 185eec1dbf39..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/license.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - - -class License(BaseModel): - """ - License information for the exposed API. - - References: - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#licenseObject - """ - - name: str - url: Optional[str] = None - model_config = ConfigDict( - extra="allow", - json_schema_extra={ - "examples": [{"name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html"}] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py deleted file mode 100644 index 69cdf29c09dc..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/link.py +++ /dev/null @@ -1,43 +0,0 @@ -from typing import Any, Optional - -from pydantic import BaseModel, ConfigDict - -from .server import Server - - -class Link(BaseModel): - """ - The `Link object` represents a possible design-time link for a response. - The presence of a link does not guarantee the caller's ability to successfully invoke it, - rather it provides a known relationship and traversal mechanism between responses and other operations. - - Unlike _dynamic_ links (i.e. links provided **in** the response payload), - the OAS linking mechanism does not require link information in the runtime response. - - For computing links, and providing instructions to execute them, - a [runtime expression](#runtimeExpression) is used for accessing values in an operation - and using them as parameters while invoking the linked operation. - - References: - - https://swagger.io/docs/specification/links/ - - https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#linkObject - """ - - operationRef: Optional[str] = None - operationId: Optional[str] = None - parameters: Optional[dict[str, Any]] = None - requestBody: Optional[Any] = None - description: Optional[str] = None - server: Optional[Server] = None - model_config = ConfigDict( - extra="allow", - json_schema_extra={ - "examples": [ - {"operationId": "getUserAddressByUUID", "parameters": {"userUuid": "$response.body#/uuid"}}, - { - "operationRef": "#/paths/~12.0~1repositories~1{username}/get", - "parameters": {"username": "$response.body#/username"}, - }, - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py deleted file mode 100644 index 95f9ede147c9..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/media_type.py +++ /dev/null @@ -1,57 +0,0 @@ -from typing import Any, Optional, Union - -from pydantic import BaseModel, ConfigDict, Field - -from .encoding import Encoding -from .example import Example -from .reference import Reference -from .schema import Schema - - -class MediaType(BaseModel): - """Each Media Type Object provides schema and examples for the media type identified by its key. - - References: - - https://swagger.io/docs/specification/media-types/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#mediaTypeObject - """ - - media_type_schema: Optional[Union[Reference, Schema]] = Field(default=None, alias="schema") - example: Optional[Any] = None - examples: Optional[dict[str, Union[Example, Reference]]] = None - encoding: Optional[dict[str, Encoding]] = None - model_config = ConfigDict( - # `Encoding` is not build yet, will rebuild in `__init__.py`: - defer_build=True, - extra="allow", - populate_by_name=True, - json_schema_extra={ - "examples": [ - { - "schema": {"$ref": "#/components/schemas/Pet"}, - "examples": { - "cat": { - "summary": "An example of a cat", - "value": { - "name": "Fluffy", - "petType": "Cat", - "color": "White", - "gender": "male", - "breed": "Persian", - }, - }, - "dog": { - "summary": "An example of a dog with a cat's name", - "value": { - "name": "Puma", - "petType": "Dog", - "color": "Black", - "gender": "Female", - "breed": "Mixed", - }, - }, - }, - } - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py deleted file mode 100644 index 16e3660901b7..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flow.py +++ /dev/null @@ -1,34 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - - -class OAuthFlow(BaseModel): - """ - Configuration details for a supported OAuth Flow - - References: - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oauthFlowObject - - https://swagger.io/docs/specification/authentication/oauth2/ - """ - - authorizationUrl: Optional[str] = None - tokenUrl: Optional[str] = None - refreshUrl: Optional[str] = None - scopes: dict[str, str] - model_config = ConfigDict( - extra="allow", - json_schema_extra={ - "examples": [ - { - "authorizationUrl": "https://example.com/api/oauth/dialog", - "scopes": {"write:pets": "modify pets in your account", "read:pets": "read your pets"}, - }, - { - "authorizationUrl": "https://example.com/api/oauth/dialog", - "tokenUrl": "https://example.com/api/oauth/token", - "scopes": {"write:pets": "modify pets in your account", "read:pets": "read your pets"}, - }, - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flows.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flows.py deleted file mode 100644 index dba193713699..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/oauth_flows.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - -from .oauth_flow import OAuthFlow - - -class OAuthFlows(BaseModel): - """ - Allows configuration of the supported OAuth Flows. - - References: - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oauthFlowsObject - - https://swagger.io/docs/specification/authentication/oauth2/ - """ - - implicit: Optional[OAuthFlow] = None - password: Optional[OAuthFlow] = None - clientCredentials: Optional[OAuthFlow] = None - authorizationCode: Optional[OAuthFlow] = None - model_config = ConfigDict(extra="allow") diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py deleted file mode 100644 index e66ea942ccfb..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/open_api.py +++ /dev/null @@ -1,49 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict, field_validator - -from .components import Components -from .external_documentation import ExternalDocumentation -from .info import Info -from .paths import Paths -from .security_requirement import SecurityRequirement -from .server import Server -from .tag import Tag - -NUM_SEMVER_PARTS = 3 - - -class OpenAPI(BaseModel): - """This is the root document object of the OpenAPI document. - - References: - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oasObject - - https://swagger.io/docs/specification/basic-structure/ - """ - - info: Info - servers: list[Server] = [Server(url="/")] - paths: Paths - components: Optional[Components] = None - security: Optional[list[SecurityRequirement]] = None - tags: Optional[list[Tag]] = None - externalDocs: Optional[ExternalDocumentation] = None - openapi: str - model_config = ConfigDict( - # `Components` is not build yet, will rebuild in `__init__.py`: - defer_build=True, - extra="allow", - ) - - @field_validator("openapi") - @classmethod - def check_openapi_version(cls, value: str) -> str: - """Validates that the declared OpenAPI version is a supported one""" - parts = value.split(".") - if len(parts) != NUM_SEMVER_PARTS: - raise ValueError(f"Invalid OpenAPI version {value}") - if parts[0] != "3": - raise ValueError(f"Only OpenAPI versions 3.* are supported, got {value}") - if int(parts[1]) > 1: - raise ValueError(f"Only OpenAPI versions 3.1.* are supported, got {value}") - return value diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py deleted file mode 100644 index ebf5e1faa10c..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/operation.py +++ /dev/null @@ -1,89 +0,0 @@ -from typing import Optional, Union - -from pydantic import BaseModel, ConfigDict, Field - -from .callback import Callback -from .external_documentation import ExternalDocumentation -from .parameter import Parameter -from .reference import Reference -from .request_body import RequestBody -from .responses import Responses -from .security_requirement import SecurityRequirement -from .server import Server - - -class Operation(BaseModel): - """Describes a single API operation on a path. - - References: - - https://swagger.io/docs/specification/paths-and-operations/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operationObject - """ - - tags: Optional[list[str]] = None - summary: Optional[str] = None - description: Optional[str] = None - externalDocs: Optional[ExternalDocumentation] = None - operationId: Optional[str] = None - parameters: Optional[list[Union[Parameter, Reference]]] = None - request_body: Optional[Union[RequestBody, Reference]] = Field(None, alias="requestBody") - responses: Responses - callbacks: Optional[dict[str, Callback]] = None - - deprecated: bool = False - security: Optional[list[SecurityRequirement]] = None - servers: Optional[list[Server]] = None - model_config = ConfigDict( - # `Callback` contains an unresolvable forward reference, will rebuild in `__init__.py`: - defer_build=True, - extra="allow", - json_schema_extra={ - "examples": [ - { - "tags": ["pet"], - "summary": "Updates a pet in the store with form data", - "operationId": "updatePetWithForm", - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be updated", - "required": True, - "schema": {"type": "string"}, - } - ], - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "type": "object", - "properties": { - "name": { - "description": "Updated name of the pet", - "type": "string", - }, - "status": { - "description": "Updated status of the pet", - "type": "string", - }, - }, - "required": ["status"], - } - } - } - }, - "responses": { - "200": { - "description": "Pet updated.", - "content": {"application/json": {}, "application/xml": {}}, - }, - "405": { - "description": "Method Not Allowed", - "content": {"application/json": {}, "application/xml": {}}, - }, - }, - "security": [{"petstore_auth": ["write:pets", "read:pets"]}], - } - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py deleted file mode 100644 index 6f6fe9342001..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/parameter.py +++ /dev/null @@ -1,89 +0,0 @@ -from typing import Any, Optional, Union - -from pydantic import BaseModel, ConfigDict, Field - -from ..parameter_location import ParameterLocation -from .example import Example -from .media_type import MediaType -from .reference import Reference -from .schema import Schema - - -class Parameter(BaseModel): - """ - Describes a single operation parameter. - - A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). - - References: - - https://swagger.io/docs/specification/describing-parameters/ - - https://swagger.io/docs/specification/serialization/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameterObject - """ - - name: str - param_in: ParameterLocation = Field(alias="in") - description: Optional[str] = None - required: bool = False - deprecated: bool = False - allowEmptyValue: bool = False - style: Optional[str] = None - explode: bool = False - allowReserved: bool = False - param_schema: Optional[Union[Reference, Schema]] = Field(default=None, alias="schema") - example: Optional[Any] = None - examples: Optional[dict[str, Union[Example, Reference]]] = None - content: Optional[dict[str, MediaType]] = None - model_config = ConfigDict( - # `MediaType` is not build yet, will rebuild in `__init__.py`: - defer_build=True, - extra="allow", - populate_by_name=True, - json_schema_extra={ - "examples": [ - { - "name": "token", - "in": "header", - "description": "token to be passed as a header", - "required": True, - "schema": {"type": "array", "items": {"type": "integer", "format": "int64"}}, - "style": "simple", - }, - { - "name": "username", - "in": "path", - "description": "username to fetch", - "required": True, - "schema": {"type": "string"}, - }, - { - "name": "id", - "in": "query", - "description": "ID of the object to fetch", - "required": False, - "schema": {"type": "array", "items": {"type": "string"}}, - "style": "form", - "explode": True, - }, - { - "in": "query", - "name": "freeForm", - "schema": {"type": "object", "additionalProperties": {"type": "integer"}}, - "style": "form", - }, - { - "in": "query", - "name": "coordinates", - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["lat", "long"], - "properties": {"lat": {"type": "number"}, "long": {"type": "number"}}, - } - } - }, - }, - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py deleted file mode 100644 index 8c1eab6ea75d..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/path_item.py +++ /dev/null @@ -1,76 +0,0 @@ -from typing import TYPE_CHECKING, Optional, Union - -from pydantic import BaseModel, ConfigDict, Field - -from .parameter import Parameter -from .reference import Reference -from .server import Server - -if TYPE_CHECKING: - from .operation import Operation # pragma: no cover - - -class PathItem(BaseModel): - """ - Describes the operations available on a single path. - A Path Item MAY be empty, due to [ACL constraints](#securityFiltering). - The path itself is still exposed to the documentation viewer - but they will not know which operations and parameters are available. - - References: - - https://swagger.io/docs/specification/paths-and-operations/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#pathItemObject - """ - - ref: Optional[str] = Field(default=None, alias="$ref") - summary: Optional[str] = None - description: Optional[str] = None - get: Optional["Operation"] = None - put: Optional["Operation"] = None - post: Optional["Operation"] = None - delete: Optional["Operation"] = None - options: Optional["Operation"] = None - head: Optional["Operation"] = None - patch: Optional["Operation"] = None - trace: Optional["Operation"] = None - servers: Optional[list[Server]] = None - parameters: Optional[list[Union[Parameter, Reference]]] = None - model_config = ConfigDict( - # `Operation` is an unresolvable forward reference, will rebuild in `__init__.py`: - defer_build=True, - extra="allow", - populate_by_name=True, - json_schema_extra={ - "examples": [ - { - "get": { - "description": "Returns pets based on ID", - "summary": "Find pets by ID", - "operationId": "getPetsById", - "responses": { - "200": { - "description": "pet response", - "content": { - "*/*": {"schema": {"type": "array", "items": {"$ref": "#/components/schemas/Pet"}}} - }, - }, - "default": { - "description": "error payload", - "content": {"text/html": {"schema": {"$ref": "#/components/schemas/ErrorModel"}}}, - }, - }, - }, - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to use", - "required": True, - "schema": {"type": "array", "items": {"type": "string"}}, - "style": "simple", - } - ], - } - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py deleted file mode 100644 index 86c1dfd19d3c..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/paths.py +++ /dev/null @@ -1,13 +0,0 @@ -from .path_item import PathItem - -Paths = dict[str, PathItem] -""" -Holds the relative paths to the individual endpoints and their operations. -The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. - -The Paths MAY be empty, due to [ACL constraints](#securityFiltering). - -References: - - https://swagger.io/docs/specification/paths-and-operations/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#pathsObject -""" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/reference.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/reference.py deleted file mode 100644 index 50d26064f88c..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/reference.py +++ /dev/null @@ -1,26 +0,0 @@ -from pydantic import BaseModel, ConfigDict, Field - - -class Reference(BaseModel): - """ - A simple object to allow referencing other components in the specification, internally and externally. - - The Reference Object is defined by [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) - and follows the same structure, behavior and rules. - - For this specification, reference resolution is accomplished as defined by the JSON Reference specification - and not by the JSON Schema specification. - - References: - - https://swagger.io/docs/specification/using-ref/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#referenceObject - """ - - ref: str = Field(alias="$ref") - model_config = ConfigDict( - extra="allow", - populate_by_name=True, - json_schema_extra={ - "examples": [{"$ref": "#/components/schemas/Pet"}, {"$ref": "Pet.json"}, {"$ref": "definitions.json#/Pet"}] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py deleted file mode 100644 index 8cd9bb52744f..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/request_body.py +++ /dev/null @@ -1,70 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - -from .media_type import MediaType - - -class RequestBody(BaseModel): - """Describes a single request body. - - References: - - https://swagger.io/docs/specification/describing-request-body/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#requestBodyObject - """ - - description: Optional[str] = None - content: dict[str, MediaType] - required: bool = False - model_config = ConfigDict( - # `MediaType` is not build yet, will rebuild in `__init__.py`: - defer_build=True, - extra="allow", - json_schema_extra={ - "examples": [ - { - "description": "user to add to the system", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"}, - "examples": { - "user": { - "summary": "User Example", - "externalValue": "http://foo.bar/examples/user-example.json", - } - }, - }, - "application/xml": { - "schema": {"$ref": "#/components/schemas/User"}, - "examples": { - "user": { - "summary": "User example in XML", - "externalValue": "http://foo.bar/examples/user-example.xml", - } - }, - }, - "text/plain": { - "examples": { - "user": { - "summary": "User example in Plain text", - "externalValue": "http://foo.bar/examples/user-example.txt", - } - } - }, - "*/*": { - "examples": { - "user": { - "summary": "User example in other format", - "externalValue": "http://foo.bar/examples/user-example.whatever", - } - } - }, - }, - }, - { - "description": "user to add to the system", - "content": {"text/plain": {"schema": {"type": "array", "items": {"type": "string"}}}}, - }, - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py deleted file mode 100644 index b7ec0d3579ec..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/response.py +++ /dev/null @@ -1,61 +0,0 @@ -from typing import Optional, Union - -from pydantic import BaseModel, ConfigDict - -from .header import Header -from .link import Link -from .media_type import MediaType -from .reference import Reference - - -class Response(BaseModel): - """ - Describes a single response from an API Operation, including design-time, - static `links` to operations based on the response. - - References: - - https://swagger.io/docs/specification/describing-responses/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#responseObject - """ - - description: str - headers: Optional[dict[str, Union[Header, Reference]]] = None - content: Optional[dict[str, MediaType]] = None - links: Optional[dict[str, Union[Link, Reference]]] = None - model_config = ConfigDict( - # `MediaType` is not build yet, will rebuild in `__init__.py`: - defer_build=True, - extra="allow", - json_schema_extra={ - "examples": [ - { - "description": "A complex object array response", - "content": { - "application/json": { - "schema": {"type": "array", "items": {"$ref": "#/components/schemas/VeryComplexType"}} - } - }, - }, - {"description": "A simple string response", "content": {"text/plain": {"schema": {"type": "string"}}}}, - { - "description": "A simple string response", - "content": {"text/plain": {"schema": {"type": "string", "example": "whoa!"}}}, - "headers": { - "X-Rate-Limit-Limit": { - "description": "The number of allowed requests in the current period", - "schema": {"type": "integer"}, - }, - "X-Rate-Limit-Remaining": { - "description": "The number of remaining requests in the current period", - "schema": {"type": "integer"}, - }, - "X-Rate-Limit-Reset": { - "description": "The number of seconds left in the current period", - "schema": {"type": "integer"}, - }, - }, - }, - {"description": "object created"}, - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py deleted file mode 100644 index 17ddc13fedaf..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/responses.py +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Union - -from .reference import Reference -from .response import Response - -Responses = dict[str, Union[Response, Reference]] -""" -A container for the expected responses of an operation. -The container maps a HTTP response code to the expected response. - -The documentation is not necessarily expected to cover all possible HTTP response codes -because they may not be known in advance. -However, documentation is expected to cover a successful operation response and any known errors. - -The `default` MAY be used as a default response object for all HTTP codes -that are not covered individually by the specification. - -The `Responses Object` MUST contain at least one response code, and it -SHOULD be the response for a successful operation call. - -References: - - https://swagger.io/docs/specification/describing-responses/ -""" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py deleted file mode 100644 index 99c64eb51120..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/schema.py +++ /dev/null @@ -1,208 +0,0 @@ -from typing import Any, Optional, Union - -from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr, model_validator - -from ..data_type import DataType -from .discriminator import Discriminator -from .external_documentation import ExternalDocumentation -from .reference import Reference -from .xml import XML - - -class Schema(BaseModel): - """ - The Schema Object allows the definition of input and output data types. - These types can be objects, but also primitives and arrays. - This object is an extended subset of the [JSON Schema Specification Wright Draft 00](https://json-schema.org/). - - References: - - https://swagger.io/docs/specification/data-models/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schemaObject - """ - - title: Optional[str] = None - multipleOf: Optional[float] = Field(default=None, gt=0.0) - maximum: Optional[float] = None - exclusiveMaximum: Optional[Union[bool, float]] = None - minimum: Optional[float] = None - exclusiveMinimum: Optional[Union[bool, float]] = None - maxLength: Optional[int] = Field(default=None, ge=0) - minLength: Optional[int] = Field(default=None, ge=0) - pattern: Optional[str] = None - maxItems: Optional[int] = Field(default=None, ge=0) - minItems: Optional[int] = Field(default=None, ge=0) - uniqueItems: Optional[bool] = None - maxProperties: Optional[int] = Field(default=None, ge=0) - minProperties: Optional[int] = Field(default=None, ge=0) - required: Optional[list[str]] = Field(default=None) - enum: Union[None, list[Any]] = Field(default=None, min_length=1) - const: Union[None, StrictStr, StrictInt, StrictFloat, StrictBool] = None - type: Union[DataType, list[DataType], None] = Field(default=None) - allOf: list[Union[Reference, "Schema"]] = Field(default_factory=list) - oneOf: list[Union[Reference, "Schema"]] = Field(default_factory=list) - anyOf: list[Union[Reference, "Schema"]] = Field(default_factory=list) - schema_not: Optional[Union[Reference, "Schema"]] = Field(default=None, alias="not") - items: Optional[Union[Reference, "Schema"]] = None - prefixItems: list[Union[Reference, "Schema"]] = Field(default_factory=list) - properties: Optional[dict[str, Union[Reference, "Schema"]]] = None - additionalProperties: Optional[Union[bool, Reference, "Schema"]] = None - description: Optional[str] = None - schema_format: Optional[str] = Field(default=None, alias="format") - default: Optional[Any] = None - nullable: bool = Field(default=False) - discriminator: Optional[Discriminator] = None - readOnly: Optional[bool] = None - writeOnly: Optional[bool] = None - xml: Optional[XML] = None - externalDocs: Optional[ExternalDocumentation] = None - example: Optional[Any] = None - deprecated: Optional[bool] = None - model_config = ConfigDict( - extra="allow", - populate_by_name=True, - json_schema_extra={ - "examples": [ - {"type": "string", "format": "email"}, - { - "type": "object", - "required": ["name"], - "properties": { - "name": {"type": "string"}, - "address": {"$ref": "#/components/schemas/Address"}, - "age": {"type": "integer", "format": "int32", "minimum": 0}, - }, - }, - {"type": "object", "additionalProperties": {"type": "string"}}, - { - "type": "object", - "additionalProperties": {"$ref": "#/components/schemas/ComplexModel"}, - }, - { - "type": "object", - "properties": { - "id": {"type": "integer", "format": "int64"}, - "name": {"type": "string"}, - }, - "required": ["name"], - "example": {"name": "Puma", "id": 1}, - }, - { - "type": "object", - "required": ["message", "code"], - "properties": { - "message": {"type": "string"}, - "code": {"type": "integer", "minimum": 100, "maximum": 600}, - }, - }, - { - "allOf": [ - {"$ref": "#/components/schemas/ErrorModel"}, - { - "type": "object", - "required": ["rootCause"], - "properties": {"rootCause": {"type": "string"}}, - }, - ] - }, - { - "type": "object", - "discriminator": {"propertyName": "petType"}, - "properties": { - "name": {"type": "string"}, - "petType": {"type": "string"}, - }, - "required": ["name", "petType"], - }, - { - "description": "A representation of a cat. " - "Note that `Cat` will be used as the discriminator value.", - "allOf": [ - {"$ref": "#/components/schemas/Pet"}, - { - "type": "object", - "properties": { - "huntingSkill": { - "type": "string", - "description": "The measured skill for hunting", - "default": "lazy", - "enum": [ - "clueless", - "lazy", - "adventurous", - "aggressive", - ], - } - }, - "required": ["huntingSkill"], - }, - ], - }, - { - "description": "A representation of a dog. " - "Note that `Dog` will be used as the discriminator value.", - "allOf": [ - {"$ref": "#/components/schemas/Pet"}, - { - "type": "object", - "properties": { - "packSize": { - "type": "integer", - "format": "int32", - "description": "the size of the pack the dog is from", - "default": 0, - "minimum": 0, - } - }, - "required": ["packSize"], - }, - ], - }, - ] - }, - ) - - @model_validator(mode="after") - def handle_exclusive_min_max(self) -> "Schema": - """ - Convert exclusiveMinimum/exclusiveMaximum between OpenAPI v3.0 (bool) and v3.1 (numeric). - """ - # Handle exclusiveMinimum - if isinstance(self.exclusiveMinimum, bool) and self.minimum is not None: - if self.exclusiveMinimum: - self.exclusiveMinimum = self.minimum - self.minimum = None - else: - self.exclusiveMinimum = None - elif isinstance(self.exclusiveMinimum, float): - self.minimum = None - - # Handle exclusiveMaximum - if isinstance(self.exclusiveMaximum, bool) and self.maximum is not None: - if self.exclusiveMaximum: - self.exclusiveMaximum = self.maximum - self.maximum = None - else: - self.exclusiveMaximum = None - elif isinstance(self.exclusiveMaximum, float): - self.maximum = None - - return self - - @model_validator(mode="after") - def handle_nullable(self) -> "Schema": - """Convert the old 3.0 `nullable` property into the new 3.1 style""" - if not self.nullable: - return self - if isinstance(self.type, str): - self.type = [self.type, DataType.NULL] - elif isinstance(self.type, list): - if DataType.NULL not in self.type: - self.type.append(DataType.NULL) - elif len(self.oneOf) > 0: - self.oneOf.append(Schema(type=DataType.NULL)) - elif len(self.anyOf) > 0: - self.anyOf.append(Schema(type=DataType.NULL)) - elif len(self.allOf) > 0: # Nullable allOf is basically oneOf[null, allOf] - self.oneOf = [Schema(type=DataType.NULL), Schema(allOf=self.allOf)] - self.allOf = [] - return self diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py deleted file mode 100644 index 58a487dc7acb..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_requirement.py +++ /dev/null @@ -1,18 +0,0 @@ -SecurityRequirement = dict[str, list[str]] -""" -Lists the required security schemes to execute this operation. -The name used for each property MUST correspond to a security scheme declared in the -[Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). - -Security Requirement Objects that contain multiple schemes require that -all schemes MUST be satisfied for a request to be authorized. -This enables support for scenarios where multiple query parameters or HTTP headers -are required to convey security information. - -When a list of Security Requirement Objects is defined on the -[OpenAPI Object](#oasObject) or [Operation Object](#operationObject), -only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. - -References: - - https://swagger.io/docs/specification/authentication/ -""" diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_scheme.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_scheme.py deleted file mode 100644 index df385440c6ea..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/security_scheme.py +++ /dev/null @@ -1,49 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict, Field - -from .oauth_flows import OAuthFlows - - -class SecurityScheme(BaseModel): - """ - Defines a security scheme that can be used by the operations. - Supported schemes are HTTP authentication, - an API key (either as a header, a cookie parameter or as a query parameter), - OAuth2's common flows (implicit, password, client credentials and authorization code) - as defined in [RFC6749](https://tools.ietf.org/html/rfc6749), - and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06). - - References: - - https://swagger.io/docs/specification/authentication/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#componentsObject - """ - - type: str - description: Optional[str] = None - name: Optional[str] = None - security_scheme_in: Optional[str] = Field(default=None, alias="in") - scheme: Optional[str] = None - bearerFormat: Optional[str] = None - flows: Optional[OAuthFlows] = None - openIdConnectUrl: Optional[str] = None - model_config = ConfigDict( - extra="allow", - populate_by_name=True, - json_schema_extra={ - "examples": [ - {"type": "http", "scheme": "basic"}, - {"type": "apiKey", "name": "api_key", "in": "header"}, - {"type": "http", "scheme": "bearer", "bearerFormat": "JWT"}, - { - "type": "oauth2", - "flows": { - "implicit": { - "authorizationUrl": "https://example.com/api/oauth/dialog", - "scopes": {"write:pets": "modify pets in your account", "read:pets": "read your pets"}, - } - }, - }, - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py deleted file mode 100644 index 6bc21766cd69..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server.py +++ /dev/null @@ -1,39 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - -from .server_variable import ServerVariable - - -class Server(BaseModel): - """An object representing a Server. - - References: - - https://swagger.io/docs/specification/api-host-and-base-path/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#serverObject - """ - - url: str - description: Optional[str] = None - variables: Optional[dict[str, ServerVariable]] = None - model_config = ConfigDict( - extra="allow", - json_schema_extra={ - "examples": [ - {"url": "https://development.gigantic-server.com/v1", "description": "Development server"}, - { - "url": "https://{username}.gigantic-server.com:{port}/{basePath}", - "description": "The production API server", - "variables": { - "username": { - "default": "demo", - "description": "this value is assigned by the service provider, " - "in this example `gigantic-server.com`", - }, - "port": {"enum": ["8443", "443"], "default": "8443"}, - "basePath": {"default": "v2"}, - }, - }, - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py deleted file mode 100644 index 8a869c40ebcb..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/server_variable.py +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - - -class ServerVariable(BaseModel): - """An object representing a Server Variable for server URL template substitution. - - References: - - https://swagger.io/docs/specification/api-host-and-base-path/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#serverVariableObject - """ - - enum: Optional[list[str]] = None - default: str - description: Optional[str] = None - model_config = ConfigDict(extra="allow") diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/tag.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/tag.py deleted file mode 100644 index acb5fdc288df..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/tag.py +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - -from .external_documentation import ExternalDocumentation - - -class Tag(BaseModel): - """ - Adds metadata to a single tag that is used by the [Operation Object](#operationObject). - It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. - - References: - - https://swagger.io/docs/specification/paths-and-operations/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#tagObject - """ - - name: str - description: Optional[str] = None - externalDocs: Optional[ExternalDocumentation] = None - model_config = ConfigDict( - extra="allow", json_schema_extra={"examples": [{"name": "pet", "description": "Pets operations"}]} - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/xml.py b/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/xml.py deleted file mode 100644 index 986aa44f43a7..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/openapi_schema_pydantic/xml.py +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel, ConfigDict - - -class XML(BaseModel): - """ - A metadata object that allows for more fine-tuned XML model definitions. - - When using arrays, XML element names are *not* inferred (for singular/plural forms) - and the `name` property SHOULD be used to add that information. - See examples for expected behavior. - - References: - - https://swagger.io/docs/specification/data-models/representing-xml/ - - https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#xmlObject - """ - - name: Optional[str] = None - namespace: Optional[str] = None - prefix: Optional[str] = None - attribute: bool = False - wrapped: bool = False - model_config = ConfigDict( - extra="allow", - json_schema_extra={ - "examples": [ - {"namespace": "http://example.com/schema/sample", "prefix": "sample"}, - {"name": "aliens", "wrapped": True}, - ] - }, - ) diff --git a/chaotic-openapi/chaotic_openapi/front/schema/parameter_location.py b/chaotic-openapi/chaotic_openapi/front/schema/parameter_location.py deleted file mode 100644 index 162a7cb131ca..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/schema/parameter_location.py +++ /dev/null @@ -1,25 +0,0 @@ -# Python 3.11 has StrEnum but breaks the old `str, Enum` hack. -# Unless this gets fixed, we need to have two implementations :( -import sys - -if sys.version_info >= (3, 11): - from enum import StrEnum - - class ParameterLocation(StrEnum): - """The places Parameters can be put when calling an Endpoint""" - - QUERY = "query" - PATH = "path" - HEADER = "header" - COOKIE = "cookie" - -else: - from enum import Enum - - class ParameterLocation(str, Enum): - """The places Parameters can be put when calling an Endpoint""" - - QUERY = "query" - PATH = "path" - HEADER = "header" - COOKIE = "cookie" diff --git a/chaotic-openapi/chaotic_openapi/front/utils.py b/chaotic-openapi/chaotic_openapi/front/utils.py deleted file mode 100644 index 8429af035176..000000000000 --- a/chaotic-openapi/chaotic_openapi/front/utils.py +++ /dev/null @@ -1,122 +0,0 @@ -from __future__ import annotations - -import builtins -import re -from email.message import Message -from keyword import iskeyword -from typing import Any - -from .config import Config - -DELIMITERS = r"\. _-" - - -class PythonIdentifier(str): - """A snake_case string which has been validated / transformed into a valid identifier for Python""" - - def __new__(cls, value: str, prefix: str, skip_snake_case: bool = False) -> PythonIdentifier: - new_value = sanitize(value) - if not skip_snake_case: - new_value = snake_case(new_value) - new_value = fix_reserved_words(new_value) - - if not new_value.isidentifier() or value.startswith("_"): - new_value = f"{prefix}{new_value}" - return str.__new__(cls, new_value) - - def __deepcopy__(self, _: Any) -> PythonIdentifier: - return self - - -class ClassName(str): - """A PascalCase string which has been validated / transformed into a valid class name for Python""" - - def __new__(cls, value: str, prefix: str) -> ClassName: - new_value = fix_reserved_words(pascal_case(sanitize(value))) - - if not new_value.isidentifier(): - value = f"{prefix}{new_value}" - new_value = fix_reserved_words(pascal_case(sanitize(value))) - return str.__new__(cls, new_value) - - def __deepcopy__(self, _: Any) -> ClassName: - return self - - -def sanitize(value: str) -> str: - """Removes every character that isn't 0-9, A-Z, a-z, or a known delimiter""" - return re.sub(rf"[^\w{DELIMITERS}]+", "", value) - - -def split_words(value: str) -> List[str]: - """Split a string on words and known delimiters""" - # We can't guess words if there is no capital letter - if any(c.isupper() for c in value): - value = " ".join(re.split("([A-Z]?[a-z]+)", value)) - return re.findall(rf"[^{DELIMITERS}]+", value) - - -RESERVED_WORDS = (set(dir(builtins)) | {"self", "true", "false", "datetime"}) - { - "id", -} - - -def fix_reserved_words(value: str) -> str: - """ - Using reserved Python words as identifiers in generated code causes problems, so this function renames them. - - Args: - value: The identifier to-be that should be renamed if it's a reserved word. - - Returns: - `value` suffixed with `_` if it was a reserved word. - """ - if value in RESERVED_WORDS or iskeyword(value): - return f"{value}_" - return value - - -def snake_case(value: str) -> str: - """Converts to snake_case""" - words = split_words(sanitize(value)) - return "_".join(words).lower() - - -def pascal_case(value: str) -> str: - """Converts to PascalCase""" - words = split_words(sanitize(value)) - capitalized_words = (word.capitalize() if not word.isupper() else word for word in words) - return "".join(capitalized_words) - - -def kebab_case(value: str) -> str: - """Converts to kebab-case""" - words = split_words(sanitize(value)) - return "-".join(words).lower() - - -def remove_string_escapes(value: str) -> str: - """Used when parsing string-literal defaults to prevent escaping the string to write arbitrary Python - - **REMOVING OR CHANGING THE USAGE OF THIS FUNCTION HAS SECURITY IMPLICATIONS** - - See Also: - - https://github.com/openapi-generators/openapi-python-client/security/advisories/GHSA-9x4c-63pf-525f - """ - return value.replace('"', r"\"") - - -def get_content_type(content_type: str, config: Config) -> str | None: - """ - Given a string representing a content type with optional parameters, returns the content type only - """ - content_type = config.content_type_overrides.get(content_type, content_type) - message = Message() - message.add_header("Content-Type", content_type) - - parsed_content_type = message.get_content_type() - if not content_type.startswith(parsed_content_type): - # Always defaults to `text/plain` if it's not recognized. We want to return an error, not default. - return None - - return parsed_content_type From 05c77a972ea89af00ec541f4035b66b94badcada Mon Sep 17 00:00:00 2001 From: Artem Khromov Date: Mon, 20 Jan 2025 02:40:02 +0300 Subject: [PATCH 4/5] Better --- scripts/chaotic/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/chaotic/requirements.txt b/scripts/chaotic/requirements.txt index 4950411a8eab..1f9f5c982cf0 100644 --- a/scripts/chaotic/requirements.txt +++ b/scripts/chaotic/requirements.txt @@ -1,3 +1,3 @@ Jinja2 >= 2.10 PyYAML >= 6.0.1 - +openapi-python-client==0.21.7 From 65cbbb35482a8235664fee782c6d129881ddc95e Mon Sep 17 00:00:00 2001 From: Artem Khromov Date: Mon, 20 Jan 2025 04:23:28 +0300 Subject: [PATCH 5/5] Better --- chaotic-openapi/chaotic_openapi/{alo.py => example.py} | 2 +- chaotic-openapi/chaotic_openapi/{opa.yaml => example.yaml} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename chaotic-openapi/chaotic_openapi/{alo.py => example.py} (93%) rename chaotic-openapi/chaotic_openapi/{opa.yaml => example.yaml} (100%) diff --git a/chaotic-openapi/chaotic_openapi/alo.py b/chaotic-openapi/chaotic_openapi/example.py similarity index 93% rename from chaotic-openapi/chaotic_openapi/alo.py rename to chaotic-openapi/chaotic_openapi/example.py index 3b0fddb63db8..1b4329597b68 100644 --- a/chaotic-openapi/chaotic_openapi/alo.py +++ b/chaotic-openapi/chaotic_openapi/example.py @@ -7,7 +7,7 @@ def parse(data_dict: Dict[str, Any], config: Config): return GeneratorData.from_dict(data_dict, config=config) def config(): - return Config.from_sources(ConfigFile(), MetaType.NONE, Path("opa.yaml"), 'utf-8', False, None) + return Config.from_sources(ConfigFile(), MetaType.NONE, Path("example.yaml"), 'utf-8', False, None) from openapi_python_client import _get_document diff --git a/chaotic-openapi/chaotic_openapi/opa.yaml b/chaotic-openapi/chaotic_openapi/example.yaml similarity index 100% rename from chaotic-openapi/chaotic_openapi/opa.yaml rename to chaotic-openapi/chaotic_openapi/example.yaml