From f507a77a430fbc499533ade438d348308f7c4aa1 Mon Sep 17 00:00:00 2001 From: Yasin Tatar Date: Fri, 10 Nov 2023 12:07:11 +0100 Subject: [PATCH 1/2] add: option to generate api specification by field name instead of alias --- docs/en/docs/how-to/extending-openapi.md | 1 + fastapi/openapi/utils.py | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md index a18fd737e..4126cf79b 100644 --- a/docs/en/docs/how-to/extending-openapi.md +++ b/docs/en/docs/how-to/extending-openapi.md @@ -26,6 +26,7 @@ And that function `get_openapi()` receives as parameters: * `summary`: A short summary of the API. * `description`: The description of your API, this can include markdown and will be shown in the docs. * `routes`: A list of routes, these are each of the registered *path operations*. They are taken from `app.routes`. +* `field_names_by_alias`: A boolean indicating whether to use the field names or the alias names for the models. !!! info The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above. diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 5bfb5acef..58c0b460a 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -450,6 +450,7 @@ def get_openapi( contact: Optional[Dict[str, Union[str, Any]]] = None, license_info: Optional[Dict[str, Union[str, Any]]] = None, separate_input_output_schemas: bool = True, + field_names_by_alias: bool = True, ) -> Dict[str, Any]: info: Dict[str, Any] = {"title": title, "version": version} if summary: @@ -471,7 +472,9 @@ def get_openapi( operation_ids: Set[str] = set() all_fields = get_fields_from_routes(list(routes or []) + list(webhooks or [])) model_name_map = get_compat_model_name_map(all_fields) - schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE) + schema_generator = GenerateJsonSchema( + ref_template=REF_TEMPLATE, by_alias=field_names_by_alias + ) field_mapping, definitions = get_definitions( fields=all_fields, schema_generator=schema_generator, From 217bf8f2b99bc1a07b0e0c2dad98dcb6eab3ad8b Mon Sep 17 00:00:00 2001 From: Yasin Tatar Date: Fri, 10 Nov 2023 12:19:18 +0100 Subject: [PATCH 2/2] update dataclass for backward-compat --- fastapi/_compat.py | 1 + 1 file changed, 1 insertion(+) diff --git a/fastapi/_compat.py b/fastapi/_compat.py index fc605d0ec..13f596423 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -347,6 +347,7 @@ else: @dataclass class GenerateJsonSchema: # type: ignore[no-redef] ref_template: str + by_alias: bool = True class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass