fastapi-code-generator icon indicating copy to clipboard operation
fastapi-code-generator copied to clipboard

Illegal FastAPI constructor generated (AttributeError: 'str' object has no attribute 'get': server_data.get("url"))

Open olivergondza opened this issue 3 years ago • 1 comments

Using default main template:

app = FastAPI(
    {% if info %}
    {% for key,value in info.items() %}
    {{ key }} = "{{ value }}",
    {% endfor %}
    {% endif %}
    )

Generates invalid FastAPI constructor when servers are used:

app = FastAPI(
    title="App title",
    description="App desc",
    version="0.1",
    servers="[{'url': 'http://api.example.com/v1', 'description': 'App desc'}, {'url': 'http://staging-api.example.com', 'description': 'App desc'}]",
)

(note the servers key value is actually a string).

Full stacktrace:

  File "/CODE/repo/openapi/main.py", line 23, in <module>
    app = FastAPI(
  File "/CODE/.repo-venv/lib/python3.10/site-packages/fastapi/applications.py", line 146, in __init__
    self.setup()
  File "/CODE/.repo-venv/lib/python3.10/site-packages/fastapi/applications.py", line 216, in setup
    server_urls = {url for url in urls if url}
  File "/CODE/.repo-venv/lib/python3.10/site-packages/fastapi/applications.py", line 216, in <setcomp>
    server_urls = {url for url in urls if url}
  File "/CODE/.repo-venv/lib/python3.10/site-packages/fastapi/applications.py", line 215, in <genexpr>
    urls = (server_data.get("url") for server_data in self.servers)
AttributeError: 'str' object has no attribute 'get'

Removing the " from the template in {{ key }} = "{{ value }}" does not help as it breaks the scalar keys. What do help is removing servers from OpenApi spec.

Version 0.3.5.

olivergondza avatar May 17 '22 11:05 olivergondza

Seems introduced by https://github.com/koxudaxi/fastapi-code-generator/commit/987a91a0520bccc4cd8067d99c2506cc35a50a44 as the servers ware not added to the constructor before.

olivergondza avatar May 17 '22 11:05 olivergondza

@koxudaxi Could you close it?

It is fixed by https://github.com/koxudaxi/fastapi-code-generator/commit/5e9ba07ec6be36a80334270531eaa3677a5ec711

I confirmed it with the follwoing servers definition.

servers:
  - url: http://petstore.swagger.io/v1
    description: Production server
  - url: http://localost:8080/
    description: local dev server

Here is a fragment of the genereted code.

app = FastAPI(
    version='1.0.0',
    title='Swagger Petstore',
    license={'name': 'MIT'},
    description='This description is for testing\nmulti-line\ndescription\n',
    servers=[
        {'url': 'http://petstore.swagger.io/v1', 'description': 'Production server'},
        {'url': 'http://localost:8080/', 'description': 'local dev server'},
    ],
)

yyamano avatar Aug 10 '23 01:08 yyamano

Sure, thanks!

olivergondza avatar Aug 16 '23 11:08 olivergondza