Skip to content

Support binary request bodies for endpoints #899

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

Merged
merged 11 commits into from
Dec 7, 2023
Merged
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
11 changes: 11 additions & 0 deletions .changeset/support_applicationoctet_stream_request_bodies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
default: minor
---

# Support `application/octet-stream` request bodies

Endpoints that accept `application/octet-stream` request bodies are now supported using the same `File` type as octet-stream responses.

Thanks to @kgutwin for the implementation and @rtaycher for the discussion!

PR #899 closes #588
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
json_body_tests_json_body_post,
no_response_tests_no_response_get,
octet_stream_tests_octet_stream_get,
octet_stream_tests_octet_stream_post,
post_form_data,
post_form_data_inline,
post_tests_json_body_string,
Expand Down Expand Up @@ -118,6 +119,13 @@ def octet_stream_tests_octet_stream_get(cls) -> types.ModuleType:
"""
return octet_stream_tests_octet_stream_get

@classmethod
def octet_stream_tests_octet_stream_post(cls) -> types.ModuleType:
"""
Binary (octet stream) request body
"""
return octet_stream_tests_octet_stream_post

@classmethod
def no_response_tests_no_response_get(cls) -> types.ModuleType:
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
from http import HTTPStatus
from typing import Any, Dict, Optional, Union, cast

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...types import File, Response


def _get_kwargs(
*,
binary_body: File,
) -> Dict[str, Any]:
headers = {}
headers["Content-Type"] = binary_body.mime_type if binary_body.mime_type else "application/octet-stream"

return {
"method": "post",
"url": "/tests/octet_stream",
"content": binary_body.payload,
"headers": headers,
}


def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, str]]:
if response.status_code == HTTPStatus.OK:
response_200 = cast(str, response.json())
return response_200
if response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY:
response_422 = HTTPValidationError.from_dict(response.json())

return response_422
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[HTTPValidationError, str]]:
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],
binary_body: File,
) -> Response[Union[HTTPValidationError, str]]:
"""Binary (octet stream) request body

Args:
binary_body (File): A file to upload

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[HTTPValidationError, str]]
"""

kwargs = _get_kwargs(
binary_body=binary_body,
)

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

return _build_response(client=client, response=response)


def sync(
*,
client: Union[AuthenticatedClient, Client],
binary_body: File,
) -> Optional[Union[HTTPValidationError, str]]:
"""Binary (octet stream) request body

Args:
binary_body (File): A file to upload

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[HTTPValidationError, str]
"""

return sync_detailed(
client=client,
binary_body=binary_body,
).parsed


async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
binary_body: File,
) -> Response[Union[HTTPValidationError, str]]:
"""Binary (octet stream) request body

Args:
binary_body (File): A file to upload

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[HTTPValidationError, str]]
"""

kwargs = _get_kwargs(
binary_body=binary_body,
)

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

return _build_response(client=client, response=response)


async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
binary_body: File,
) -> Optional[Union[HTTPValidationError, str]]:
"""Binary (octet stream) request body

Args:
binary_body (File): A file to upload

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[HTTPValidationError, str]
"""

return (
await asyncio_detailed(
client=client,
binary_body=binary_body,
)
).parsed
40 changes: 40 additions & 0 deletions end_to_end_tests/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,46 @@
}
}
}
},
"post": {
"tags": [
"tests"
],
"summary": "Binary (octet stream) request body",
"operationId": "octet_stream_tests_octet_stream_post",
"requestBody": {
"content": {
"application/octet-stream": {
"schema": {
"description": "A file to upload",
"type": "string",
"format": "binary"
}
}
}
},
"responses": {
"200": {
"description": "success",
"content": {
"application/json": {
"schema": {
"type": "string"
}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
}
}
}
}
},
"/tests/no_response": {
Expand Down
Loading