otterapi 0.2.0__tar.gz → 0.2.1__tar.gz

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 (126) hide show
  1. {otterapi-0.2.0 → otterapi-0.2.1}/PKG-INFO +18 -2
  2. {otterapi-0.2.0 → otterapi-0.2.1}/README.md +17 -1
  3. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/codegen.py +6 -0
  4. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/emit.py +8 -2
  5. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/endpoints.py +10 -1
  6. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/runtime/_serialization.py +77 -0
  7. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/splitting.py +7 -1
  8. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/utils.py +44 -0
  9. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/config.py +10 -0
  10. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_wire_format.py +140 -0
  11. {otterapi-0.2.0 → otterapi-0.2.1}/.gitignore +0 -0
  12. {otterapi-0.2.0 → otterapi-0.2.1}/LICENSE +0 -0
  13. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/__init__.py +0 -0
  14. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/__main__.py +0 -0
  15. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/cli.py +0 -0
  16. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/__init__.py +0 -0
  17. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/_body_builder.py +0 -0
  18. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/_features.py +0 -0
  19. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/_openapi_adapter.py +0 -0
  20. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/_pep695.py +0 -0
  21. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/ast_utils.py +0 -0
  22. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/auth.py +0 -0
  23. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/client.py +0 -0
  24. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/client_layout.py +0 -0
  25. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/dataframes.py +0 -0
  26. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/export.py +0 -0
  27. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/pagination.py +0 -0
  28. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/runtime/__init__.py +0 -0
  29. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/runtime/_client_stub.py.tpl +0 -0
  30. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/runtime/_concurrency.py +0 -0
  31. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/runtime/_dataframe.py +0 -0
  32. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/runtime/_export.py +0 -0
  33. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/runtime/_models_mixin.py +0 -0
  34. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/runtime/_pagination.py +0 -0
  35. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/runtime/_query.py +0 -0
  36. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/runtime/_retry.py +0 -0
  37. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/schema.py +0 -0
  38. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/codegen/types.py +0 -0
  39. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/exceptions.py +0 -0
  40. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/__init__.py +0 -0
  41. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/_lenient.py +0 -0
  42. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/constants.py +0 -0
  43. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v2/__init__.py +0 -0
  44. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v2/spec.json +0 -0
  45. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v2/v2.py +0 -0
  46. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v3/__init__.py +0 -0
  47. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v3/spec.json +0 -0
  48. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v3/v3.py +0 -0
  49. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v3_1/__init__.py +0 -0
  50. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v3_1/spec.json +0 -0
  51. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v3_1/v3_1.py +0 -0
  52. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v3_2/__init__.py +0 -0
  53. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v3_2/spec.json +0 -0
  54. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/v3_2/v3_2.py +0 -0
  55. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/openapi/warnings.py +0 -0
  56. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/py.typed +0 -0
  57. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/__init__.py +0 -0
  58. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/__init__.py +0 -0
  59. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/constraints/spec.yaml +0 -0
  60. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/dataframe/config.yaml +0 -0
  61. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/dataframe/spec.yaml +0 -0
  62. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/discriminator/spec.yaml +0 -0
  63. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/envelope/spec.yaml +0 -0
  64. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/envelope_optional/spec.yaml +0 -0
  65. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/nested/spec.yaml +0 -0
  66. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/paginated/config.yaml +0 -0
  67. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/paginated/spec.yaml +0 -0
  68. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/petstore/spec.json +0 -0
  69. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/petstore_v2/spec.json +0 -0
  70. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/real_world_patterns/spec.yaml +0 -0
  71. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/shadow/spec.yaml +0 -0
  72. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/golden/tagged/spec.yaml +0 -0
  73. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/real_specs/README.md +0 -0
  74. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/real_specs/github.openapi.json.gz +0 -0
  75. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/fixtures/real_specs/stripe.openapi.json.gz +0 -0
  76. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_ast_utils.py +0 -0
  77. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_atomic_generation.py +0 -0
  78. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_auth.py +0 -0
  79. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_body_builder.py +0 -0
  80. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_body_flatten.py +0 -0
  81. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_client_retry_lifecycle.py +0 -0
  82. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_client_style.py +0 -0
  83. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_codegen.py +0 -0
  84. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_codegen_consolidation.py +0 -0
  85. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_codegen_edge_cases.py +0 -0
  86. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_codegen_regressions.py +0 -0
  87. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_codegen_structure.py +0 -0
  88. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_concurrency_runtime.py +0 -0
  89. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_config_errors.py +0 -0
  90. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_dataframe.py +0 -0
  91. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_discriminated_union_runtime.py +0 -0
  92. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_discriminated_unions.py +0 -0
  93. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_empty_schema.py +0 -0
  94. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_error_response_types.py +0 -0
  95. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_exceptions.py +0 -0
  96. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_export.py +0 -0
  97. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_extra_forbid.py +0 -0
  98. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_feature_modules.py +0 -0
  99. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_generated_correctness.py +0 -0
  100. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_generated_hygiene.py +0 -0
  101. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_generated_typecheck.py +0 -0
  102. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_html_repr.py +0 -0
  103. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_init_scaffold.py +0 -0
  104. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_lenient.py +0 -0
  105. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_media_type_parameters.py +0 -0
  106. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_not_schema.py +0 -0
  107. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_nullable_upgrade.py +0 -0
  108. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_openapi_adapter.py +0 -0
  109. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_openapi_support.py +0 -0
  110. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_openapi_upgrade.py +0 -0
  111. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_pagination.py +0 -0
  112. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_pep695.py +0 -0
  113. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_per_status_errors.py +0 -0
  114. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_public_api.py +0 -0
  115. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_real_specs_smoke.py +0 -0
  116. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_recursive_schema.py +0 -0
  117. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_retry_runtime.py +0 -0
  118. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_runtime_guards.py +0 -0
  119. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_schema_constraints.py +0 -0
  120. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_smoke_generated_client.py +0 -0
  121. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_splitting_config.py +0 -0
  122. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_splitting_integration.py +0 -0
  123. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_splitting_resolver.py +0 -0
  124. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_splitting_tree.py +0 -0
  125. {otterapi-0.2.0 → otterapi-0.2.1}/otterapi/tests/test_unused_imports.py +0 -0
  126. {otterapi-0.2.0 → otterapi-0.2.1}/pyproject.toml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: otterapi
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: A cute otter that turns OpenAPI & Swagger specs into type-safe, async Python clients — powered by httpx and Pydantic.
5
5
  Project-URL: Source, https://github.com/danplischke/otterapi
6
6
  Author: Dan Plischke
@@ -61,7 +61,9 @@ Generated clients use [httpx2](https://github.com/pydantic/httpx2), pydantic's
61
61
  maintained fork of httpx (same API, package renamed), installed alongside
62
62
  otterapi. A custom `http_client` / `async_http_client` you pass in must be an
63
63
  `httpx2.Client` / `httpx2.AsyncClient`. Note that httpx2 verifies TLS against
64
- the operating system's trust store (`truststore`) rather than `certifi`.
64
+ the operating system's trust store (`truststore`) rather than `certifi`. To
65
+ generate clients that use the original `httpx` package instead, set
66
+ `http_library: httpx` (see [Document Options](#document-options)).
65
67
 
66
68
  ### Basic Usage
67
69
 
@@ -187,6 +189,7 @@ Each entry under `documents:` supports these fields:
187
189
  | `include_paths` | list | `null` | Glob patterns — only matching paths are generated |
188
190
  | `exclude_paths` | list | `null` | Glob patterns — matching paths are skipped (applied after `include_paths`) |
189
191
  | `target_python` | `3.11` … `3.14` | `3.11` | Oldest Python the generated code has to run on. `3.12`+ emits PEP 695 type parameters in the runtime helpers |
192
+ | `http_library` | `httpx2` \| `httpx` | `httpx2` | HTTP library the generated client imports. Use `httpx` if your project already depends on the original package (install it yourself; otterapi only ships `httpx2`) |
190
193
  | `pydantic_version` | `1` \| `2` | `2` | Target Pydantic version for generated models and helpers |
191
194
 
192
195
  #### Function Naming
@@ -1167,6 +1170,19 @@ documents:
1167
1170
  place_order(body=Order(id=7)) # -> {"id": 7, "shipDate": null, "note": null}
1168
1171
  ```
1169
1172
 
1173
+ ### Multipart bodies
1174
+
1175
+ A `multipart/form-data` body is sent one part per property, following the
1176
+ OpenAPI Encoding Object defaults: `bytes` or file-like values become file
1177
+ uploads, arrays become one part per item under the same name, objects are sent
1178
+ as `application/json` parts, and everything else is sent as a plain text
1179
+ field. `None` values are left out, since multipart cannot express null.
1180
+
1181
+ ```python
1182
+ upload(body=Upload(name='a', tags=['x', 'y'], file=b'...'))
1183
+ # -> parts: name=a, tags=x, tags=y, file (upload)
1184
+ ```
1185
+
1170
1186
  ### Flattening the body into parameters
1171
1187
 
1172
1188
  By default a POST/PUT/PATCH takes the body as one model:
@@ -30,7 +30,9 @@ Generated clients use [httpx2](https://github.com/pydantic/httpx2), pydantic's
30
30
  maintained fork of httpx (same API, package renamed), installed alongside
31
31
  otterapi. A custom `http_client` / `async_http_client` you pass in must be an
32
32
  `httpx2.Client` / `httpx2.AsyncClient`. Note that httpx2 verifies TLS against
33
- the operating system's trust store (`truststore`) rather than `certifi`.
33
+ the operating system's trust store (`truststore`) rather than `certifi`. To
34
+ generate clients that use the original `httpx` package instead, set
35
+ `http_library: httpx` (see [Document Options](#document-options)).
34
36
 
35
37
  ### Basic Usage
36
38
 
@@ -156,6 +158,7 @@ Each entry under `documents:` supports these fields:
156
158
  | `include_paths` | list | `null` | Glob patterns — only matching paths are generated |
157
159
  | `exclude_paths` | list | `null` | Glob patterns — matching paths are skipped (applied after `include_paths`) |
158
160
  | `target_python` | `3.11` … `3.14` | `3.11` | Oldest Python the generated code has to run on. `3.12`+ emits PEP 695 type parameters in the runtime helpers |
161
+ | `http_library` | `httpx2` \| `httpx` | `httpx2` | HTTP library the generated client imports. Use `httpx` if your project already depends on the original package (install it yourself; otterapi only ships `httpx2`) |
159
162
  | `pydantic_version` | `1` \| `2` | `2` | Target Pydantic version for generated models and helpers |
160
163
 
161
164
  #### Function Naming
@@ -1136,6 +1139,19 @@ documents:
1136
1139
  place_order(body=Order(id=7)) # -> {"id": 7, "shipDate": null, "note": null}
1137
1140
  ```
1138
1141
 
1142
+ ### Multipart bodies
1143
+
1144
+ A `multipart/form-data` body is sent one part per property, following the
1145
+ OpenAPI Encoding Object defaults: `bytes` or file-like values become file
1146
+ uploads, arrays become one part per item under the same name, objects are sent
1147
+ as `application/json` parts, and everything else is sent as a plain text
1148
+ field. `None` values are left out, since multipart cannot express null.
1149
+
1150
+ ```python
1151
+ upload(body=Upload(name='a', tags=['x', 'y'], file=b'...'))
1152
+ # -> parts: name=a, tags=x, tags=y, file (upload)
1153
+ ```
1154
+
1139
1155
  ### Flattening the body into parameters
1140
1156
 
1141
1157
  By default a POST/PUT/PATCH takes the body as one model:
@@ -1212,6 +1212,7 @@ class Codegen(OpenAPIProcessor):
1212
1212
  path,
1213
1213
  format_code=self.format_output,
1214
1214
  validate_code=self.validate_output,
1215
+ http_module=self.config.http_library,
1215
1216
  )
1216
1217
  return set(names)
1217
1218
 
@@ -1290,6 +1291,7 @@ class Codegen(OpenAPIProcessor):
1290
1291
  directory / '_clients.py',
1291
1292
  format_code=self.format_output,
1292
1293
  validate_code=self.validate_output,
1294
+ http_module=self.config.http_library,
1293
1295
  )
1294
1296
 
1295
1297
  def _resource_path_of(
@@ -1549,6 +1551,7 @@ class Codegen(OpenAPIProcessor):
1549
1551
  path,
1550
1552
  format_code=self.format_output,
1551
1553
  validate_code=self.validate_output,
1554
+ http_module=self.config.http_library,
1552
1555
  )
1553
1556
 
1554
1557
  def generate(self):
@@ -1811,6 +1814,7 @@ class Codegen(OpenAPIProcessor):
1811
1814
  init_path,
1812
1815
  format_code=self.format_output,
1813
1816
  validate_code=self.validate_output,
1817
+ http_module=self.config.http_library,
1814
1818
  )
1815
1819
 
1816
1820
  def _generate_split_endpoints(
@@ -1872,6 +1876,7 @@ class Codegen(OpenAPIProcessor):
1872
1876
  root_reexport_names=root_reexport_names,
1873
1877
  format_output=self.format_output,
1874
1878
  validate_output=self.validate_output,
1879
+ http_module=self.config.http_library,
1875
1880
  )
1876
1881
 
1877
1882
  assert self.typegen is not None
@@ -1980,6 +1985,7 @@ class Codegen(OpenAPIProcessor):
1980
1985
  client_file,
1981
1986
  format_code=self.format_output,
1982
1987
  validate_code=self.validate_output,
1988
+ http_module=self.config.http_library,
1983
1989
  )
1984
1990
  generated_files.append(f'{output_name}/_client.py')
1985
1991
 
@@ -895,10 +895,16 @@ def finalize_file_imports(
895
895
  """
896
896
  sink.imports.add_imports({'.client': {'Client'}})
897
897
  # Registered optimistically: pruned away for modules that use
898
- # neither path parameters nor a flattened request body (see
898
+ # neither path parameters nor a flattened or multipart request body (see
899
899
  # write_mod's import pruning).
900
900
  sink.imports.add_imports(
901
- {'._serialization': {'format_path_param', 'build_request_body'}}
901
+ {
902
+ '._serialization': {
903
+ 'format_path_param',
904
+ 'build_request_body',
905
+ 'build_multipart_body',
906
+ }
907
+ }
902
908
  )
903
909
  for name in resolver.used_model_names(endpoints):
904
910
  sink.imports.add_imports({MODELS_MODULE: {name}})
@@ -731,7 +731,16 @@ class ParameterASTBuilder:
731
731
  if body.is_json and body.type and body.type.type in ('model', 'root'):
732
732
  body_expr = _body_value()
733
733
  elif body.is_multipart:
734
- body_expr = _name(body_name)
734
+ keywords: list[ast.keyword] = []
735
+ if not body.exclude_unset:
736
+ keywords.append(
737
+ ast.keyword(arg='exclude_unset', value=ast.Constant(value=False))
738
+ )
739
+ body_expr = _call(
740
+ func=_name('build_multipart_body'),
741
+ args=[_name(body_name)],
742
+ keywords=keywords,
743
+ )
735
744
  elif body.is_form:
736
745
  if body.type and body.type.type in ('model', 'root'):
737
746
  body_expr = _body_value()
@@ -19,16 +19,19 @@ header, and path -- puts the same bytes on the wire, including the
19
19
 
20
20
  from __future__ import annotations
21
21
 
22
+ import json
22
23
  from collections.abc import Mapping, Sequence
23
24
  from datetime import date, time
24
25
  from decimal import Decimal
25
26
  from enum import Enum
26
27
  from typing import Any
27
28
  from urllib.parse import quote
29
+ from uuid import UUID
28
30
 
29
31
  __all__ = [
30
32
  'NOTSET',
31
33
  'NotSet',
34
+ 'build_multipart_body',
32
35
  'build_request_body',
33
36
  'format_path_param',
34
37
  'serialize_headers',
@@ -258,6 +261,80 @@ def build_request_body(
258
261
  )
259
262
 
260
263
 
264
+ def _json_default(value: Any) -> Any:
265
+ if isinstance(value, Enum):
266
+ return value.value
267
+ if isinstance(value, (date, time)):
268
+ return value.isoformat()
269
+ if isinstance(value, (Decimal, UUID)):
270
+ return str(value)
271
+ raise TypeError(f'{type(value).__name__} is not JSON serializable')
272
+
273
+
274
+ def _is_file(value: Any) -> bool:
275
+ """True for values httpx should send as file content."""
276
+ return isinstance(value, (bytes, bytearray, tuple)) or callable(
277
+ getattr(value, 'read', None)
278
+ )
279
+
280
+
281
+ def _multipart_part(value: Any) -> Any:
282
+ """Render one non-array property value as an httpx ``files=`` entry."""
283
+ if _is_file(value):
284
+ return value
285
+ if isinstance(value, Mapping):
286
+ # Object-valued parts default to ``application/json``.
287
+ return (
288
+ None,
289
+ json.dumps(value, default=_json_default),
290
+ 'application/json',
291
+ )
292
+ # A ``None`` file name makes httpx send a plain form field, not an upload.
293
+ return (None, _scalar(value))
294
+
295
+
296
+ def build_multipart_body(
297
+ body: Any, *, exclude_unset: bool = True
298
+ ) -> list[tuple[str, Any]] | None:
299
+ """Turn a ``multipart/form-data`` body into httpx ``files=`` entries.
300
+
301
+ Every property goes through ``files=`` -- text fields with no file name --
302
+ so the request is multipart even when it carries no file. Array
303
+ properties become one part per item under the same name, as the OpenAPI
304
+ Encoding Object requires. ``None`` values are omitted: multipart has no
305
+ way to express null.
306
+
307
+ Args:
308
+ body: A generated model or a mapping of property name to value.
309
+ Anything else is assumed to be httpx-ready and passed through.
310
+ exclude_unset: Drop model fields the caller never set.
311
+
312
+ Returns:
313
+ A list of ``(name, value)`` pairs, or None when *body* is None.
314
+ """
315
+ if body is None:
316
+ return None
317
+ fields: Any
318
+ if isinstance(body, Mapping):
319
+ fields = body
320
+ elif callable(getattr(body, 'model_dump', None)):
321
+ # Python mode keeps ``bytes`` intact for file fields.
322
+ fields = body.model_dump(by_alias=True, exclude_unset=exclude_unset)
323
+ elif callable(getattr(body, 'dict', None)): # Pydantic v1
324
+ fields = body.dict(by_alias=True, exclude_unset=exclude_unset)
325
+ else:
326
+ return body
327
+ parts: list[tuple[str, Any]] = []
328
+ for name, value in fields.items():
329
+ if value is None:
330
+ continue
331
+ items = value if _is_sequence(value) and not _is_file(value) else [value]
332
+ parts.extend(
333
+ (name, _multipart_part(item)) for item in items if item is not None
334
+ )
335
+ return parts
336
+
337
+
261
338
  def format_path_param(
262
339
  value: Any,
263
340
  style: str = 'simple',
@@ -18,7 +18,7 @@ from typing import TYPE_CHECKING, cast
18
18
 
19
19
  from upath import UPath
20
20
 
21
- from otterapi.codegen.ast_utils import _all
21
+ from otterapi.codegen.ast_utils import HTTP_MODULE, _all
22
22
  from otterapi.codegen.emit import (
23
23
  EmitConfig,
24
24
  EmitSink,
@@ -632,6 +632,7 @@ class SplitModuleEmitter:
632
632
  root_reexport_names: list[str] | None = None,
633
633
  format_output: bool = True,
634
634
  validate_output: bool = True,
635
+ http_module: str = HTTP_MODULE,
635
636
  ):
636
637
  """Initialize the split module emitter.
637
638
 
@@ -662,6 +663,7 @@ class SplitModuleEmitter:
662
663
  ``__all__``.
663
664
  format_output: Whether to format generated code with ruff/black.
664
665
  validate_output: Whether to validate generated code syntax.
666
+ http_module: HTTP library the generated modules import.
665
667
  """
666
668
  self.config = config
667
669
  self.output_dir = UPath(output_dir)
@@ -687,6 +689,7 @@ class SplitModuleEmitter:
687
689
  self.root_reexport_names: list[str] = list(root_reexport_names or [])
688
690
  self.format_output = format_output
689
691
  self.validate_output = validate_output
692
+ self.http_module = http_module
690
693
  self._emitted_modules: list[EmittedModule] = []
691
694
  self._typegen_types: dict[str, Type] = {}
692
695
 
@@ -833,6 +836,7 @@ class SplitModuleEmitter:
833
836
  file_path,
834
837
  format_code=self.format_output,
835
838
  validate_code=self.validate_output,
839
+ http_module=self.http_module,
836
840
  )
837
841
 
838
842
  return endpoint_names
@@ -906,6 +910,7 @@ class SplitModuleEmitter:
906
910
  init_path,
907
911
  format_code=self.format_output,
908
912
  validate_code=self.validate_output,
913
+ http_module=self.http_module,
909
914
  )
910
915
  else:
911
916
  init_path.touch()
@@ -1045,6 +1050,7 @@ class SplitModuleEmitter:
1045
1050
  init_path,
1046
1051
  format_code=self.format_output,
1047
1052
  validate_code=self.validate_output,
1053
+ http_module=self.http_module,
1048
1054
  )
1049
1055
 
1050
1056
  def _get_model_names(self) -> list[str]:
@@ -10,6 +10,7 @@ from urllib.parse import urlparse
10
10
  from upath import UPath
11
11
 
12
12
  from otterapi.codegen.ast_utils import (
13
+ HTTP_MODULE,
13
14
  IMPORT_SECTION_SEPARATOR,
14
15
  find_unresolved_names,
15
16
  prune_unused_imports,
@@ -294,12 +295,51 @@ def format_source(source: str) -> str:
294
295
  return _add_blank_lines(source)
295
296
 
296
297
 
298
+ _HTTP_MODULE_WORD = re.compile(rf'\b{re.escape(HTTP_MODULE)}\b')
299
+
300
+
301
+ def _retarget_module_name(name: str, module: str) -> str:
302
+ if name == HTTP_MODULE or name.startswith(f'{HTTP_MODULE}.'):
303
+ return module + name[len(HTTP_MODULE) :]
304
+ return name
305
+
306
+
307
+ def retarget_http_module(body: list[ast.stmt], module: str) -> None:
308
+ """Point generated code at *module* instead of :data:`HTTP_MODULE`.
309
+
310
+ httpx2 is a renamed fork of httpx with the same public API, so switching
311
+ between them only touches import statements -- plus the docstrings that
312
+ name the library, so the generated documentation stays accurate.
313
+ """
314
+ if module == HTTP_MODULE:
315
+ return
316
+ for node in ast.walk(ast.Module(body=body, type_ignores=[])):
317
+ if isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
318
+ node.module = _retarget_module_name(node.module, module)
319
+ elif isinstance(node, ast.Import):
320
+ for alias in node.names:
321
+ alias.name = _retarget_module_name(alias.name, module)
322
+ elif isinstance(
323
+ node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)
324
+ ):
325
+ docstring = node.body[0] if node.body else None
326
+ if (
327
+ isinstance(docstring, ast.Expr)
328
+ and isinstance(docstring.value, ast.Constant)
329
+ and isinstance(docstring.value.value, str)
330
+ ):
331
+ docstring.value.value = _HTTP_MODULE_WORD.sub(
332
+ module, docstring.value.value
333
+ )
334
+
335
+
297
336
  def write_mod(
298
337
  body: list[ast.stmt],
299
338
  path: UPath | Path | str,
300
339
  format_code: bool = True,
301
340
  validate_code: bool = True,
302
341
  prune_imports: bool = True,
342
+ http_module: str = HTTP_MODULE,
303
343
  ) -> None:
304
344
  """Write a list of AST statements to a Python file.
305
345
 
@@ -328,6 +368,8 @@ def write_mod(
328
368
  format_code: Whether to format the code with ruff/black. Defaults to True.
329
369
  validate_code: Whether to validate the generated code. Defaults to True.
330
370
  prune_imports: Whether to drop unreferenced imports. Defaults to True.
371
+ http_module: HTTP library the generated code imports (``httpx2`` or
372
+ ``httpx``). Defaults to :data:`HTTP_MODULE`.
331
373
 
332
374
  Raises:
333
375
  SyntaxError: If the generated code is not valid Python (when validate_code=True).
@@ -341,6 +383,8 @@ def write_mod(
341
383
  if prune_imports:
342
384
  body = prune_unused_imports(body)
343
385
 
386
+ retarget_http_module(body, http_module)
387
+
344
388
  # Ordering is part of generation, not formatting: the generated package is
345
389
  # linted by the user's ruff, not this repo's, and an import block in
346
390
  # discovery order is an I001 finding in their tree.
@@ -1266,6 +1266,16 @@ class DocumentConfig(BaseModel):
1266
1266
  ),
1267
1267
  )
1268
1268
 
1269
+ http_library: Literal['httpx2', 'httpx'] = Field(
1270
+ default='httpx2',
1271
+ description=(
1272
+ 'HTTP library the generated client imports. "httpx2" is pydantic\'s '
1273
+ 'maintained fork of httpx 0.28.1 with the same API; choose "httpx" '
1274
+ 'for projects that already depend on the original package. The '
1275
+ 'generated package needs the chosen library installed.'
1276
+ ),
1277
+ )
1278
+
1269
1279
  pydantic_version: Literal[1, 2] = Field(
1270
1280
  default=2,
1271
1281
  description=(
@@ -14,6 +14,7 @@ Python-mode ``model_dump()`` on request bodies.
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
+ import ast
17
18
  import datetime
18
19
  import importlib
19
20
  import json
@@ -543,6 +544,92 @@ class TestRequestBody:
543
544
  assert rec.body == '{"id":3}'
544
545
 
545
546
 
547
+ def _multipart_spec() -> dict:
548
+ return _spec(
549
+ {
550
+ '/uploads': {
551
+ 'post': {
552
+ 'operationId': 'upload',
553
+ 'requestBody': {
554
+ 'required': True,
555
+ 'content': {
556
+ 'multipart/form-data': {
557
+ 'schema': {'$ref': '#/components/schemas/Upload'}
558
+ }
559
+ },
560
+ },
561
+ 'responses': _OK,
562
+ }
563
+ }
564
+ },
565
+ {
566
+ 'Upload': {
567
+ 'type': 'object',
568
+ 'properties': {
569
+ 'name': {'type': 'string'},
570
+ 'tags': {'type': 'array', 'items': {'type': 'string'}},
571
+ 'meta': {
572
+ 'type': 'object',
573
+ 'properties': {'n': {'type': 'integer'}},
574
+ },
575
+ 'file': {'type': 'string', 'format': 'binary'},
576
+ },
577
+ }
578
+ },
579
+ )
580
+
581
+
582
+ def _multipart_parts(request: httpx2.Request) -> list[tuple[str, str]]:
583
+ """``(Content-Disposition + Content-Type headers, payload)`` per part."""
584
+ content_type = request.headers['content-type']
585
+ assert content_type.startswith('multipart/form-data; boundary=')
586
+ boundary = content_type.split('boundary=', 1)[1]
587
+ raw = request.content.decode()
588
+ parts = []
589
+ for chunk in raw.split(f'--{boundary}')[1:-1]:
590
+ headers, _, payload = chunk.strip('\r\n').partition('\r\n\r\n')
591
+ parts.append((headers, payload))
592
+ return parts
593
+
594
+
595
+ class TestMultipartBody:
596
+ def test_model_is_encoded_per_property(self, tmp_path: Path):
597
+ """Arrays send one part per item; objects are JSON; text has no filename."""
598
+ mod = _generate(tmp_path, _multipart_spec(), 'wire_multipart')
599
+ rec = Recorder()
600
+ mod.upload(
601
+ mod.models.Upload(
602
+ name='a', tags=['x', 'y'], meta={'n': 1}, file=b'payload'
603
+ ),
604
+ client=rec.bind(mod.Client()),
605
+ )
606
+ # The harness's yaml.safe_dump sorts keys, so fields are alphabetical.
607
+ assert _multipart_parts(rec.request) == [
608
+ (
609
+ 'Content-Disposition: form-data; name="file"; filename="upload"\r\n'
610
+ 'Content-Type: application/octet-stream',
611
+ 'payload',
612
+ ),
613
+ (
614
+ 'Content-Disposition: form-data; name="meta"\r\n'
615
+ 'Content-Type: application/json',
616
+ '{"n": 1}',
617
+ ),
618
+ ('Content-Disposition: form-data; name="name"', 'a'),
619
+ ('Content-Disposition: form-data; name="tags"', 'x'),
620
+ ('Content-Disposition: form-data; name="tags"', 'y'),
621
+ ]
622
+
623
+ def test_text_only_body_is_still_multipart(self, tmp_path: Path):
624
+ """Unset fields are dropped, and no file must not fall back to urlencoded."""
625
+ mod = _generate(tmp_path, _multipart_spec(), 'wire_multipart_text')
626
+ rec = Recorder()
627
+ mod.upload(mod.models.Upload(name='a'), client=rec.bind(mod.Client()))
628
+ assert _multipart_parts(rec.request) == [
629
+ ('Content-Disposition: form-data; name="name"', 'a'),
630
+ ]
631
+
632
+
546
633
  # ---------------------------------------------------------------------------
547
634
  # Model annotations
548
635
  # ---------------------------------------------------------------------------
@@ -665,3 +752,56 @@ class TestExcludeUnsetConfig:
665
752
  client=rec.bind(mod.Client()),
666
753
  )
667
754
  assert '"shipDate":"2024-01-02T03:04:05"' in rec.body
755
+
756
+
757
+ # ---------------------------------------------------------------------------
758
+ # HTTP library
759
+ # ---------------------------------------------------------------------------
760
+
761
+
762
+ def _imported_modules(package_dir: Path) -> set[str]:
763
+ modules: set[str] = set()
764
+ for path in package_dir.rglob('*.py'):
765
+ for node in ast.walk(ast.parse(path.read_text(encoding='utf-8'))):
766
+ if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
767
+ modules.add(node.module.split('.')[0])
768
+ elif isinstance(node, ast.Import):
769
+ modules.update(alias.name.split('.')[0] for alias in node.names)
770
+ return modules
771
+
772
+
773
+ class TestHttpLibrary:
774
+ @pytest.mark.parametrize('split', [False, True], ids=['single', 'split'])
775
+ def test_httpx_replaces_every_httpx2_import(self, tmp_path: Path, split: bool):
776
+ from otterapi.config import ModuleSplitConfig
777
+
778
+ # Generate without importing: httpx itself may not be installed.
779
+ spec_file = tmp_path / 'openapi.yaml'
780
+ spec_file.write_text(yaml.safe_dump(_body_spec(required=True)), 'utf-8')
781
+ Codegen(
782
+ DocumentConfig(
783
+ source=str(spec_file),
784
+ output=str(tmp_path / 'wire_httpx_imports'),
785
+ http_library='httpx',
786
+ module_split=ModuleSplitConfig(enabled=split),
787
+ )
788
+ ).generate()
789
+ imported = _imported_modules(tmp_path / 'wire_httpx_imports')
790
+ assert 'httpx' in imported
791
+ assert 'httpx2' not in imported
792
+
793
+ def test_httpx_client_sends_requests(self, tmp_path: Path):
794
+ httpx = pytest.importorskip('httpx')
795
+ mod = _generate(
796
+ tmp_path, _body_spec(required=True), 'wire_httpx', http_library='httpx'
797
+ )
798
+ sent: list[Any] = []
799
+
800
+ def handler(request: Any) -> Any:
801
+ sent.append(request)
802
+ return httpx.Response(200, json={})
803
+
804
+ client = mod.Client()
805
+ client._sync_client = httpx.Client(transport=httpx.MockTransport(handler))
806
+ mod.place_order(mod.models.Order(id=7), client=client)
807
+ assert sent[0].content == b'{"id":7}'
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes