@kattebak/openapi-generator-ts 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +189 -0
  3. package/dist/cli/commands/generate.d.ts +23 -0
  4. package/dist/cli/commands/generate.d.ts.map +1 -0
  5. package/dist/cli/commands/generate.js +116 -0
  6. package/dist/cli/commands/generate.js.map +1 -0
  7. package/dist/cli/commands/list.d.ts +2 -0
  8. package/dist/cli/commands/list.d.ts.map +1 -0
  9. package/dist/cli/commands/list.js +26 -0
  10. package/dist/cli/commands/list.js.map +1 -0
  11. package/dist/cli/commands/validate.d.ts +6 -0
  12. package/dist/cli/commands/validate.d.ts.map +1 -0
  13. package/dist/cli/commands/validate.js +80 -0
  14. package/dist/cli/commands/validate.js.map +1 -0
  15. package/dist/cli/convert-template.d.ts +31 -0
  16. package/dist/cli/convert-template.d.ts.map +1 -0
  17. package/dist/cli/convert-template.js +204 -0
  18. package/dist/cli/convert-template.js.map +1 -0
  19. package/dist/cli/convert-template.test.d.ts +2 -0
  20. package/dist/cli/convert-template.test.d.ts.map +1 -0
  21. package/dist/cli/convert-template.test.js +74 -0
  22. package/dist/cli/convert-template.test.js.map +1 -0
  23. package/dist/cli/index.d.ts +3 -0
  24. package/dist/cli/index.d.ts.map +1 -0
  25. package/dist/cli/index.js +246 -0
  26. package/dist/cli/index.js.map +1 -0
  27. package/dist/core/config.d.ts +252 -0
  28. package/dist/core/config.d.ts.map +1 -0
  29. package/dist/core/config.js +31 -0
  30. package/dist/core/config.js.map +1 -0
  31. package/dist/core/generator.d.ts +99 -0
  32. package/dist/core/generator.d.ts.map +1 -0
  33. package/dist/core/generator.js +492 -0
  34. package/dist/core/generator.js.map +1 -0
  35. package/dist/core/index.d.ts +4 -0
  36. package/dist/core/index.d.ts.map +1 -0
  37. package/dist/core/index.js +4 -0
  38. package/dist/core/index.js.map +1 -0
  39. package/dist/core/types.d.ts +47 -0
  40. package/dist/core/types.d.ts.map +1 -0
  41. package/dist/core/types.js +5 -0
  42. package/dist/core/types.js.map +1 -0
  43. package/dist/generators/generators.test.d.ts +6 -0
  44. package/dist/generators/generators.test.d.ts.map +1 -0
  45. package/dist/generators/generators.test.js +247 -0
  46. package/dist/generators/generators.test.js.map +1 -0
  47. package/dist/generators/go.d.ts +10 -0
  48. package/dist/generators/go.d.ts.map +1 -0
  49. package/dist/generators/go.js +327 -0
  50. package/dist/generators/go.js.map +1 -0
  51. package/dist/generators/index.d.ts +29 -0
  52. package/dist/generators/index.d.ts.map +1 -0
  53. package/dist/generators/index.js +58 -0
  54. package/dist/generators/index.js.map +1 -0
  55. package/dist/generators/php.d.ts +14 -0
  56. package/dist/generators/php.d.ts.map +1 -0
  57. package/dist/generators/php.js +241 -0
  58. package/dist/generators/php.js.map +1 -0
  59. package/dist/generators/python.d.ts +10 -0
  60. package/dist/generators/python.d.ts.map +1 -0
  61. package/dist/generators/python.js +273 -0
  62. package/dist/generators/python.js.map +1 -0
  63. package/dist/generators/typescript-fetch.d.ts +14 -0
  64. package/dist/generators/typescript-fetch.d.ts.map +1 -0
  65. package/dist/generators/typescript-fetch.js +217 -0
  66. package/dist/generators/typescript-fetch.js.map +1 -0
  67. package/dist/index.d.ts +14 -0
  68. package/dist/index.d.ts.map +1 -0
  69. package/dist/index.js +16 -0
  70. package/dist/index.js.map +1 -0
  71. package/dist/models/codegen-model.d.ts +123 -0
  72. package/dist/models/codegen-model.d.ts.map +1 -0
  73. package/dist/models/codegen-model.js +64 -0
  74. package/dist/models/codegen-model.js.map +1 -0
  75. package/dist/models/codegen-model.test.d.ts +6 -0
  76. package/dist/models/codegen-model.test.d.ts.map +1 -0
  77. package/dist/models/codegen-model.test.js +143 -0
  78. package/dist/models/codegen-model.test.js.map +1 -0
  79. package/dist/models/codegen-operation.d.ts +95 -0
  80. package/dist/models/codegen-operation.d.ts.map +1 -0
  81. package/dist/models/codegen-operation.js +54 -0
  82. package/dist/models/codegen-operation.js.map +1 -0
  83. package/dist/models/codegen-parameter.d.ts +86 -0
  84. package/dist/models/codegen-parameter.d.ts.map +1 -0
  85. package/dist/models/codegen-parameter.js +47 -0
  86. package/dist/models/codegen-parameter.js.map +1 -0
  87. package/dist/models/codegen-property.d.ts +95 -0
  88. package/dist/models/codegen-property.d.ts.map +1 -0
  89. package/dist/models/codegen-property.js +47 -0
  90. package/dist/models/codegen-property.js.map +1 -0
  91. package/dist/models/codegen-response.d.ts +64 -0
  92. package/dist/models/codegen-response.d.ts.map +1 -0
  93. package/dist/models/codegen-response.js +42 -0
  94. package/dist/models/codegen-response.js.map +1 -0
  95. package/dist/models/codegen-security.d.ts +34 -0
  96. package/dist/models/codegen-security.d.ts.map +1 -0
  97. package/dist/models/codegen-security.js +18 -0
  98. package/dist/models/codegen-security.js.map +1 -0
  99. package/dist/models/index.d.ts +8 -0
  100. package/dist/models/index.d.ts.map +1 -0
  101. package/dist/models/index.js +7 -0
  102. package/dist/models/index.js.map +1 -0
  103. package/dist/parser/index.d.ts +4 -0
  104. package/dist/parser/index.d.ts.map +1 -0
  105. package/dist/parser/index.js +4 -0
  106. package/dist/parser/index.js.map +1 -0
  107. package/dist/parser/openapi-parser.d.ts +71 -0
  108. package/dist/parser/openapi-parser.d.ts.map +1 -0
  109. package/dist/parser/openapi-parser.js +195 -0
  110. package/dist/parser/openapi-parser.js.map +1 -0
  111. package/dist/parser/openapi-parser.test.d.ts +6 -0
  112. package/dist/parser/openapi-parser.test.d.ts.map +1 -0
  113. package/dist/parser/openapi-parser.test.js +238 -0
  114. package/dist/parser/openapi-parser.test.js.map +1 -0
  115. package/dist/parser/operation-transformer.d.ts +95 -0
  116. package/dist/parser/operation-transformer.d.ts.map +1 -0
  117. package/dist/parser/operation-transformer.js +634 -0
  118. package/dist/parser/operation-transformer.js.map +1 -0
  119. package/dist/parser/schema-transformer.d.ts +134 -0
  120. package/dist/parser/schema-transformer.d.ts.map +1 -0
  121. package/dist/parser/schema-transformer.js +557 -0
  122. package/dist/parser/schema-transformer.js.map +1 -0
  123. package/dist/template/engine-adapter.d.ts +55 -0
  124. package/dist/template/engine-adapter.d.ts.map +1 -0
  125. package/dist/template/engine-adapter.js +178 -0
  126. package/dist/template/engine-adapter.js.map +1 -0
  127. package/dist/template/engine-adapter.test.d.ts +6 -0
  128. package/dist/template/engine-adapter.test.d.ts.map +1 -0
  129. package/dist/template/engine-adapter.test.js +186 -0
  130. package/dist/template/engine-adapter.test.js.map +1 -0
  131. package/dist/template/index.d.ts +5 -0
  132. package/dist/template/index.d.ts.map +1 -0
  133. package/dist/template/index.js +5 -0
  134. package/dist/template/index.js.map +1 -0
  135. package/dist/template/lambdas/indent-lambdas.d.ts +40 -0
  136. package/dist/template/lambdas/indent-lambdas.d.ts.map +1 -0
  137. package/dist/template/lambdas/indent-lambdas.js +98 -0
  138. package/dist/template/lambdas/indent-lambdas.js.map +1 -0
  139. package/dist/template/lambdas/index.d.ts +44 -0
  140. package/dist/template/lambdas/index.d.ts.map +1 -0
  141. package/dist/template/lambdas/index.js +79 -0
  142. package/dist/template/lambdas/index.js.map +1 -0
  143. package/dist/template/lambdas/string-lambdas.d.ts +78 -0
  144. package/dist/template/lambdas/string-lambdas.d.ts.map +1 -0
  145. package/dist/template/lambdas/string-lambdas.js +148 -0
  146. package/dist/template/lambdas/string-lambdas.js.map +1 -0
  147. package/dist/template/lambdas/string-lambdas.test.d.ts +6 -0
  148. package/dist/template/lambdas/string-lambdas.test.d.ts.map +1 -0
  149. package/dist/template/lambdas/string-lambdas.test.js +158 -0
  150. package/dist/template/lambdas/string-lambdas.test.js.map +1 -0
  151. package/dist/template/template-locator.d.ts +72 -0
  152. package/dist/template/template-locator.d.ts.map +1 -0
  153. package/dist/template/template-locator.js +173 -0
  154. package/dist/template/template-locator.js.map +1 -0
  155. package/dist/template/template-manager.d.ts +65 -0
  156. package/dist/template/template-manager.d.ts.map +1 -0
  157. package/dist/template/template-manager.js +185 -0
  158. package/dist/template/template-manager.js.map +1 -0
  159. package/package.json +67 -0
  160. package/templates/go/.travis.yml +8 -0
  161. package/templates/go/README.mustache +236 -0
  162. package/templates/go/api.mustache +452 -0
  163. package/templates/go/api_doc.mustache +92 -0
  164. package/templates/go/api_test.mustache +59 -0
  165. package/templates/go/client.mustache +761 -0
  166. package/templates/go/configuration.mustache +332 -0
  167. package/templates/go/git_push.sh.mustache +57 -0
  168. package/templates/go/gitignore.mustache +24 -0
  169. package/templates/go/go.mod.mustache +16 -0
  170. package/templates/go/go.sum.mustache +19 -0
  171. package/templates/go/model.mustache +21 -0
  172. package/templates/go/model_anyof.mustache +93 -0
  173. package/templates/go/model_doc.mustache +97 -0
  174. package/templates/go/model_enum.mustache +101 -0
  175. package/templates/go/model_oneof.mustache +160 -0
  176. package/templates/go/model_simple.mustache +572 -0
  177. package/templates/go/nullable_model.mustache +35 -0
  178. package/templates/go/openapi.mustache +1 -0
  179. package/templates/go/partial_header.mustache +18 -0
  180. package/templates/go/response.mustache +38 -0
  181. package/templates/go/signing.mustache +453 -0
  182. package/templates/go/utils.mustache +352 -0
  183. package/templates/php/.php-cs-fixer.dist.php +29 -0
  184. package/templates/php/.travis.yml +8 -0
  185. package/templates/php/ApiException.mustache +111 -0
  186. package/templates/php/Configuration.mustache +606 -0
  187. package/templates/php/FormDataProcessor.mustache +238 -0
  188. package/templates/php/HeaderSelector.mustache +265 -0
  189. package/templates/php/ModelInterface.mustache +103 -0
  190. package/templates/php/ObjectSerializer.mustache +591 -0
  191. package/templates/php/README.mustache +151 -0
  192. package/templates/php/api.mustache +891 -0
  193. package/templates/php/api_doc.mustache +105 -0
  194. package/templates/php/api_test.mustache +80 -0
  195. package/templates/php/composer.mustache +44 -0
  196. package/templates/php/git_push.sh.mustache +57 -0
  197. package/templates/php/gitignore +15 -0
  198. package/templates/php/libraries/psr-18/ApiException.mustache +114 -0
  199. package/templates/php/libraries/psr-18/DebugPlugin.mustache +93 -0
  200. package/templates/php/libraries/psr-18/README.mustache +161 -0
  201. package/templates/php/libraries/psr-18/api.mustache +833 -0
  202. package/templates/php/libraries/psr-18/api_doc.mustache +79 -0
  203. package/templates/php/libraries/psr-18/composer.mustache +56 -0
  204. package/templates/php/model.mustache +47 -0
  205. package/templates/php/model_doc.mustache +10 -0
  206. package/templates/php/model_enum.mustache +33 -0
  207. package/templates/php/model_generic.mustache +565 -0
  208. package/templates/php/model_test.mustache +88 -0
  209. package/templates/php/partial_header.mustache +18 -0
  210. package/templates/php/php_doc_auth_partial.mustache +23 -0
  211. package/templates/php/phpunit.xml.mustache +18 -0
  212. package/templates/python/README.mustache +60 -0
  213. package/templates/python/README_onlypackage.mustache +50 -0
  214. package/templates/python/__init__.mustache +1 -0
  215. package/templates/python/__init__api.mustache +19 -0
  216. package/templates/python/__init__model.mustache +22 -0
  217. package/templates/python/__init__package.mustache +49 -0
  218. package/templates/python/api.mustache +244 -0
  219. package/templates/python/api_client.mustache +822 -0
  220. package/templates/python/api_doc.mustache +81 -0
  221. package/templates/python/api_doc_example.mustache +38 -0
  222. package/templates/python/api_response.mustache +21 -0
  223. package/templates/python/api_test.mustache +48 -0
  224. package/templates/python/asyncio/rest.mustache +209 -0
  225. package/templates/python/common_README.mustache +85 -0
  226. package/templates/python/configuration.mustache +806 -0
  227. package/templates/python/exceptions.mustache +210 -0
  228. package/templates/python/exports_api.mustache +3 -0
  229. package/templates/python/exports_model.mustache +3 -0
  230. package/templates/python/exports_package.mustache +20 -0
  231. package/templates/python/git_push.sh.mustache +57 -0
  232. package/templates/python/github-workflow.mustache +35 -0
  233. package/templates/python/gitignore.mustache +66 -0
  234. package/templates/python/gitlab-ci.mustache +31 -0
  235. package/templates/python/httpx/rest.mustache +190 -0
  236. package/templates/python/model.mustache +16 -0
  237. package/templates/python/model_anyof.mustache +182 -0
  238. package/templates/python/model_doc.mustache +40 -0
  239. package/templates/python/model_enum.mustache +36 -0
  240. package/templates/python/model_generic.mustache +403 -0
  241. package/templates/python/model_oneof.mustache +209 -0
  242. package/templates/python/model_test.mustache +60 -0
  243. package/templates/python/partial_api.mustache +52 -0
  244. package/templates/python/partial_api_args.mustache +18 -0
  245. package/templates/python/partial_header.mustache +19 -0
  246. package/templates/python/py.typed.mustache +1 -0
  247. package/templates/python/pyproject.mustache +172 -0
  248. package/templates/python/python_doc_auth_partial.mustache +108 -0
  249. package/templates/python/requirements.mustache +23 -0
  250. package/templates/python/rest.mustache +254 -0
  251. package/templates/python/setup.mustache +60 -0
  252. package/templates/python/setup_cfg.mustache +2 -0
  253. package/templates/python/signing.mustache +422 -0
  254. package/templates/python/test-requirements.mustache +6 -0
  255. package/templates/python/tornado/rest.mustache +148 -0
  256. package/templates/python/tox.mustache +9 -0
  257. package/templates/python/travis.mustache +17 -0
  258. package/templates/typescript-fetch/ApiEntitiesRecord.mustache +26 -0
  259. package/templates/typescript-fetch/ApiEntitiesReducer.mustache +21 -0
  260. package/templates/typescript-fetch/ApiEntitiesSelectors.mustache +5 -0
  261. package/templates/typescript-fetch/README.mustache +127 -0
  262. package/templates/typescript-fetch/allSagas.mustache +19 -0
  263. package/templates/typescript-fetch/api_doc.mustache +63 -0
  264. package/templates/typescript-fetch/api_example.mustache +44 -0
  265. package/templates/typescript-fetch/apis.index.mustache +16 -0
  266. package/templates/typescript-fetch/apis.mustache +483 -0
  267. package/templates/typescript-fetch/apisAssignQueryParam.mustache +12 -0
  268. package/templates/typescript-fetch/gitignore +4 -0
  269. package/templates/typescript-fetch/index.mustache +17 -0
  270. package/templates/typescript-fetch/licenseInfo.mustache +11 -0
  271. package/templates/typescript-fetch/modelEnum.mustache +28 -0
  272. package/templates/typescript-fetch/modelEnumInterfaces.mustache +37 -0
  273. package/templates/typescript-fetch/modelGeneric.mustache +261 -0
  274. package/templates/typescript-fetch/modelGenericInterfaces.mustache +50 -0
  275. package/templates/typescript-fetch/modelOneOf.mustache +255 -0
  276. package/templates/typescript-fetch/modelOneOfInterfaces.mustache +6 -0
  277. package/templates/typescript-fetch/model_doc.mustache +41 -0
  278. package/templates/typescript-fetch/models.index.mustache +32 -0
  279. package/templates/typescript-fetch/models.mustache +24 -0
  280. package/templates/typescript-fetch/npmignore.mustache +1 -0
  281. package/templates/typescript-fetch/package.mustache +43 -0
  282. package/templates/typescript-fetch/recordGeneric.mustache +295 -0
  283. package/templates/typescript-fetch/records.mustache +17 -0
  284. package/templates/typescript-fetch/runtime.mustache +424 -0
  285. package/templates/typescript-fetch/runtimeSagasAndRecords.mustache +120 -0
  286. package/templates/typescript-fetch/sagaApiManager.mustache +28 -0
  287. package/templates/typescript-fetch/sagas.mustache +245 -0
  288. package/templates/typescript-fetch/sourceLibraryIndex.mustache +1 -0
  289. package/templates/typescript-fetch/tsconfig.esm.mustache +7 -0
  290. package/templates/typescript-fetch/tsconfig.mustache +25 -0
@@ -0,0 +1,822 @@
1
+ # coding: utf-8
2
+
3
+ {{>partial_header}}
4
+
5
+
6
+ import datetime
7
+ from dateutil.parser import parse
8
+ from enum import Enum
9
+ import decimal
10
+ import json
11
+ import mimetypes
12
+ import os
13
+ import re
14
+ import tempfile
15
+ import uuid
16
+
17
+ from urllib.parse import quote
18
+ from typing import Tuple, Optional, List, Dict, Union
19
+ from pydantic import SecretStr
20
+ {{#tornado}}
21
+ import tornado.gen
22
+ {{/tornado}}
23
+
24
+ from {{packageName}}.configuration import Configuration
25
+ from {{packageName}}.api_response import ApiResponse, T as ApiResponseT
26
+ import {{modelPackage}}
27
+ from {{packageName}} import rest
28
+ from {{packageName}}.exceptions import (
29
+ ApiValueError,
30
+ ApiException,
31
+ BadRequestException,
32
+ UnauthorizedException,
33
+ ForbiddenException,
34
+ NotFoundException,
35
+ ServiceException
36
+ )
37
+
38
+ RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
39
+
40
+ class ApiClient:
41
+ """Generic API client for OpenAPI client library builds.
42
+
43
+ OpenAPI generic API client. This client handles the client-
44
+ server communication, and is invariant across implementations. Specifics of
45
+ the methods and models for each application are generated from the OpenAPI
46
+ templates.
47
+
48
+ :param configuration: .Configuration object for this client
49
+ :param header_name: a header to pass when making calls to the API.
50
+ :param header_value: a header value to pass when making calls to
51
+ the API.
52
+ :param cookie: a cookie to include in the header when making calls
53
+ to the API
54
+ """
55
+
56
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
57
+ NATIVE_TYPES_MAPPING = {
58
+ 'int': int,
59
+ 'long': int, # TODO remove as only py3 is supported?
60
+ 'float': float,
61
+ 'str': str,
62
+ 'bool': bool,
63
+ 'date': datetime.date,
64
+ 'datetime': datetime.datetime,
65
+ 'decimal': decimal.Decimal,
66
+ 'object': object,
67
+ }
68
+ _pool = None
69
+
70
+ def __init__(
71
+ self,
72
+ configuration=None,
73
+ header_name=None,
74
+ header_value=None,
75
+ cookie=None
76
+ ) -> None:
77
+ # use default configuration if none is provided
78
+ if configuration is None:
79
+ configuration = Configuration.get_default()
80
+ self.configuration = configuration
81
+
82
+ self.rest_client = rest.RESTClientObject(configuration)
83
+ self.default_headers = {}
84
+ if header_name is not None:
85
+ self.default_headers[header_name] = header_value
86
+ self.cookie = cookie
87
+ # Set default User-Agent.
88
+ self.user_agent = '{{{httpUserAgent}}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/python{{/httpUserAgent}}'
89
+ self.client_side_validation = configuration.client_side_validation
90
+
91
+ {{#async}}
92
+ async def __aenter__(self):
93
+ return self
94
+
95
+ async def __aexit__(self, exc_type, exc_value, traceback):
96
+ await self.close()
97
+
98
+ async def close(self):
99
+ await self.rest_client.close()
100
+ {{/async}}
101
+ {{^async}}
102
+ def __enter__(self):
103
+ return self
104
+
105
+ def __exit__(self, exc_type, exc_value, traceback):
106
+ pass
107
+ {{/async}}
108
+
109
+ @property
110
+ def user_agent(self):
111
+ """User agent for this API client"""
112
+ return self.default_headers['User-Agent']
113
+
114
+ @user_agent.setter
115
+ def user_agent(self, value):
116
+ self.default_headers['User-Agent'] = value
117
+
118
+ def set_default_header(self, header_name, header_value):
119
+ self.default_headers[header_name] = header_value
120
+
121
+
122
+ _default = None
123
+
124
+ @classmethod
125
+ def get_default(cls):
126
+ """Return new instance of ApiClient.
127
+
128
+ This method returns newly created, based on default constructor,
129
+ object of ApiClient class or returns a copy of default
130
+ ApiClient.
131
+
132
+ :return: The ApiClient object.
133
+ """
134
+ if cls._default is None:
135
+ cls._default = ApiClient()
136
+ return cls._default
137
+
138
+ @classmethod
139
+ def set_default(cls, default):
140
+ """Set default instance of ApiClient.
141
+
142
+ It stores default ApiClient.
143
+
144
+ :param default: object of ApiClient.
145
+ """
146
+ cls._default = default
147
+
148
+ def param_serialize(
149
+ self,
150
+ method,
151
+ resource_path,
152
+ path_params=None,
153
+ query_params=None,
154
+ header_params=None,
155
+ body=None,
156
+ post_params=None,
157
+ files=None, auth_settings=None,
158
+ collection_formats=None,
159
+ _host=None,
160
+ _request_auth=None
161
+ ) -> RequestSerialized:
162
+
163
+ """Builds the HTTP request params needed by the request.
164
+ :param method: Method to call.
165
+ :param resource_path: Path to method endpoint.
166
+ :param path_params: Path parameters in the url.
167
+ :param query_params: Query parameters in the url.
168
+ :param header_params: Header parameters to be
169
+ placed in the request header.
170
+ :param body: Request body.
171
+ :param post_params dict: Request post form parameters,
172
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
173
+ :param auth_settings list: Auth Settings names for the request.
174
+ :param files dict: key -> filename, value -> filepath,
175
+ for `multipart/form-data`.
176
+ :param collection_formats: dict of collection formats for path, query,
177
+ header, and post parameters.
178
+ :param _request_auth: set to override the auth_settings for an a single
179
+ request; this effectively ignores the authentication
180
+ in the spec for a single request.
181
+ :return: tuple of form (path, http_method, query_params, header_params,
182
+ body, post_params, files)
183
+ """
184
+
185
+ config = self.configuration
186
+
187
+ # header parameters
188
+ header_params = header_params or {}
189
+ header_params.update(self.default_headers)
190
+ if self.cookie:
191
+ header_params['Cookie'] = self.cookie
192
+ if header_params:
193
+ header_params = self.sanitize_for_serialization(header_params)
194
+ header_params = dict(
195
+ self.parameters_to_tuples(header_params,collection_formats)
196
+ )
197
+
198
+ # path parameters
199
+ if path_params:
200
+ path_params = self.sanitize_for_serialization(path_params)
201
+ path_params = self.parameters_to_tuples(
202
+ path_params,
203
+ collection_formats
204
+ )
205
+ for k, v in path_params:
206
+ # specified safe chars, encode everything
207
+ resource_path = resource_path.replace(
208
+ '{%s}' % k,
209
+ quote(str(v), safe=config.safe_chars_for_path_param)
210
+ )
211
+
212
+ # post parameters
213
+ if post_params or files:
214
+ post_params = post_params if post_params else []
215
+ post_params = self.sanitize_for_serialization(post_params)
216
+ post_params = self.parameters_to_tuples(
217
+ post_params,
218
+ collection_formats
219
+ )
220
+ if files:
221
+ post_params.extend(self.files_parameters(files))
222
+
223
+ # auth setting
224
+ self.update_params_for_auth(
225
+ header_params,
226
+ query_params,
227
+ auth_settings,
228
+ resource_path,
229
+ method,
230
+ body,
231
+ request_auth=_request_auth
232
+ )
233
+
234
+ # body
235
+ if body:
236
+ body = self.sanitize_for_serialization(body)
237
+
238
+ # request url
239
+ if _host is None or self.configuration.ignore_operation_servers:
240
+ url = self.configuration.host + resource_path
241
+ else:
242
+ # use server/host defined in path or operation instead
243
+ url = _host + resource_path
244
+
245
+ # query parameters
246
+ if query_params:
247
+ query_params = self.sanitize_for_serialization(query_params)
248
+ url_query = self.parameters_to_url_query(
249
+ query_params,
250
+ collection_formats
251
+ )
252
+ url += "?" + url_query
253
+
254
+ return method, url, header_params, body, post_params
255
+
256
+
257
+ {{#tornado}}
258
+ @tornado.gen.coroutine
259
+ {{/tornado}}
260
+ {{#async}}async {{/async}}def call_api(
261
+ self,
262
+ method,
263
+ url,
264
+ header_params=None,
265
+ body=None,
266
+ post_params=None,
267
+ _request_timeout=None
268
+ ) -> rest.RESTResponse:
269
+ """Makes the HTTP request (synchronous)
270
+ :param method: Method to call.
271
+ :param url: Path to method endpoint.
272
+ :param header_params: Header parameters to be
273
+ placed in the request header.
274
+ :param body: Request body.
275
+ :param post_params dict: Request post form parameters,
276
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
277
+ :param _request_timeout: timeout setting for this request.
278
+ :return: RESTResponse
279
+ """
280
+
281
+ try:
282
+ # perform request and return response
283
+ response_data = {{#async}}await {{/async}}{{#tornado}}yield {{/tornado}}self.rest_client.request(
284
+ method, url,
285
+ headers=header_params,
286
+ body=body, post_params=post_params,
287
+ _request_timeout=_request_timeout
288
+ )
289
+
290
+ except ApiException as e:
291
+ raise e
292
+
293
+ return response_data
294
+
295
+ def response_deserialize(
296
+ self,
297
+ response_data: rest.RESTResponse,
298
+ response_types_map: Optional[Dict[str, ApiResponseT]]=None
299
+ ) -> ApiResponse[ApiResponseT]:
300
+ """Deserializes response into an object.
301
+ :param response_data: RESTResponse object to be deserialized.
302
+ :param response_types_map: dict of response types.
303
+ :return: ApiResponse
304
+ """
305
+
306
+ msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
307
+ assert response_data.data is not None, msg
308
+
309
+ response_type = response_types_map.get(str(response_data.status), None)
310
+ if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
311
+ # if not found, look for '1XX', '2XX', etc.
312
+ response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
313
+
314
+ # deserialize response data
315
+ response_text = None
316
+ return_data = None
317
+ try:
318
+ if response_type == "bytearray":
319
+ return_data = response_data.data
320
+ elif response_type == "file":
321
+ return_data = self.__deserialize_file(response_data)
322
+ elif response_type is not None:
323
+ match = None
324
+ content_type = response_data.headers.get('content-type')
325
+ if content_type is not None:
326
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
327
+ encoding = match.group(1) if match else "utf-8"
328
+ response_text = response_data.data.decode(encoding)
329
+ return_data = self.deserialize(response_text, response_type, content_type)
330
+ finally:
331
+ if not 200 <= response_data.status <= 299:
332
+ raise ApiException.from_response(
333
+ http_resp=response_data,
334
+ body=response_text,
335
+ data=return_data,
336
+ )
337
+
338
+ return ApiResponse(
339
+ status_code = response_data.status,
340
+ data = return_data,
341
+ headers = response_data.headers,
342
+ raw_data = response_data.data
343
+ )
344
+
345
+ def sanitize_for_serialization(self, obj):
346
+ """Builds a JSON POST object.
347
+
348
+ If obj is None, return None.
349
+ If obj is SecretStr, return obj.get_secret_value()
350
+ If obj is str, int, long, float, bool, return directly.
351
+ If obj is datetime.datetime, datetime.date
352
+ convert to string in iso8601 format.
353
+ If obj is decimal.Decimal return string representation.
354
+ If obj is list, sanitize each element in the list.
355
+ If obj is dict, return the dict.
356
+ If obj is OpenAPI model, return the properties dict.
357
+
358
+ :param obj: The data to serialize.
359
+ :return: The serialized form of data.
360
+ """
361
+ if obj is None:
362
+ return None
363
+ elif isinstance(obj, Enum):
364
+ return obj.value
365
+ elif isinstance(obj, SecretStr):
366
+ return obj.get_secret_value()
367
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
368
+ return obj
369
+ elif isinstance(obj, uuid.UUID):
370
+ return str(obj)
371
+ elif isinstance(obj, list):
372
+ return [
373
+ self.sanitize_for_serialization(sub_obj) for sub_obj in obj
374
+ ]
375
+ elif isinstance(obj, tuple):
376
+ return tuple(
377
+ self.sanitize_for_serialization(sub_obj) for sub_obj in obj
378
+ )
379
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
380
+ return obj.isoformat()
381
+ elif isinstance(obj, decimal.Decimal):
382
+ return str(obj)
383
+
384
+ elif isinstance(obj, dict):
385
+ obj_dict = obj
386
+ else:
387
+ # Convert model obj to dict except
388
+ # attributes `openapi_types`, `attribute_map`
389
+ # and attributes which value is not None.
390
+ # Convert attribute name to json key in
391
+ # model definition for request.
392
+ if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')):
393
+ obj_dict = obj.to_dict()
394
+ else:
395
+ obj_dict = obj.__dict__
396
+
397
+ if isinstance(obj_dict, list):
398
+ # here we handle instances that can either be a list or something else, and only became a real list by calling to_dict()
399
+ return self.sanitize_for_serialization(obj_dict)
400
+
401
+ return {
402
+ key: self.sanitize_for_serialization(val)
403
+ for key, val in obj_dict.items()
404
+ }
405
+
406
+ def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]):
407
+ """Deserializes response into an object.
408
+
409
+ :param response: RESTResponse object to be deserialized.
410
+ :param response_type: class literal for
411
+ deserialized object, or string of class name.
412
+ :param content_type: content type of response.
413
+
414
+ :return: deserialized object.
415
+ """
416
+
417
+ # fetch data from response object
418
+ if content_type is None:
419
+ try:
420
+ data = json.loads(response_text)
421
+ except ValueError:
422
+ data = response_text
423
+ elif re.match(r'^application/(json|[\w!#$&.+\-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE):
424
+ if response_text == "":
425
+ data = ""
426
+ else:
427
+ data = json.loads(response_text)
428
+ elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE):
429
+ data = response_text
430
+ else:
431
+ raise ApiException(
432
+ status=0,
433
+ reason="Unsupported content type: {0}".format(content_type)
434
+ )
435
+
436
+ return self.__deserialize(data, response_type)
437
+
438
+ def __deserialize(self, data, klass):
439
+ """Deserializes dict, list, str into an object.
440
+
441
+ :param data: dict, list or str.
442
+ :param klass: class literal, or string of class name.
443
+
444
+ :return: object.
445
+ """
446
+ if data is None:
447
+ return None
448
+
449
+ if isinstance(klass, str):
450
+ if klass.startswith('List['):
451
+ m = re.match(r'List\[(.*)]', klass)
452
+ assert m is not None, "Malformed List type definition"
453
+ sub_kls = m.group(1)
454
+ return [self.__deserialize(sub_data, sub_kls)
455
+ for sub_data in data]
456
+
457
+ if klass.startswith('Dict['):
458
+ m = re.match(r'Dict\[([^,]*), (.*)]', klass)
459
+ assert m is not None, "Malformed Dict type definition"
460
+ sub_kls = m.group(2)
461
+ return {k: self.__deserialize(v, sub_kls)
462
+ for k, v in data.items()}
463
+
464
+ # convert str to class
465
+ if klass in self.NATIVE_TYPES_MAPPING:
466
+ klass = self.NATIVE_TYPES_MAPPING[klass]
467
+ else:
468
+ klass = getattr({{modelPackage}}, klass)
469
+
470
+ if klass in self.PRIMITIVE_TYPES:
471
+ return self.__deserialize_primitive(data, klass)
472
+ elif klass is object:
473
+ return self.__deserialize_object(data)
474
+ elif klass is datetime.date:
475
+ return self.__deserialize_date(data)
476
+ elif klass is datetime.datetime:
477
+ return self.__deserialize_datetime(data)
478
+ elif klass is decimal.Decimal:
479
+ return decimal.Decimal(data)
480
+ elif issubclass(klass, Enum):
481
+ return self.__deserialize_enum(data, klass)
482
+ else:
483
+ return self.__deserialize_model(data, klass)
484
+
485
+ def parameters_to_tuples(self, params, collection_formats):
486
+ """Get parameters as list of tuples, formatting collections.
487
+
488
+ :param params: Parameters as dict or list of two-tuples
489
+ :param dict collection_formats: Parameter collection formats
490
+ :return: Parameters as list of tuples, collections formatted
491
+ """
492
+ new_params: List[Tuple[str, str]] = []
493
+ if collection_formats is None:
494
+ collection_formats = {}
495
+ for k, v in params.items() if isinstance(params, dict) else params:
496
+ if k in collection_formats:
497
+ collection_format = collection_formats[k]
498
+ if collection_format == 'multi':
499
+ new_params.extend((k, value) for value in v)
500
+ else:
501
+ if collection_format == 'ssv':
502
+ delimiter = ' '
503
+ elif collection_format == 'tsv':
504
+ delimiter = '\t'
505
+ elif collection_format == 'pipes':
506
+ delimiter = '|'
507
+ else: # csv is the default
508
+ delimiter = ','
509
+ new_params.append(
510
+ (k, delimiter.join(str(value) for value in v)))
511
+ else:
512
+ new_params.append((k, v))
513
+ return new_params
514
+
515
+ def parameters_to_url_query(self, params, collection_formats):
516
+ """Get parameters as list of tuples, formatting collections.
517
+
518
+ :param params: Parameters as dict or list of two-tuples
519
+ :param dict collection_formats: Parameter collection formats
520
+ :return: URL query string (e.g. a=Hello%20World&b=123)
521
+ """
522
+ new_params: List[Tuple[str, str]] = []
523
+ if collection_formats is None:
524
+ collection_formats = {}
525
+ for k, v in params.items() if isinstance(params, dict) else params:
526
+ if isinstance(v, bool):
527
+ v = str(v).lower()
528
+ if isinstance(v, (int, float)):
529
+ v = str(v)
530
+ if isinstance(v, dict):
531
+ v = json.dumps(v)
532
+
533
+ if k in collection_formats:
534
+ collection_format = collection_formats[k]
535
+ if collection_format == 'multi':
536
+ new_params.extend((k, quote(str(value))) for value in v)
537
+ else:
538
+ if collection_format == 'ssv':
539
+ delimiter = ' '
540
+ elif collection_format == 'tsv':
541
+ delimiter = '\t'
542
+ elif collection_format == 'pipes':
543
+ delimiter = '|'
544
+ else: # csv is the default
545
+ delimiter = ','
546
+ new_params.append(
547
+ (k, delimiter.join(quote(str(value)) for value in v))
548
+ )
549
+ else:
550
+ new_params.append((k, quote(str(v))))
551
+
552
+ return "&".join(["=".join(map(str, item)) for item in new_params])
553
+
554
+ def files_parameters(
555
+ self,
556
+ files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]],
557
+ ):
558
+ """Builds form parameters.
559
+
560
+ :param files: File parameters.
561
+ :return: Form parameters with files.
562
+ """
563
+ params = []
564
+ for k, v in files.items():
565
+ if isinstance(v, str):
566
+ with open(v, 'rb') as f:
567
+ filename = os.path.basename(f.name)
568
+ filedata = f.read()
569
+ elif isinstance(v, bytes):
570
+ filename = k
571
+ filedata = v
572
+ elif isinstance(v, tuple):
573
+ filename, filedata = v
574
+ elif isinstance(v, list):
575
+ for file_param in v:
576
+ params.extend(self.files_parameters({k: file_param}))
577
+ continue
578
+ else:
579
+ raise ValueError("Unsupported file value")
580
+ mimetype = (
581
+ mimetypes.guess_type(filename)[0]
582
+ or 'application/octet-stream'
583
+ )
584
+ params.append(
585
+ tuple([k, tuple([filename, filedata, mimetype])])
586
+ )
587
+ return params
588
+
589
+ def select_header_accept(self, accepts: List[str]) -> Optional[str]:
590
+ """Returns `Accept` based on an array of accepts provided.
591
+
592
+ :param accepts: List of headers.
593
+ :return: Accept (e.g. application/json).
594
+ """
595
+ if not accepts:
596
+ return None
597
+
598
+ for accept in accepts:
599
+ if re.search('json', accept, re.IGNORECASE):
600
+ return accept
601
+
602
+ return accepts[0]
603
+
604
+ def select_header_content_type(self, content_types):
605
+ """Returns `Content-Type` based on an array of content_types provided.
606
+
607
+ :param content_types: List of content-types.
608
+ :return: Content-Type (e.g. application/json).
609
+ """
610
+ if not content_types:
611
+ return None
612
+
613
+ for content_type in content_types:
614
+ if re.search('json', content_type, re.IGNORECASE):
615
+ return content_type
616
+
617
+ return content_types[0]
618
+
619
+ def update_params_for_auth(
620
+ self,
621
+ headers,
622
+ queries,
623
+ auth_settings,
624
+ resource_path,
625
+ method,
626
+ body,
627
+ request_auth=None
628
+ ) -> None:
629
+ """Updates header and query params based on authentication setting.
630
+
631
+ :param headers: Header parameters dict to be updated.
632
+ :param queries: Query parameters tuple list to be updated.
633
+ :param auth_settings: Authentication setting identifiers list.
634
+ :resource_path: A string representation of the HTTP request resource path.
635
+ :method: A string representation of the HTTP request method.
636
+ :body: A object representing the body of the HTTP request.
637
+ The object type is the return value of sanitize_for_serialization().
638
+ :param request_auth: if set, the provided settings will
639
+ override the token in the configuration.
640
+ """
641
+ if not auth_settings:
642
+ return
643
+
644
+ if request_auth:
645
+ self._apply_auth_params(
646
+ headers,
647
+ queries,
648
+ resource_path,
649
+ method,
650
+ body,
651
+ request_auth
652
+ )
653
+ else:
654
+ for auth in auth_settings:
655
+ auth_setting = self.configuration.auth_settings().get(auth)
656
+ if auth_setting:
657
+ self._apply_auth_params(
658
+ headers,
659
+ queries,
660
+ resource_path,
661
+ method,
662
+ body,
663
+ auth_setting
664
+ )
665
+
666
+ def _apply_auth_params(
667
+ self,
668
+ headers,
669
+ queries,
670
+ resource_path,
671
+ method,
672
+ body,
673
+ auth_setting
674
+ ) -> None:
675
+ """Updates the request parameters based on a single auth_setting
676
+
677
+ :param headers: Header parameters dict to be updated.
678
+ :param queries: Query parameters tuple list to be updated.
679
+ :resource_path: A string representation of the HTTP request resource path.
680
+ :method: A string representation of the HTTP request method.
681
+ :body: A object representing the body of the HTTP request.
682
+ The object type is the return value of sanitize_for_serialization().
683
+ :param auth_setting: auth settings for the endpoint
684
+ """
685
+ if auth_setting['in'] == 'cookie':
686
+ headers['Cookie'] = auth_setting['value']
687
+ elif auth_setting['in'] == 'header':
688
+ if auth_setting['type'] != 'http-signature':
689
+ headers[auth_setting['key']] = auth_setting['value']
690
+ {{#hasHttpSignatureMethods}}
691
+ else:
692
+ # The HTTP signature scheme requires multiple HTTP headers
693
+ # that are calculated dynamically.
694
+ signing_info = self.configuration.signing_info
695
+ auth_headers = signing_info.get_http_signature_headers(
696
+ resource_path, method, headers, body, queries)
697
+ headers.update(auth_headers)
698
+ {{/hasHttpSignatureMethods}}
699
+ elif auth_setting['in'] == 'query':
700
+ queries.append((auth_setting['key'], auth_setting['value']))
701
+ else:
702
+ raise ApiValueError(
703
+ 'Authentication token must be in `query` or `header`'
704
+ )
705
+
706
+ def __deserialize_file(self, response):
707
+ """Deserializes body to file
708
+
709
+ Saves response body into a file in a temporary folder,
710
+ using the filename from the `Content-Disposition` header if provided.
711
+
712
+ handle file downloading
713
+ save response body into a tmp file and return the instance
714
+
715
+ :param response: RESTResponse.
716
+ :return: file path.
717
+ """
718
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
719
+ os.close(fd)
720
+ os.remove(path)
721
+
722
+ content_disposition = response.headers.get("Content-Disposition")
723
+ if content_disposition:
724
+ m = re.search(
725
+ r'filename=[\'"]?([^\'"\s]+)[\'"]?',
726
+ content_disposition
727
+ )
728
+ assert m is not None, "Unexpected 'content-disposition' header value"
729
+ filename = m.group(1)
730
+ path = os.path.join(os.path.dirname(path), filename)
731
+
732
+ with open(path, "wb") as f:
733
+ f.write(response.data)
734
+
735
+ return path
736
+
737
+ def __deserialize_primitive(self, data, klass):
738
+ """Deserializes string to primitive type.
739
+
740
+ :param data: str.
741
+ :param klass: class literal.
742
+
743
+ :return: int, long, float, str, bool.
744
+ """
745
+ try:
746
+ return klass(data)
747
+ except UnicodeEncodeError:
748
+ return str(data)
749
+ except TypeError:
750
+ return data
751
+
752
+ def __deserialize_object(self, value):
753
+ """Return an original value.
754
+
755
+ :return: object.
756
+ """
757
+ return value
758
+
759
+ def __deserialize_date(self, string):
760
+ """Deserializes string to date.
761
+
762
+ :param string: str.
763
+ :return: date.
764
+ """
765
+ try:
766
+ return parse(string).date()
767
+ except ImportError:
768
+ return string
769
+ except ValueError:
770
+ raise rest.ApiException(
771
+ status=0,
772
+ reason="Failed to parse `{0}` as date object".format(string)
773
+ )
774
+
775
+ def __deserialize_datetime(self, string):
776
+ """Deserializes string to datetime.
777
+
778
+ The string should be in iso8601 datetime format.
779
+
780
+ :param string: str.
781
+ :return: datetime.
782
+ """
783
+ try:
784
+ return parse(string)
785
+ except ImportError:
786
+ return string
787
+ except ValueError:
788
+ raise rest.ApiException(
789
+ status=0,
790
+ reason=(
791
+ "Failed to parse `{0}` as datetime object"
792
+ .format(string)
793
+ )
794
+ )
795
+
796
+ def __deserialize_enum(self, data, klass):
797
+ """Deserializes primitive type to enum.
798
+
799
+ :param data: primitive type.
800
+ :param klass: class literal.
801
+ :return: enum value.
802
+ """
803
+ try:
804
+ return klass(data)
805
+ except ValueError:
806
+ raise rest.ApiException(
807
+ status=0,
808
+ reason=(
809
+ "Failed to parse `{0}` as `{1}`"
810
+ .format(data, klass)
811
+ )
812
+ )
813
+
814
+ def __deserialize_model(self, data, klass):
815
+ """Deserializes list or dict to model.
816
+
817
+ :param data: dict, list.
818
+ :param klass: class literal.
819
+ :return: model object.
820
+ """
821
+
822
+ return klass.from_dict(data)