Specs with vendor extensions might lead to invalid Python code
hajs opened this issue · 0 comments
hajs commented
Users can add additional information with x-fields. But Python does not accept identifiers with dashses.
Here are some common vendor extensions documented: https://github.com/Redocly/redoc/blob/main/docs/redoc-vendor-extensions.md#x-logo
Here is example spec:
openapi: 3.0.0
info:
title: Example
version: 1.0.0
x-audience: company-internal
x-logo:
url: https://www.example.com/company-logo.png
The generated code looks like this
app = FastAPI(
title='Example',
version='1.0.0',
x - audience='company-internal',
x - logo={'url': 'https://www.example.com/company-logo.png'},
)
I fixed it this way:
--- fastapi_code_generator/template/main.jinja2.orig 2023-02-13 16:11:00.677867572 +0100
+++ fastapi_code_generator/template/main.jinja2 2023-02-13 16:37:28.944897684 +0100
@@ -8,7 +8,9 @@
{% if info %}
{% for key,value in info.items() %}
{% set info_value= value.__repr__() %}
+ {%- if not key.startswith("x-") -%}
{{ key }} = {{info_value}},
+ {%- endif -%}
{% endfor %}
{% endif %}
)
First I tried to add all fields as a dict passed as kwargs:
app = FastAPI(**{
'title': 'Example',
'version': '1.0.0',
'x-audience': 'company-internal',
'x-logo': {'url': 'https://www.example.com/company-logo.png'},
})
But ignoring these fields seems sufficient because FastAPI ignores them anyway.