Skip to content

feat: Support responses with multiple media types in content #1293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,13 @@ content_type_overrides:
application/zip: application/octet-stream
```

### multiple_media_types

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.
This config tells the generator to check the `Content-Type` header of the response and parse the response accordingly.

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.

## Supported Extensions

### x-enum-varnames
Expand Down
23 changes: 23 additions & 0 deletions end_to_end_tests/multiple-media-types-golden-record/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
__pycache__/
build/
dist/
*.egg-info/
.pytest_cache/

# pyenv
.python-version

# Environments
.env
.venv

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# JetBrains
.idea/

/coverage.xml
/.coverage
124 changes: 124 additions & 0 deletions end_to_end_tests/multiple-media-types-golden-record/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# multiple-media-types-client
A client library for accessing Multiple media types

## Usage
First, create a client:

```python
from multiple_media_types_client import Client

client = Client(base_url="https://api.example.com")
```

If the endpoints you're going to hit require authentication, use `AuthenticatedClient` instead:

```python
from multiple_media_types_client import AuthenticatedClient

client = AuthenticatedClient(base_url="https://api.example.com", token="SuperSecretToken")
```

Now call your endpoint and use your models:

```python
from multiple_media_types_client.models import MyDataModel
from multiple_media_types_client.api.my_tag import get_my_data_model
from multiple_media_types_client.types import Response

with client as client:
my_data: MyDataModel = get_my_data_model.sync(client=client)
# or if you need more info (e.g. status_code)
response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client)
```

Or do the same thing with an async version:

```python
from multiple_media_types_client.models import MyDataModel
from multiple_media_types_client.api.my_tag import get_my_data_model
from multiple_media_types_client.types import Response

async with client as client:
my_data: MyDataModel = await get_my_data_model.asyncio(client=client)
response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client)
```

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.

```python
client = AuthenticatedClient(
base_url="https://internal_api.example.com",
token="SuperSecretToken",
verify_ssl="/path/to/certificate_bundle.pem",
)
```

You can also disable certificate validation altogether, but beware that **this is a security risk**.

```python
client = AuthenticatedClient(
base_url="https://internal_api.example.com",
token="SuperSecretToken",
verify_ssl=False
)
```

Things to know:
1. Every path/method combo becomes a Python module with four functions:
1. `sync`: Blocking request that returns parsed data (if successful) or `None`
1. `sync_detailed`: Blocking request that always returns a `Request`, optionally with `parsed` set if the request was successful.
1. `asyncio`: Like `sync` but async instead of blocking
1. `asyncio_detailed`: Like `sync_detailed` but async instead of blocking

1. All path/query params, and bodies become method arguments.
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)
1. Any endpoint which did not have a tag will be in `multiple_media_types_client.api.default`

## Advanced customizations

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):

```python
from multiple_media_types_client import Client

def log_request(request):
print(f"Request event hook: {request.method} {request.url} - Waiting for response")

def log_response(response):
request = response.request
print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")

client = Client(
base_url="https://api.example.com",
httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}},
)

# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client()
```

You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url):

```python
import httpx
from multiple_media_types_client import Client

client = Client(
base_url="https://api.example.com",
)
# Note that base_url needs to be re-set, as would any shared cookies, headers, etc.
client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030"))
```

## Building / publishing this package
This project uses [Poetry](https://python-poetry.org/) to manage dependencies and packaging. Here are the basics:
1. Update the metadata in pyproject.toml (e.g. authors, version)
1. If you're using a private repository, configure it with Poetry
1. `poetry config repositories.<your-repository-name> <url-to-your-repository>`
1. `poetry config http-basic.<your-repository-name> <username> <password>`
1. Publish the client with `poetry publish --build -r <your-repository-name>` or, if for public PyPI, just `poetry publish --build`

If you want to install this client into another project without publishing it (e.g. for development) then:
1. If that project **is using Poetry**, you can simply do `poetry add <path-to-this-client>` from that project
1. If that project is not using Poetry:
1. Build a wheel with `poetry build -f wheel`
1. Install that wheel from the other project `pip install <path-to-wheel>`
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""A client library for accessing Multiple media types"""

from .client import AuthenticatedClient, Client

__all__ = (
"AuthenticatedClient",
"Client",
)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Contains methods for accessing the API"""
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Contains endpoint functions for accessing the API"""
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
from http import HTTPStatus
from typing import Any, Literal, Optional, Union, cast

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.error_response import ErrorResponse
from ...types import Response


def _get_kwargs() -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "post",
"url": "/",
}

return _kwargs


def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
if response.status_code == 200:
response_200: Union[Literal["Why have a fixed response? I dunno"], Any]
if response.headers.get("content-type") == "application/json":
response_200 = cast(Literal["Why have a fixed response? I dunno"], response.json())
if response_200 != "Why have a fixed response? I dunno":
raise ValueError(
f"response_200 must match const 'Why have a fixed response? I dunno', got '{response_200}'"
)
return response_200
if response.headers.get("content-type") == "application/octet-stream":
response_200 = cast(Any, response.content)
return response_200
if response.status_code == 503:
response_503: Union[ErrorResponse, Any]
if response.headers.get("content-type") == "application/json":
response_503 = ErrorResponse.from_dict(response.json())

return response_503
if response.headers.get("content-type") == "text/plain":
response_503 = cast(Any, response.text)
return response_503
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None


def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)


def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
"""
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.

Returns:
Response[Union[Any, ErrorResponse, Literal['Why have a fixed response? I dunno']]]
"""

kwargs = _get_kwargs()

response = client.get_httpx_client().request(
**kwargs,
)

return _build_response(client=client, response=response)


def sync(
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
"""
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.

Returns:
Union[Any, ErrorResponse, Literal['Why have a fixed response? I dunno']]
"""

return sync_detailed(
client=client,
).parsed


async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
"""
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.

Returns:
Response[Union[Any, ErrorResponse, Literal['Why have a fixed response? I dunno']]]
"""

kwargs = _get_kwargs()

response = await client.get_async_httpx_client().request(**kwargs)

return _build_response(client=client, response=response)


async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, ErrorResponse, Literal["Why have a fixed response? I dunno"]]]:
"""
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.

Returns:
Union[Any, ErrorResponse, Literal['Why have a fixed response? I dunno']]
"""

return (
await asyncio_detailed(
client=client,
)
).parsed
Loading
Loading