Skip to content

Commit 4d8f6ee

Browse files
committed
feat: Add support for responses with multiple media types in content
1 parent 1bbbaf3 commit 4d8f6ee

File tree

26 files changed

+1022
-75
lines changed

26 files changed

+1022
-75
lines changed

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,13 @@ content_type_overrides:
192192
application/zip: application/octet-stream
193193
```
194194

195+
### multiple_media_types
196+
197+
OpenAPI documents may have more than one media type for a response. By default, `openapi-python-client` only generates a response body parser for the first one it encounters.
198+
This config tells the generator to check the `Content-Type` header of the response and parse the response accordingly.
199+
200+
For example, this might be useful if an OpenAPI document models a service that returns 503 with a JSON error description when a downstream service fails, but is behind a load balancer that returns 503 with plain text when overloaded.
201+
195202
## Supported Extensions
196203

197204
### x-enum-varnames
Lines changed: 23 additions & 0 deletions
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
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# multiple-media-types-client
2+
A client library for accessing Multiple media types
3+
4+
## Usage
5+
First, create a client:
6+
7+
```python
8+
from multiple_media_types_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 multiple_media_types_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 multiple_media_types_client.models import MyDataModel
25+
from multiple_media_types_client.api.my_tag import get_my_data_model
26+
from multiple_media_types_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 multiple_media_types_client.models import MyDataModel
38+
from multiple_media_types_client.api.my_tag import get_my_data_model
39+
from multiple_media_types_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 `multiple_media_types_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 multiple_media_types_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 multiple_media_types_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>`
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
"""A client library for accessing Multiple media types"""
2+
3+
from .client import AuthenticatedClient, Client
4+
5+
__all__ = (
6+
"AuthenticatedClient",
7+
"Client",
8+
)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"""Contains methods for accessing the API"""
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"""Contains endpoint functions for accessing the API"""
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
from http import HTTPStatus
2+
from typing import Any, Literal, Optional, Union, cast
3+
4+
import httpx
5+
6+
from ... import errors
7+
from ...client import AuthenticatedClient, Client
8+
from ...models.error_response import ErrorResponse
9+
from ...types import Response
10+
11+
12+
def _get_kwargs() -> dict[str, Any]:
13+
_kwargs: dict[str, Any] = {
14+
"method": "post",
15+
"url": "/",
16+
}
17+
18+
return _kwargs
19+
20+
21+
def _parse_response(
22+
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
23+
) -> Optional[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
24+
if response.status_code == 200:
25+
response_200: Union[Literal["Why have a fixed response? I dunno"] | Any]
26+
if response.headers.get("content-type") == "application/json":
27+
response_200 = cast(Literal["Why have a fixed response? I dunno"], response.json())
28+
if response_200 != "Why have a fixed response? I dunno":
29+
raise ValueError(
30+
f"response_200 must match const 'Why have a fixed response? I dunno', got '{response_200}'"
31+
)
32+
return response_200
33+
if response.headers.get("content-type") == "application/octet-stream":
34+
response_200 = cast(Any, response.content)
35+
return response_200
36+
if response.status_code == 503:
37+
response_503: Union[ErrorResponse | Any]
38+
if response.headers.get("content-type") == "application/json":
39+
response_503 = ErrorResponse.from_dict(response.json())
40+
41+
return response_503
42+
if response.headers.get("content-type") == "text/plain":
43+
response_503 = cast(Any, response.text)
44+
return response_503
45+
if client.raise_on_unexpected_status:
46+
raise errors.UnexpectedStatus(response.status_code, response.content)
47+
else:
48+
return None
49+
50+
51+
def _build_response(
52+
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
53+
) -> Response[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
54+
return Response(
55+
status_code=HTTPStatus(response.status_code),
56+
content=response.content,
57+
headers=response.headers,
58+
parsed=_parse_response(client=client, response=response),
59+
)
60+
61+
62+
def sync_detailed(
63+
*,
64+
client: Union[AuthenticatedClient, Client],
65+
) -> Response[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
66+
"""
67+
Raises:
68+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
69+
httpx.TimeoutException: If the request takes longer than Client.timeout.
70+
71+
Returns:
72+
Response[Union[Any, ErrorResponse, Literal['Why have a fixed response? I dunno']]]
73+
"""
74+
75+
kwargs = _get_kwargs()
76+
77+
response = client.get_httpx_client().request(
78+
**kwargs,
79+
)
80+
81+
return _build_response(client=client, response=response)
82+
83+
84+
def sync(
85+
*,
86+
client: Union[AuthenticatedClient, Client],
87+
) -> Optional[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
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+
Union[Any, ErrorResponse, Literal['Why have a fixed response? I dunno']]
95+
"""
96+
97+
return sync_detailed(
98+
client=client,
99+
).parsed
100+
101+
102+
async def asyncio_detailed(
103+
*,
104+
client: Union[AuthenticatedClient, Client],
105+
) -> Response[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
106+
"""
107+
Raises:
108+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
109+
httpx.TimeoutException: If the request takes longer than Client.timeout.
110+
111+
Returns:
112+
Response[Union[Any, ErrorResponse, Literal['Why have a fixed response? I dunno']]]
113+
"""
114+
115+
kwargs = _get_kwargs()
116+
117+
response = await client.get_async_httpx_client().request(**kwargs)
118+
119+
return _build_response(client=client, response=response)
120+
121+
122+
async def asyncio(
123+
*,
124+
client: Union[AuthenticatedClient, Client],
125+
) -> Optional[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
126+
"""
127+
Raises:
128+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
129+
httpx.TimeoutException: If the request takes longer than Client.timeout.
130+
131+
Returns:
132+
Union[Any, ErrorResponse, Literal['Why have a fixed response? I dunno']]
133+
"""
134+
135+
return (
136+
await asyncio_detailed(
137+
client=client,
138+
)
139+
).parsed

0 commit comments

Comments
 (0)