Skip to content

Commit cf30e48

Browse files
committed
add option to use dataclasses instead of attrs
1 parent 40d63f9 commit cf30e48

22 files changed

+789
-22
lines changed

.changeset/use_dataclasses.md

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
default: minor
3+
---
4+
5+
# Add `use_dataclasses` config setting
6+
7+
Instead of using the `attrs` package in the generated code, you can choose to use the built-in `dataclasses` module by setting `use_dataclasses: true` in your config file. This may be useful if you are trying to reduce external dependencies, or if your client package might be used in applications that require different versions of `attrs`.
8+
9+
The generated client code should behave exactly the same from an application's point of view except for the following differences:
10+
11+
- The generated project file does not have an `attrs` dependency.
12+
- If you were using `attrs.evolve` to create an updated instance of a model class, you should use `dataclasses.replace` instead.
13+
- Undocumented attributes of the `Client` class that had an underscore prefix in their names are no longer available.
14+
- The builder methods `with_cookies`, `with_headers`, and `with_timeout` do _not_ modify any Httpx client that may have been created from the previous Client instance; they affect only the new instance.

CONTRIBUTING.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ If you think that some of the added code is not testable (or testing it would ad
5858

5959
This project aims to have all "happy paths" (types of code which _can_ be generated) covered by end to end tests (snapshot tests). In order to check code changes against the previous set of snapshots (called a "golden record" here), you can run `pdm e2e`. To regenerate the snapshots, run `pdm regen`.
6060

61-
There are 4 types of snapshots generated right now, you may have to update only some or all of these depending on the changes you're making. Within the `end_to_end_tets` directory:
61+
There are 4 types of snapshots generated right now, you may have to update only some or all of these depending on the changes you're making. Within the `end_to_end_tests` directory:
6262

6363
1. `baseline_openapi_3.0.json` creates `golden-record` for testing OpenAPI 3.0 features
6464
2. `baseline_openapi_3.1.yaml` is checked against `golden-record` for testing OpenAPI 3.1 features (and ensuring consistency with 3.0)

README.md

+11
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,17 @@ post_hooks:
150150
- "ruff format ."
151151
```
152152

153+
### use_dataclasses
154+
155+
By default, `openapi-python-client` uses the `attrs` package when generating model classes (and the `Client` class). Setting `use_dataclasses` to `true` causes it to use the built-in `dataclasses` module instead. This may be useful if you are trying to reduce external dependencies, or if your client package might be used in applications that require different versions of `attrs`.
156+
157+
The generated client code should behave exactly the same from an application's point of view except for the following differences:
158+
159+
- The generated project file does not have an `attrs` dependency.
160+
- If you were using `attrs.evolve` to create an updated instance of a model class, you should use `dataclasses.replace` instead.
161+
- Undocumented attributes of the `Client` class that had an underscore prefix in their names are no longer available.
162+
- The builder methods `with_cookies`, `with_headers`, and `with_timeout` do _not_ modify any Httpx client that may have been created from the previous Client instance; they affect only the new instance.
163+
153164
### use_path_prefixes_for_title_model_names
154165

155166
By default, `openapi-python-client` generates class names which include the full path to the schema, including any parent-types. This can result in very long class names like `MyRouteSomeClassAnotherClassResponse`—which is very unique and unlikely to cause conflicts with future API additions, but also super verbose.
+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
use_dataclasses: true
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-dataclasses-api-client
2+
A client library for accessing My Dataclasses API
3+
4+
## Usage
5+
First, create a client:
6+
7+
```python
8+
from my_dataclasses_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_dataclasses_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_dataclasses_api_client.models import MyDataModel
25+
from my_dataclasses_api_client.api.my_tag import get_my_data_model
26+
from my_dataclasses_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_dataclasses_api_client.models import MyDataModel
38+
from my_dataclasses_api_client.api.my_tag import get_my_data_model
39+
from my_dataclasses_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_dataclasses_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_dataclasses_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_dataclasses_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 Dataclasses 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"""

0 commit comments

Comments
 (0)