Skip to content
This repository was archived by the owner on Dec 25, 2024. It is now read-only.

v2 adds generics, OpenApiResponse + ApiException updates #86

Merged
merged 6 commits into from
Nov 21, 2022
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io.swagger.v3.oas.models.tags.Tag;

import java.util.*;
import java.util.stream.Collectors;

public class CodegenOperation {
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
Expand All @@ -33,7 +34,7 @@ public class CodegenOperation {
hasErrorResponseObject; // if 4xx, 5xx responses have at least one error object defined
public CodegenProperty returnProperty;
public String path, operationId, returnType, returnFormat, httpMethod, returnBaseType,
returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse;
returnContainer, summary, unescapedNotes, notes, baseName;
public CodegenDiscriminator discriminator;
public List<Map<String, String>> consumes, produces, prioritizedContentTypes;
public List<CodegenServer> servers = new ArrayList<CodegenServer>();
Expand All @@ -51,6 +52,7 @@ public class CodegenOperation {
public List<CodegenSecurity> authMethods;
public List<Tag> tags;
public List<CodegenResponse> responses = new ArrayList<CodegenResponse>();
public CodegenResponse defaultResponse = null;
public List<CodegenCallback> callbacks = new ArrayList<>();
public Set<String> imports = new HashSet<String>();
public List<Map<String, String>> examples;
Expand Down Expand Up @@ -197,6 +199,10 @@ public boolean getAllResponsesAreErrors() {
return responses.stream().allMatch(response -> response.is4xx || response.is5xx);
}

public List<CodegenResponse> getNonDefaultResponses() {
return responses.stream().filter(response -> !response.isDefault).collect(Collectors.toList());
}

/**
* @return contentTypeToOperation
* returns a map where the key is the request body content type and the value is the current CodegenOperation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4076,7 +4076,6 @@ protected void handleMethodResponse(Operation operation,
op.examples = new ExampleGenerator(schemas, this.openAPI).generateFromResponseSchema(exampleStatusCode, responseSchema, getProducesInfo(this.openAPI, operation));
}

op.defaultResponse = toDefaultValue(responseSchema);
op.returnType = cm.dataType;
op.returnFormat = cm.dataFormat;
op.hasReference = schemas != null && schemas.containsKey(op.returnBaseType);
Expand Down Expand Up @@ -4214,6 +4213,7 @@ public CodegenOperation fromOperation(String path,
}
if (Boolean.TRUE.equals(r.isDefault)) {
op.defaultReturnType = Boolean.TRUE;
op.defaultResponse = r;
}
// check if any 4xx or 5xx response has an error response object defined
if ((Boolean.TRUE.equals(r.is4xx) || Boolean.TRUE.equals(r.is5xx)) && r.getContent() != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -932,12 +932,19 @@ class TypedDictInputVerifier:
)


class OpenApiResponse(JSONDetector, TypedDictInputVerifier):
T = typing.TypeVar("T")


@dataclasses.dataclass
class OpenApiResponse(JSONDetector, TypedDictInputVerifier, typing.Generic[T]):
__filename_content_disposition_pattern = re.compile('filename="(.+?)"')
response_cls: typing.Type[T]
content: typing.Optional[typing.Dict[str, MediaType]]
headers: typing.Optional[typing.Dict[str, HeaderParameterWithoutName]]

def __init__(
self,
response_cls: typing.Type[ApiResponse] = ApiResponse,
response_cls: typing.Type[T],
content: typing.Optional[typing.Dict[str, MediaType]] = None,
headers: typing.Optional[typing.Dict[str, HeaderParameterWithoutName]] = None,
):
Expand Down Expand Up @@ -1022,7 +1029,7 @@ class OpenApiResponse(JSONDetector, TypedDictInputVerifier):
for part in msg.get_payload()
}

def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> ApiResponse:
def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> T:
content_type = response.getheader('content-type')
deserialized_body = unset
streamed = response.supports_chunked_reads()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,25 @@ _servers = (
{{/unless}}
{{#unless isStub}}

_status_code_to_response = {
{{#each responses}}
{{#if isDefault}}
'default': response_for_default.response,
{{else}}
'{{code}}': response_for_{{code}}.response,

{{#if defaultResponse}}
default_response = response_for_default.response
{{/if}}
{{#if getNonDefaultResponses}}
__StatusCodeToResponse = typing_extensions.TypedDict(
'__StatusCodeToResponse',
{
{{#each getNonDefaultResponses}}
'{{code}}': api_client.OpenApiResponse[response_for_{{code}}.ApiResponse],
{{/each}}
}
)
_status_code_to_response = __StatusCodeToResponse({
{{#each getNonDefaultResponses}}
'{{code}}': response_for_{{code}}.response,
{{/each}}
}
})
{{/if}}
{{/unless}}
{{#each produces}}
{{#if @first}}
Expand Down Expand Up @@ -246,22 +256,35 @@ class BaseApi(api_client.Api):
if skip_deserialization:
api_response = api_client.ApiResponseWithoutDeserialization(response=response)
else:
response_for_status = _status_code_to_response.get(str(response.status))
if response_for_status:
api_response = response_for_status.deserialize(response, self.api_client.configuration)
{{#if getNonDefaultResponses}}
status = str(response.status)
if status in _status_code_to_response:
status: typing_extensions.Literal[
{{#each getNonDefaultResponses}}
'{{code}}',
{{/each}}
]
api_response = _status_code_to_response[status].deserialize(response, self.api_client.configuration)
else:
{{#if hasDefaultResponse}}
default_response = _status_code_to_response.get('default')
if default_response:
api_response = default_response.deserialize(response, self.api_client.configuration)
else:
api_response = api_client.ApiResponseWithoutDeserialization(response=response)
{{#if defaultResponse}}
api_response = default_response.deserialize(response, self.api_client.configuration)
{{else}}
api_response = api_client.ApiResponseWithoutDeserialization(response=response)
{{/if}}
{{else}}
{{#if defaultResponse}}
api_response = default_response.deserialize(response, self.api_client.configuration)
{{else}}
api_response = api_client.ApiResponseWithoutDeserialization(response=response)
{{/if}}
{{/if}}

if not 200 <= response.status <= 299:
raise exceptions.ApiException(api_response=api_response)
raise exceptions.ApiException(
status=response.status,
reason=response.reason,
api_response=api_response
)

return api_response

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# coding: utf-8

{{>partial_header}}
import dataclasses
import typing

from urllib3._collections import HTTPHeaderDict


class OpenApiException(Exception):
Expand Down Expand Up @@ -90,30 +94,25 @@ class ApiKeyError(OpenApiException, KeyError):
super(ApiKeyError, self).__init__(full_msg)


class ApiException(OpenApiException):
T = typing.TypeVar("T")

def __init__(self, status=None, reason=None, api_response: '{{packageName}}.api_client.ApiResponse' = None):
if api_response:
self.status = api_response.response.status
self.reason = api_response.response.reason
self.body = api_response.response.data
self.headers = api_response.response.getheaders()
else:
self.status = status
self.reason = reason
self.body = None
self.headers = None

@dataclasses.dataclass
class ApiException(OpenApiException, typing.Generic[T]):
status: int
reason: str
api_response: typing.Optional[T] = None

def __str__(self):
"""Custom error messages for exception"""
error_message = "({0})\n"\
"Reason: {1}\n".format(self.status, self.reason)
if self.headers:
error_message += "HTTP response headers: {0}\n".format(
self.headers)

if self.body:
error_message += "HTTP response body: {0}\n".format(self.body)
if self.api_response:
if self.api_response.response.getheaders():
error_message += "HTTP response headers: {0}\n".format(
self.api_response.response.getheaders())
if self.api_response.response.data:
error_message += "HTTP response body: {0}\n".format(self.api_response.response.data)

return error_message

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -936,12 +936,19 @@ def _verify_typed_dict_inputs_oapg(cls: typing.Type[typing_extensions.TypedDict]
)


class OpenApiResponse(JSONDetector, TypedDictInputVerifier):
T = typing.TypeVar("T")


@dataclasses.dataclass
class OpenApiResponse(JSONDetector, TypedDictInputVerifier, typing.Generic[T]):
__filename_content_disposition_pattern = re.compile('filename="(.+?)"')
response_cls: typing.Type[T]
content: typing.Optional[typing.Dict[str, MediaType]]
headers: typing.Optional[typing.Dict[str, HeaderParameterWithoutName]]

def __init__(
self,
response_cls: typing.Type[ApiResponse] = ApiResponse,
response_cls: typing.Type[T],
content: typing.Optional[typing.Dict[str, MediaType]] = None,
headers: typing.Optional[typing.Dict[str, HeaderParameterWithoutName]] = None,
):
Expand Down Expand Up @@ -1026,7 +1033,7 @@ def __deserialize_multipart_form_data(
for part in msg.get_payload()
}

def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> ApiResponse:
def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> T:
content_type = response.getheader('content-type')
deserialized_body = unset
streamed = response.supports_chunked_reads()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
The version of the OpenAPI document: 0.0.1
Generated by: https://openapi-generator.tech
"""
import dataclasses
import typing

from urllib3._collections import HTTPHeaderDict


class OpenApiException(Exception):
Expand Down Expand Up @@ -97,30 +101,25 @@ def __init__(self, msg, path_to_item=None):
super(ApiKeyError, self).__init__(full_msg)


class ApiException(OpenApiException):
T = typing.TypeVar("T")

def __init__(self, status=None, reason=None, api_response: 'unit_test_api.api_client.ApiResponse' = None):
if api_response:
self.status = api_response.response.status
self.reason = api_response.response.reason
self.body = api_response.response.data
self.headers = api_response.response.getheaders()
else:
self.status = status
self.reason = reason
self.body = None
self.headers = None

@dataclasses.dataclass
class ApiException(OpenApiException, typing.Generic[T]):
status: int
reason: str
api_response: typing.Optional[T] = None

def __str__(self):
"""Custom error messages for exception"""
error_message = "({0})\n"\
"Reason: {1}\n".format(self.status, self.reason)
if self.headers:
error_message += "HTTP response headers: {0}\n".format(
self.headers)

if self.body:
error_message += "HTTP response body: {0}\n".format(self.body)
if self.api_response:
if self.api_response.response.getheaders():
error_message += "HTTP response headers: {0}\n".format(
self.api_response.response.getheaders())
if self.api_response.response.data:
error_message += "HTTP response body: {0}\n".format(self.api_response.response.data)

return error_message

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,16 @@
from . import request_body


_status_code_to_response = {

__StatusCodeToResponse = typing_extensions.TypedDict(
'__StatusCodeToResponse',
{
'200': api_client.OpenApiResponse[response_for_200.ApiResponse],
}
)
_status_code_to_response = __StatusCodeToResponse({
'200': response_for_200.response,
}
})


class BaseApi(api_client.Api):
Expand Down Expand Up @@ -128,14 +135,21 @@ class instances
if skip_deserialization:
api_response = api_client.ApiResponseWithoutDeserialization(response=response)
else:
response_for_status = _status_code_to_response.get(str(response.status))
if response_for_status:
api_response = response_for_status.deserialize(response, self.api_client.configuration)
status = str(response.status)
if status in _status_code_to_response:
status: typing_extensions.Literal[
'200',
]
api_response = _status_code_to_response[status].deserialize(response, self.api_client.configuration)
else:
api_response = api_client.ApiResponseWithoutDeserialization(response=response)

if not 200 <= response.status <= 299:
raise exceptions.ApiException(api_response=api_response)
raise exceptions.ApiException(
status=response.status,
reason=response.reason,
api_response=api_response
)

return api_response

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,21 @@ class BaseApi(api_client.Api):
if skip_deserialization:
api_response = api_client.ApiResponseWithoutDeserialization(response=response)
else:
response_for_status = _status_code_to_response.get(str(response.status))
if response_for_status:
api_response = response_for_status.deserialize(response, self.api_client.configuration)
status = str(response.status)
if status in _status_code_to_response:
status: typing_extensions.Literal[
'200',
]
api_response = _status_code_to_response[status].deserialize(response, self.api_client.configuration)
else:
api_response = api_client.ApiResponseWithoutDeserialization(response=response)

if not 200 <= response.status <= 299:
raise exceptions.ApiException(api_response=api_response)
raise exceptions.ApiException(
status=response.status,
reason=response.reason,
api_response=api_response
)

return api_response

Expand Down
Loading