Skip to content

Commit 9810108

Browse files
committed
:feat: Added headers handling to generated code if they are required through the API
1 parent cc7c151 commit 9810108

File tree

13 files changed

+1595
-409
lines changed

13 files changed

+1595
-409
lines changed

poetry.lock

+497-402
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/openapi_python_generator/generate_data.py

+3
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ def write_code(path: Path, content) -> None:
3434
formatted_contend = black.format_file_contents(
3535
content, fast=False, mode=black.FileMode(line_length=120)
3636
)
37+
3738
except NothingChanged:
3839
formatted_contend = content
3940
formatted_contend = isort.code(formatted_contend, line_length=120)
@@ -142,5 +143,7 @@ def generate_data(
142143
"""
143144
data = get_open_api(source)
144145
click.echo(f"Generating data from {source}")
146+
145147
result = generator(data, library_config_dict[library], env_token_name, use_orjson)
148+
146149
write_data(result, output)

src/openapi_python_generator/language_converters/python/api_config_generator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,5 @@ def generate_api_config(
2020
content=JINJA_ENV.get_template(API_CONFIG_TEMPLATE).render(
2121
env_token_name=env_token_name, **data.dict()
2222
),
23-
base_url=data.servers[0].url,
23+
base_url=data.servers[0].url if len(data.servers) > 0 else "NO SERVER",
2424
)

src/openapi_python_generator/language_converters/python/service_generator.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import re
2-
from typing import Dict
2+
from typing import Dict, Literal
33
from typing import List
44
from typing import Tuple
55
from typing import Union
@@ -158,19 +158,24 @@ def generate_operation_id(operation: Operation, http_op: str) -> str:
158158
raise Exception(f"OperationId is not defined for {http_op}") # pragma: no cover
159159

160160

161-
def generate_query_params(operation: Operation) -> List[str]:
161+
def _generate_params(operation: Operation, param_in : Literal["query", "header"] = "query"):
162162
if operation.parameters is None:
163163
return []
164164

165165
params = []
166166
for param in operation.parameters:
167-
if isinstance(param, Parameter) and param.param_in == "query":
167+
if isinstance(param, Parameter) and param.param_in == param_in:
168168
param_name_cleaned = param.name.replace("-", "_")
169169

170170
params.append(f"'{param.name}' : {param_name_cleaned}")
171171

172172
return params
173173

174+
def generate_query_params(operation: Operation) -> List[str]:
175+
return _generate_params(operation, "query")
176+
177+
def generate_header_params(operation: Operation) -> List[str]:
178+
return _generate_params(operation, "header")
174179

175180
def generate_return_type(operation: Operation) -> OpReturnType:
176181
if operation.responses is None:
@@ -257,13 +262,15 @@ def generate_service_operation(
257262
params = generate_params(op)
258263
operation_id = generate_operation_id(op, http_operation)
259264
query_params = generate_query_params(op)
265+
header_params = generate_header_params(op)
260266
return_type = generate_return_type(op)
261267
body_param = generate_body_param(op)
262268

263269
so = ServiceOperation(
264270
params=params,
265271
operation_id=operation_id,
266272
query_params=query_params,
273+
header_params=header_params,
267274
return_type=return_type,
268275
operation=op,
269276
pathItem=path,

src/openapi_python_generator/language_converters/python/templates/aiohttp.jinja2

+2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ async def {{ operation_id }}({{ params }}) -> {% if return_type.type is none or
55
'Content-Type': 'application/json',
66
'Accept': 'application/json',
77
'Authorization': f'Bearer { APIConfig.get_access_token() }',
8+
{{ header_params | join(',\n') | safe }}
89
}
10+
911
query_params : Dict[str,Any] = {
1012
{% if query_params|length > 0 %}
1113
{{ query_params | join(',\n') | safe }}

src/openapi_python_generator/language_converters/python/templates/apiconfig.jinja2

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
from typing import Optional, Union
44

55
class APIConfig():
6-
base_path: str = '{{ servers[0].url }}'
6+
base_path: str = {% if servers|length > 0 %} '{{ servers[0].url }}' {% else %} 'NO SERVER' {% endif %}
7+
78
verify: Union[bool, str] = True
89
{% if env_token_name is none %}
910
_access_token : Optional[str] = None

src/openapi_python_generator/language_converters/python/templates/httpx.jinja2

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
'Content-Type': 'application/json',
66
'Accept': 'application/json',
77
'Authorization': f'Bearer { APIConfig.get_access_token() }',
8+
{{ header_params | join(',\n') | safe }}
89
}
910
query_params : Dict[str,Any] = {
1011
{% if query_params|length > 0 %}

src/openapi_python_generator/language_converters/python/templates/requests.jinja2

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ def {{ operation_id }}({{ params }}) -> {% if return_type.type is none or return
55
'Content-Type': 'application/json',
66
'Accept': 'application/json',
77
'Authorization': f'Bearer { APIConfig.get_access_token() }',
8-
}
8+
{{ header_params | join(',\n') | safe }}
9+
}
910
query_params : Dict[str,Any] = {
1011
{% if query_params|length > 0 %}
1112
{{ query_params | join(',\n') | safe }}

src/openapi_python_generator/models.py

+1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ class ServiceOperation(BaseModel):
3232
params: str
3333
operation_id: str
3434
query_params: List[str]
35+
header_params: List[str]
3536
return_type: OpReturnType
3637
operation: Operation
3738
pathItem: PathItem

tests/regression/test_issue_17.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import pytest
2+
from click.testing import CliRunner
3+
4+
from openapi_python_generator.__main__ import main
5+
from openapi_python_generator.common import HTTPLibrary
6+
from openapi_python_generator.generate_data import generate_data
7+
from tests.conftest import test_data_folder
8+
from tests.conftest import test_result_path
9+
10+
11+
@pytest.fixture
12+
def runner() -> CliRunner:
13+
"""Fixture for invoking command-line interfaces."""
14+
return CliRunner()
15+
16+
@pytest.mark.parametrize(
17+
"library",
18+
[HTTPLibrary.httpx, HTTPLibrary.aiohttp, HTTPLibrary.requests],
19+
)
20+
def test_issue_11(runner: CliRunner, model_data_with_cleanup, library) -> None:
21+
"""
22+
https://github.com/MarcoMuellner/openapi-python-generator/issues/7
23+
"""
24+
assert generate_data(test_data_folder / "issue_17.json",
25+
test_result_path,
26+
library) is None
27+

0 commit comments

Comments
 (0)