Skip to content

Commit 8864a5f

Browse files
dbantyemosenkis
andauthored
Literal enums support! (#1142)
This is just #1114 but with some docs & changeset --------- Co-authored-by: Eitan Mosenkis <[email protected]> Co-authored-by: Eitan Mosenkis <[email protected]> Co-authored-by: Dylan Anthony <[email protected]>
1 parent a9c0784 commit 8864a5f

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+2388
-55
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
default: minor
3+
---
4+
5+
# Add `literal_enums` config setting
6+
7+
Instead of the default `Enum` classes for enums, you can now generate `Literal` sets wherever `enum` appears in the OpenAPI spec by setting `literal_enums: true` in your config file.
8+
9+
```yaml
10+
literal_enums: true
11+
```
12+
13+
Thanks to @emosenkis for PR #1114 closes #587, #725, #1076, and probably many more.
14+
Thanks also to @eli-bl, @expobrain, @theorm, @chrisguillory, and anyone else who helped getting to this design!

README.md

+11
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,17 @@ class_overrides:
9797
9898
The easiest way to find what needs to be overridden is probably to generate your client and go look at everything in the `models` folder.
9999

100+
### literal_enums
101+
102+
By default, `openapi-python-client` generates classes inheriting for `Enum` for enums. It can instead use `Literal`
103+
values for enums by setting this to `true`:
104+
105+
```yaml
106+
literal_enums: true
107+
```
108+
109+
This is especially useful if enum values, when transformed to their Python names, end up conflicting due to case sensitivity or special symbols.
110+
100111
### project_name_override and package_name_override
101112

102113
Used to change the name of generated client library project/package. If the project name is changed but an override for the package name
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
__pycache__/
2+
build/
3+
dist/
4+
*.egg-info/
5+
.pytest_cache/
6+
7+
# pyenv
8+
.python-version
9+
10+
# Environments
11+
.env
12+
.venv
13+
14+
# mypy
15+
.mypy_cache/
16+
.dmypy.json
17+
dmypy.json
18+
19+
# JetBrains
20+
.idea/
21+
22+
/coverage.xml
23+
/.coverage
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# my-enum-api-client
2+
A client library for accessing My Enum API
3+
4+
## Usage
5+
First, create a client:
6+
7+
```python
8+
from my_enum_api_client import Client
9+
10+
client = Client(base_url="https://api.example.com")
11+
```
12+
13+
If the endpoints you're going to hit require authentication, use `AuthenticatedClient` instead:
14+
15+
```python
16+
from my_enum_api_client import AuthenticatedClient
17+
18+
client = AuthenticatedClient(base_url="https://api.example.com", token="SuperSecretToken")
19+
```
20+
21+
Now call your endpoint and use your models:
22+
23+
```python
24+
from my_enum_api_client.models import MyDataModel
25+
from my_enum_api_client.api.my_tag import get_my_data_model
26+
from my_enum_api_client.types import Response
27+
28+
with client as client:
29+
my_data: MyDataModel = get_my_data_model.sync(client=client)
30+
# or if you need more info (e.g. status_code)
31+
response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client)
32+
```
33+
34+
Or do the same thing with an async version:
35+
36+
```python
37+
from my_enum_api_client.models import MyDataModel
38+
from my_enum_api_client.api.my_tag import get_my_data_model
39+
from my_enum_api_client.types import Response
40+
41+
async with client as client:
42+
my_data: MyDataModel = await get_my_data_model.asyncio(client=client)
43+
response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client)
44+
```
45+
46+
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.
47+
48+
```python
49+
client = AuthenticatedClient(
50+
base_url="https://internal_api.example.com",
51+
token="SuperSecretToken",
52+
verify_ssl="/path/to/certificate_bundle.pem",
53+
)
54+
```
55+
56+
You can also disable certificate validation altogether, but beware that **this is a security risk**.
57+
58+
```python
59+
client = AuthenticatedClient(
60+
base_url="https://internal_api.example.com",
61+
token="SuperSecretToken",
62+
verify_ssl=False
63+
)
64+
```
65+
66+
Things to know:
67+
1. Every path/method combo becomes a Python module with four functions:
68+
1. `sync`: Blocking request that returns parsed data (if successful) or `None`
69+
1. `sync_detailed`: Blocking request that always returns a `Request`, optionally with `parsed` set if the request was successful.
70+
1. `asyncio`: Like `sync` but async instead of blocking
71+
1. `asyncio_detailed`: Like `sync_detailed` but async instead of blocking
72+
73+
1. All path/query params, and bodies become method arguments.
74+
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)
75+
1. Any endpoint which did not have a tag will be in `my_enum_api_client.api.default`
76+
77+
## Advanced customizations
78+
79+
There are more settings on the generated `Client` class which let you control more runtime behavior, check out the docstring on that class for more info. You can also customize the underlying `httpx.Client` or `httpx.AsyncClient` (depending on your use-case):
80+
81+
```python
82+
from my_enum_api_client import Client
83+
84+
def log_request(request):
85+
print(f"Request event hook: {request.method} {request.url} - Waiting for response")
86+
87+
def log_response(response):
88+
request = response.request
89+
print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")
90+
91+
client = Client(
92+
base_url="https://api.example.com",
93+
httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}},
94+
)
95+
96+
# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client()
97+
```
98+
99+
You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url):
100+
101+
```python
102+
import httpx
103+
from my_enum_api_client import Client
104+
105+
client = Client(
106+
base_url="https://api.example.com",
107+
)
108+
# Note that base_url needs to be re-set, as would any shared cookies, headers, etc.
109+
client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030"))
110+
```
111+
112+
## Building / publishing this package
113+
This project uses [Poetry](https://python-poetry.org/) to manage dependencies and packaging. Here are the basics:
114+
1. Update the metadata in pyproject.toml (e.g. authors, version)
115+
1. If you're using a private repository, configure it with Poetry
116+
1. `poetry config repositories.<your-repository-name> <url-to-your-repository>`
117+
1. `poetry config http-basic.<your-repository-name> <username> <password>`
118+
1. Publish the client with `poetry publish --build -r <your-repository-name>` or, if for public PyPI, just `poetry publish --build`
119+
120+
If you want to install this client into another project without publishing it (e.g. for development) then:
121+
1. If that project **is using Poetry**, you can simply do `poetry add <path-to-this-client>` from that project
122+
1. If that project is not using Poetry:
123+
1. Build a wheel with `poetry build -f wheel`
124+
1. Install that wheel from the other project `pip install <path-to-wheel>`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
"""A client library for accessing My Enum API"""
2+
3+
from .client import AuthenticatedClient, Client
4+
5+
__all__ = (
6+
"AuthenticatedClient",
7+
"Client",
8+
)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"""Contains methods for accessing the API"""

end_to_end_tests/literal-enums-golden-record/my_enum_api_client/api/enums/__init__.py

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
from http import HTTPStatus
2+
from typing import Any, Dict, Optional, Union
3+
4+
import httpx
5+
6+
from ... import errors
7+
from ...client import AuthenticatedClient, Client
8+
from ...types import UNSET, Response
9+
10+
11+
def _get_kwargs(
12+
*,
13+
bool_enum: bool,
14+
) -> Dict[str, Any]:
15+
params: Dict[str, Any] = {}
16+
17+
params["bool_enum"] = bool_enum
18+
19+
params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
20+
21+
_kwargs: Dict[str, Any] = {
22+
"method": "post",
23+
"url": "/enum/bool",
24+
"params": params,
25+
}
26+
27+
return _kwargs
28+
29+
30+
def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Any]:
31+
if response.status_code == HTTPStatus.OK:
32+
return None
33+
if client.raise_on_unexpected_status:
34+
raise errors.UnexpectedStatus(response.status_code, response.content)
35+
else:
36+
return None
37+
38+
39+
def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Any]:
40+
return Response(
41+
status_code=HTTPStatus(response.status_code),
42+
content=response.content,
43+
headers=response.headers,
44+
parsed=_parse_response(client=client, response=response),
45+
)
46+
47+
48+
def sync_detailed(
49+
*,
50+
client: Union[AuthenticatedClient, Client],
51+
bool_enum: bool,
52+
) -> Response[Any]:
53+
"""Bool Enum
54+
55+
Args:
56+
bool_enum (bool):
57+
58+
Raises:
59+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
60+
httpx.TimeoutException: If the request takes longer than Client.timeout.
61+
62+
Returns:
63+
Response[Any]
64+
"""
65+
66+
kwargs = _get_kwargs(
67+
bool_enum=bool_enum,
68+
)
69+
70+
response = client.get_httpx_client().request(
71+
**kwargs,
72+
)
73+
74+
return _build_response(client=client, response=response)
75+
76+
77+
async def asyncio_detailed(
78+
*,
79+
client: Union[AuthenticatedClient, Client],
80+
bool_enum: bool,
81+
) -> Response[Any]:
82+
"""Bool Enum
83+
84+
Args:
85+
bool_enum (bool):
86+
87+
Raises:
88+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
89+
httpx.TimeoutException: If the request takes longer than Client.timeout.
90+
91+
Returns:
92+
Response[Any]
93+
"""
94+
95+
kwargs = _get_kwargs(
96+
bool_enum=bool_enum,
97+
)
98+
99+
response = await client.get_async_httpx_client().request(**kwargs)
100+
101+
return _build_response(client=client, response=response)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
from http import HTTPStatus
2+
from typing import Any, Dict, Optional, Union
3+
4+
import httpx
5+
6+
from ... import errors
7+
from ...client import AuthenticatedClient, Client
8+
from ...models.an_int_enum import AnIntEnum
9+
from ...types import UNSET, Response
10+
11+
12+
def _get_kwargs(
13+
*,
14+
int_enum: AnIntEnum,
15+
) -> Dict[str, Any]:
16+
params: Dict[str, Any] = {}
17+
18+
json_int_enum: int = int_enum
19+
params["int_enum"] = json_int_enum
20+
21+
params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
22+
23+
_kwargs: Dict[str, Any] = {
24+
"method": "post",
25+
"url": "/enum/int",
26+
"params": params,
27+
}
28+
29+
return _kwargs
30+
31+
32+
def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Any]:
33+
if response.status_code == HTTPStatus.OK:
34+
return None
35+
if client.raise_on_unexpected_status:
36+
raise errors.UnexpectedStatus(response.status_code, response.content)
37+
else:
38+
return None
39+
40+
41+
def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Any]:
42+
return Response(
43+
status_code=HTTPStatus(response.status_code),
44+
content=response.content,
45+
headers=response.headers,
46+
parsed=_parse_response(client=client, response=response),
47+
)
48+
49+
50+
def sync_detailed(
51+
*,
52+
client: Union[AuthenticatedClient, Client],
53+
int_enum: AnIntEnum,
54+
) -> Response[Any]:
55+
"""Int Enum
56+
57+
Args:
58+
int_enum (AnIntEnum): An enumeration.
59+
60+
Raises:
61+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
62+
httpx.TimeoutException: If the request takes longer than Client.timeout.
63+
64+
Returns:
65+
Response[Any]
66+
"""
67+
68+
kwargs = _get_kwargs(
69+
int_enum=int_enum,
70+
)
71+
72+
response = client.get_httpx_client().request(
73+
**kwargs,
74+
)
75+
76+
return _build_response(client=client, response=response)
77+
78+
79+
async def asyncio_detailed(
80+
*,
81+
client: Union[AuthenticatedClient, Client],
82+
int_enum: AnIntEnum,
83+
) -> Response[Any]:
84+
"""Int Enum
85+
86+
Args:
87+
int_enum (AnIntEnum): An enumeration.
88+
89+
Raises:
90+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
91+
httpx.TimeoutException: If the request takes longer than Client.timeout.
92+
93+
Returns:
94+
Response[Any]
95+
"""
96+
97+
kwargs = _get_kwargs(
98+
int_enum=int_enum,
99+
)
100+
101+
response = await client.get_async_httpx_client().request(**kwargs)
102+
103+
return _build_response(client=client, response=response)

end_to_end_tests/literal-enums-golden-record/my_enum_api_client/api/tests/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)