Skip to content

Commit 306c2e0

Browse files
committed
feat: tags in client
1 parent 88010cb commit 306c2e0

59 files changed

Lines changed: 3192 additions & 726 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import ssl
2+
from typing import Dict, Union
3+
4+
5+
class MyTestApiClient:
6+
"""A class for keeping track of data related to the API
7+
8+
Attributes:
9+
base_url: The base URL for the API, all requests are made to a relative path to this URL
10+
cookies: A dictionary of cookies to be sent with every request
11+
headers: A dictionary of headers to be sent with every request
12+
timeout: The maximum amount of a time in seconds a request can take. API functions will raise
13+
httpx.TimeoutException if this is exceeded.
14+
verify_ssl: Whether or not to verify the SSL certificate of the API server. This should be True in production,
15+
but can be set to False for testing purposes.
16+
raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
17+
status code that was not documented in the source OpenAPI document.
18+
follow_redirects: Whether or not to follow redirects. Default value is False.
19+
"""
20+
21+
def __init__(
22+
self,
23+
base_url: str,
24+
cookies: Union[Dict[str, str], None] = None,
25+
headers: Union[Dict[str, str], None] = None,
26+
timeout: float = 5.0,
27+
verify_ssl: Union[str, bool, ssl.SSLContext] = True,
28+
raise_on_unexpected_status: bool = False,
29+
follow_redirects: bool = False,
30+
token: Union[str, None] = None,
31+
prefix: str = "Bearer",
32+
auth_header_name: str = "Authorization",
33+
):
34+
cookies = cookies if cookies is not None else {}
35+
headers = headers if headers is not None else {}
36+
37+
self.base_url = base_url
38+
self.cookies = cookies
39+
self.headers = headers
40+
self.timeout = timeout
41+
self.verify_ssl = verify_ssl
42+
self.raise_on_unexpected_status = raise_on_unexpected_status
43+
self.follow_redirects = follow_redirects
44+
self.token = token
45+
self.prefix = prefix
46+
self.auth_header_name = auth_header_name
47+
48+
def get_headers(self) -> Dict[str, str]:
49+
"""Get headers to be used in all endpoints"""
50+
if not self.token:
51+
return {**self.headers}
52+
auth_header_value = f"{self.prefix} {self.token}" if self.prefix else self.token
53+
return {self.auth_header_name: auth_header_value, **self.headers}
54+
55+
def get_cookies(self) -> Dict[str, str]:
56+
return {**self.cookies}
57+
58+
def get_timeout(self) -> float:
59+
return self.timeout

end_to_end_tests/golden-record/README.md

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,36 +7,29 @@ First, configure a client:
77
```python
88
from my_test_api_client import MyTestApiClient
99

10-
MyTestApiClient.configure(base_url="https://api.example.com", token="SuperSecretToken")
10+
client = MyTestApiClient(base_url="https://api.example.com", token="SuperSecretToken")
1111
```
1212

1313
Now call your endpoint and use your models:
1414

1515
```python
1616
from my_test_api_client.models import MyDataModel
17-
from my_test_api_client.my_tag import get_my_data_model
18-
from my_test_api_client.types import Response
1917

20-
my_data: MyDataModel = get_my_data_model()
21-
# or if you need more info (e.g. status_code)
22-
response: Response[MyDataModel] = get_my_data_model_detailed()
18+
my_data: MyDataModel = client.my_tag.get_my_data_model()
2319
```
2420

2521
Or do the same thing with an async version:
2622

2723
```python
2824
from my_test_api_client.models import MyDataModel
29-
from my_test_api_client.my_tag import get_my_data_model
30-
from my_test_api_client.types import Response
3125

32-
my_data: MyDataModel = await get_my_data_model_async()
33-
response: Response[MyDataModel] = await get_my_data_model_async_detailed()
26+
my_data: MyDataModel = await client.get_my_data_model_async()
3427
```
3528

3629
By default, when you're calling an HTTPS API it will attempt to verify that SSL is working correctly. Using certificate verification is highly recommended most of the time, but sometimes you may need to authenticate to a server (especially an internal server) using a custom certificate bundle.
3730

3831
```python
39-
MyTestApiClient.configure(
32+
client = MyTestApiClient(
4033
base_url="https://internal_api.example.com",
4134
token="SuperSecretToken",
4235
verify_ssl="/path/to/certificate_bundle.pem",
@@ -46,7 +39,7 @@ MyTestApiClient.configure(
4639
You can also disable certificate validation altogether, but beware that **this is a security risk**.
4740

4841
```python
49-
MyTestApiClient.configure(
42+
client = MyTestApiClient(
5043
base_url="https://internal_api.example.com",
5144
token="SuperSecretToken",
5245
verify_ssl=False
@@ -56,11 +49,9 @@ MyTestApiClient.configure(
5649
There are more settings on the generated `MyTestApiClient` class which let you control more runtime behavior, check out the docstring on that class for more info.
5750

5851
Things to know:
59-
1. Every path/method combo becomes provides you with four functions. For example: get_my_data_model has these methods:
52+
1. Every path/method combo becomes provides you with two functions. For example: get_my_data_model has these methods:
6053
1. `get_my_data_model`: Blocking request that returns parsed data (if successful) or `None`
61-
1. `get_my_data_model_detailed`: Blocking request that always returns a `Request`, optionally with `parsed` set if the request was successful.
6254
1. `get_my_data_model_async`: Like `sync` but async instead of blocking
63-
1. `get_my_data_model_async_detailed`: Like `sync_detailed` but async instead of blocking
6455

6556
1. All path/query params, and bodies become method arguments.
6657
1. If your endpoint had any tags on it, the first tag will be used as a module name for the function (my_tag above)
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
from typing import TYPE_CHECKING, Any, Optional
2+
3+
if TYPE_CHECKING:
4+
from ...client import MyTestApiClient
5+
6+
from typing import Optional, Union
7+
8+
from ...types import UNSET, Unset
9+
from . import get_common_parameters, post_common_parameters
10+
11+
12+
class Default:
13+
def __init__(self, client: "MyTestApiClient"):
14+
self.__client = client
15+
16+
def get_common_parameters(
17+
self,
18+
*,
19+
common: Union[Unset, None, str] = UNSET,
20+
) -> Optional[Any]:
21+
"""
22+
Args:
23+
common (Union[Unset, None, str]):
24+
25+
Raises:
26+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
27+
httpx.TimeoutException: If the request takes longer than Client.timeout.
28+
29+
Returns:
30+
Response[Any]
31+
"""
32+
33+
return get_common_parameters.sync(
34+
client=self.__client,
35+
common=common,
36+
)
37+
38+
async def get_common_parameters_async(
39+
self,
40+
*,
41+
common: Union[Unset, None, str] = UNSET,
42+
) -> Optional[Any]:
43+
"""
44+
Args:
45+
common (Union[Unset, None, str]):
46+
47+
Raises:
48+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
49+
httpx.TimeoutException: If the request takes longer than Client.timeout.
50+
51+
Returns:
52+
Response[Any]
53+
"""
54+
55+
return await get_common_parameters.asyncio(
56+
client=self.__client,
57+
common=common,
58+
)
59+
60+
def post_common_parameters(
61+
self,
62+
*,
63+
common: Union[Unset, None, str] = UNSET,
64+
) -> Optional[Any]:
65+
"""
66+
Args:
67+
common (Union[Unset, None, str]):
68+
69+
Raises:
70+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
71+
httpx.TimeoutException: If the request takes longer than Client.timeout.
72+
73+
Returns:
74+
Response[Any]
75+
"""
76+
77+
return post_common_parameters.sync(
78+
client=self.__client,
79+
common=common,
80+
)
81+
82+
async def post_common_parameters_async(
83+
self,
84+
*,
85+
common: Union[Unset, None, str] = UNSET,
86+
) -> Optional[Any]:
87+
"""
88+
Args:
89+
common (Union[Unset, None, str]):
90+
91+
Raises:
92+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
93+
httpx.TimeoutException: If the request takes longer than Client.timeout.
94+
95+
Returns:
96+
Response[Any]
97+
"""
98+
99+
return await post_common_parameters.asyncio(
100+
client=self.__client,
101+
common=common,
102+
)

end_to_end_tests/golden-record/my_test_api_client/api/default/get_common_parameters.py

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
from http import HTTPStatus
2-
from typing import Any, Dict, Optional, Union
2+
from typing import TYPE_CHECKING, Any, Dict, Optional, Union
33

44
import httpx
55

6+
if TYPE_CHECKING:
7+
from ...client import MyTestApiClient
8+
9+
from typing import Optional, Union
10+
611
from ... import errors
7-
from ...client import MyTestApiClient
812
from ...types import UNSET, Response, Unset
913

1014

11-
def _get_kwargs(*, common: Union[Unset, None, str] = UNSET, client: MyTestApiClient) -> Dict[str, Any]:
15+
def _get_kwargs(*, common: Union[Unset, None, str] = UNSET, client: "MyTestApiClient") -> Dict[str, Any]:
1216
url = "{}/common_parameters".format(client.base_url)
1317

1418
headers: Dict[str, str] = client.get_headers()
@@ -30,7 +34,7 @@ def _get_kwargs(*, common: Union[Unset, None, str] = UNSET, client: MyTestApiCli
3034
}
3135

3236

33-
def _parse_response(*, client: MyTestApiClient, response: httpx.Response) -> Optional[Any]:
37+
def _parse_response(*, client: "MyTestApiClient", response: httpx.Response) -> Optional[Any]:
3438
if response.status_code == HTTPStatus.OK:
3539
return None
3640
if client.raise_on_unexpected_status:
@@ -39,7 +43,7 @@ def _parse_response(*, client: MyTestApiClient, response: httpx.Response) -> Opt
3943
return None
4044

4145

42-
def _build_response(*, client: MyTestApiClient, response: httpx.Response) -> Response[Any]:
46+
def _build_response(*, client: "MyTestApiClient", response: httpx.Response) -> Response[Any]:
4347
return Response(
4448
status_code=HTTPStatus(response.status_code),
4549
content=response.content,
@@ -48,9 +52,7 @@ def _build_response(*, client: MyTestApiClient, response: httpx.Response) -> Res
4852
)
4953

5054

51-
def sync_detailed(
52-
*, common: Union[Unset, None, str] = UNSET, client: Union[MyTestApiClient, Unset] = UNSET
53-
) -> Response[Any]:
55+
def sync_detailed(*, common: Union[Unset, None, str] = UNSET, client: "MyTestApiClient") -> Response[Any]:
5456
"""
5557
Args:
5658
common (Union[Unset, None, str]):
@@ -63,7 +65,6 @@ def sync_detailed(
6365
Response[Any]
6466
"""
6567

66-
client = client if not isinstance(client, Unset) else MyTestApiClient.instance()
6768
kwargs = _get_kwargs(
6869
client=client,
6970
common=common,
@@ -77,9 +78,26 @@ def sync_detailed(
7778
return _build_response(client=client, response=response)
7879

7980

80-
async def asyncio_detailed(
81-
*, common: Union[Unset, None, str] = UNSET, client: Union[MyTestApiClient, Unset] = UNSET
82-
) -> Response[Any]:
81+
def sync(*, common: Union[Unset, None, str] = UNSET, client: "MyTestApiClient") -> Optional[Any]:
82+
"""
83+
Args:
84+
common (Union[Unset, None, str]):
85+
86+
Raises:
87+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
88+
httpx.TimeoutException: If the request takes longer than Client.timeout.
89+
90+
Returns:
91+
Response[Any]
92+
"""
93+
94+
return sync_detailed(
95+
client=client,
96+
common=common,
97+
).parsed
98+
99+
100+
async def asyncio_detailed(*, common: Union[Unset, None, str] = UNSET, client: "MyTestApiClient") -> Response[Any]:
83101
"""
84102
Args:
85103
common (Union[Unset, None, str]):
@@ -92,7 +110,6 @@ async def asyncio_detailed(
92110
Response[Any]
93111
"""
94112

95-
client = client if not isinstance(client, Unset) else MyTestApiClient.instance()
96113
kwargs = _get_kwargs(
97114
client=client,
98115
common=common,
@@ -102,3 +119,24 @@ async def asyncio_detailed(
102119
response = await _client.request(**kwargs)
103120

104121
return _build_response(client=client, response=response)
122+
123+
124+
async def asyncio(*, common: Union[Unset, None, str] = UNSET, client: "MyTestApiClient") -> Optional[Any]:
125+
"""
126+
Args:
127+
common (Union[Unset, None, str]):
128+
129+
Raises:
130+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
131+
httpx.TimeoutException: If the request takes longer than Client.timeout.
132+
133+
Returns:
134+
Response[Any]
135+
"""
136+
137+
return (
138+
await asyncio_detailed(
139+
client=client,
140+
common=common,
141+
)
142+
).parsed

0 commit comments

Comments
 (0)