fastapi-typed-client 0.1.0__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,408 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-typed-client
3
+ Version: 0.1.0
4
+ Summary: Generate a fully-typed client for your FastAPI app with the Pydantic models from your code (mostly for testing)
5
+ Keywords: fastapi,client,testing,typed,httpx,pydantic,api-client
6
+ Author: Lukas Schmelzeisen
7
+ Author-email: Lukas Schmelzeisen <me@lschmelzeisen.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Web Environment
12
+ Classifier: Framework :: AnyIO
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Framework :: Pydantic
15
+ Classifier: Framework :: Pydantic :: 2
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: Information Technology
18
+ Classifier: Intended Audience :: System Administrators
19
+ Classifier: License :: OSI Approved :: Apache Software License
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Programming Language :: Python :: 3 :: Only
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
26
+ Classifier: Programming Language :: Python :: 3.14
27
+ Classifier: Topic :: Internet
28
+ Classifier: Topic :: Internet :: WWW/HTTP
29
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
30
+ Classifier: Topic :: Software Development
31
+ Classifier: Topic :: Software Development :: Libraries
32
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
33
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
34
+ Classifier: Topic :: Software Development :: Testing
35
+ Classifier: Topic :: Utilities
36
+ Classifier: Typing :: Typed
37
+ Requires-Dist: fastapi>=0.119.0
38
+ Requires-Dist: httpx>=0.28.1
39
+ Requires-Dist: pydantic>=2.12.2
40
+ Requires-Dist: rich>=14.2.0
41
+ Requires-Dist: typer>=0.19.2
42
+ Requires-Python: >=3.12
43
+ Project-URL: changelog, https://github.com/lschmelzeisen/fastapi-typed-client/blob/main/CHANGELOG.md
44
+ Project-URL: issues, https://github.com/lschmelzeisen/fastapi-typed-client/issues
45
+ Project-URL: source, https://github.com/lschmelzeisen/fastapi-typed-client
46
+ Description-Content-Type: text/markdown
47
+
48
+ # fastapi-typed-client
49
+
50
+ [![PyPI](https://img.shields.io/pypi/v/fastapi-typed-client)](https://pypi.org/project/fastapi-typed-client/)
51
+ [![Python 3.12-3.14](https://img.shields.io/pypi/pyversions/fastapi-typed-client)](https://pypi.org/project/fastapi-typed-client/)
52
+ [![License](https://img.shields.io/pypi/l/fastapi-typed-client)](./LICENSE)
53
+
54
+ Generate a fully-typed client for your [FastAPI](https://fastapi.tiangolo.com/) app with the Pydantic models from your code.
55
+
56
+ [Quickstart](#quickstart) • [Features](#features) • [Introduction](#introduction) • [Usage](#usage) • [Development](#development) • [License](#license) • [Changelog](./CHANGELOG.md)
57
+
58
+ ## Quickstart
59
+
60
+ If you are using [uv](https://docs.astral.sh/uv/) (recommended) and your FastAPI app is importable from `module.submodule` with name `app`:
61
+
62
+ ```shell
63
+ uvx fastapi-typed-client generate module.submodule:app
64
+ ```
65
+
66
+ Otherwise, do this (preferably in a [virtual environment](https://fastapi.tiangolo.com/virtual-environments/)):
67
+
68
+ ```shell
69
+ pip install fastapi-typed-client
70
+ fastapi-typed-client generate module.submodule:app
71
+ ```
72
+
73
+ This will generate a file called `fastapi_client.py` (or if your FastAPI app has a title: `<title>_client.py`). You can then use it like this:
74
+
75
+ ```python
76
+ from module.submodule import app, YourPydanticModel
77
+ from fastapi_client import FastAPIClient
78
+
79
+ with FastAPIClient.from_app(app) as client:
80
+ print(client.your_endpoint(your_param=YourPydanticModel(foo="bar")))
81
+ ```
82
+
83
+ For help on available options, see:
84
+
85
+ ```shell
86
+ fastapi-typed-client generate --help
87
+ ```
88
+
89
+ ## Features
90
+
91
+ Generates a client for your FastAPI app that:
92
+
93
+ - Has **full type annotations** for all endpoint parameters and combinations of status codes and response models
94
+ - Uses the **types and Pydantic models defined in your app code**
95
+ - Can be either **sync or async** (via the `--async` CLI option)
96
+ - Support for **path**, **query**, **header**, **body parameters** (plus experimental support for **cookie parameters**)
97
+ - Support for **streams of JSON objects** (experimental)
98
+ - Only depends on [Pydantic](https://pydantic.dev/), [HTTPX](https://www.python-httpx.org/), [`fastapi.encoders`](https://fastapi.tiangolo.com/reference/encoders/), and any Pydantic models that your app defines at runtime
99
+ - Generated code is **human-readable**, has **diff-friendly formatting**, **controllable import styles**, and is **designed to be checked into version control**
100
+ - Supports Python 3.12-3.14
101
+
102
+ ## Introduction
103
+
104
+ The main use case of this tool is to write type-checked tests for FastAPI apps.
105
+
106
+ Let's take the following file `birthday_app.py` as an example of a simple FastAPI app:
107
+
108
+ ```python
109
+ from datetime import date
110
+ from fastapi import FastAPI, HTTPException, status
111
+ from pydantic import BaseModel
112
+
113
+ class BirthdayData(BaseModel):
114
+ name: str
115
+ birthday: date
116
+
117
+ class GetBirthdayError(BaseModel):
118
+ detail: str
119
+
120
+ app_db: dict[str, date] = {} # Simple in-memory dict, just for example.
121
+ app = FastAPI(title="BirthdayApp")
122
+
123
+ @app.post("/birthday", status_code=status.HTTP_201_CREATED)
124
+ def register_birthday(data: BirthdayData) -> bool:
125
+ app_db[data.name] = data.birthday
126
+ return True
127
+
128
+ @app.get(
129
+ "/birthday/{name}",
130
+ responses={status.HTTP_404_NOT_FOUND: {"model": GetBirthdayError}},
131
+ )
132
+ def get_birthday(name: str) -> BirthdayData:
133
+ if name not in app_db:
134
+ raise HTTPException(
135
+ status_code=status.HTTP_404_NOT_FOUND, detail=f"No birthday data for {name}"
136
+ )
137
+ return BirthdayData(name=name, birthday=app_db[name])
138
+ ```
139
+
140
+ This app allows us to store and retrieve birthday information. Note that the `register_birthday` endpoint returns a status code of `201 Created` instead of the default `200 Ok`, and that the `get_birthday` endpoint returns a JSON object of shape `BirthdayData` on success or of shape `GetBirthdayError` with a `404 Not Found` on failure.
141
+
142
+ With regular [FastAPI testing](https://fastapi.tiangolo.com/tutorial/testing/), we might test this app like so:
143
+
144
+ ```python
145
+ import pytest
146
+ from birthday_app import app, app_db
147
+ from datetime import date
148
+ from fastapi.testclient import TestClient
149
+
150
+ @pytest.fixture
151
+ def client() -> TestClient:
152
+ app_db.clear()
153
+ return TestClient(app)
154
+
155
+ def test_register_birthday(client: TestClient) -> None:
156
+ name = "Elvis"
157
+ birthday = date(year=1935, month=1, day=8)
158
+
159
+ register_response = client.post(
160
+ "/birthday", json={"name": name, "birthday": f"{birthday:%Y-%m-%d}"}
161
+ )
162
+ register_response.raise_for_status()
163
+ assert register_response.json() is True
164
+
165
+ get_response = client.get(f"/birthday/{name}")
166
+ get_response.raise_for_status()
167
+ assert get_response.json() == {"name": name, "birthday": f"{birthday:%Y-%m-%d}"}
168
+
169
+ def test_unregistered_birthday(client: TestClient) -> None:
170
+ response = client.get("/birthday/Elvis")
171
+ assert response.status_code == 404
172
+ assert response.json()["detail"] == "No birthday data for Elvis"
173
+ ```
174
+
175
+ While this definitely tests the desired behavior of our app, this code is not ideal:
176
+
177
+ - Our tests hardcode the HTTP method and URL pattern that each endpoint expects and construct URLs with path parameters manually in multiple places.
178
+ - Our test code must be aware of how our app serializes and deserializes JSON. For example, how `birthday` is represented by FastAPI.
179
+ - Our tests need to specify what format each endpoint expects for its parameters. Path parameters need to be encoded in the URL, body parameters need to be gathered in a dict and passed to the `json` argument of `client.post`, whereas query parameters would need to be passed to the `params` argument. If we were to change the `alias` of a parameter, or if we refactor a body parameter to a query parameter, our tests would need to be updated to reflect this change.
180
+ - We use `response.raise_for_status()` to check assert that our endpoints did not return an error. However, this only checks for any `2xx` status code and silently would accept if `register_birthday` would erroneously return a `200 Ok` instead of a `201 Created`.
181
+ - There are no type-based guarantees for our test code. The type checker doesn't know what parameters are permissible to pass into an endpoint and what things they could return. For example, the type-checker can't know whether `response.json()["detail"]` is valid, nor can your IDE provide any type-based hints about it.
182
+
183
+ It's up to you whether you consider each of these points as downsides. For example, you can argue that you want your tests to duplicate such implementation details to protect against accidentally changing them. In any case, fastapi-typed-client allows us to address these concerns when desired.
184
+
185
+ First, we generate a fully-typed client for our FastAPI app with:
186
+
187
+ ```shell
188
+ fastapi-typed-client generate birthday_app:app
189
+ ```
190
+
191
+ This creates a file `birthday_app_client.py` (check out the [example generated client](./examples/birthday_app_client.py) if you want to see the actual generated code), which allows us to now write our tests as follows:
192
+
193
+ ```python
194
+ import pytest
195
+ from birthday_app import BirthdayData, GetBirthdayError, app, app_db
196
+ from birthday_app_client import BirthdayAppClient
197
+ from collections.abc import Iterator
198
+ from datetime import date
199
+ from http import HTTPStatus
200
+ from typing import Literal, assert_type
201
+
202
+ @pytest.fixture
203
+ def client() -> Iterator[BirthdayAppClient]:
204
+ app_db.clear()
205
+ with BirthdayAppClient.from_app(app) as client:
206
+ yield client
207
+
208
+ def test_register_birthday(client: BirthdayAppClient) -> None:
209
+ name = "Elvis"
210
+ birthday = date(year=1935, month=1, day=8)
211
+
212
+ register_response = client.register_birthday(
213
+ BirthdayData(name=name, birthday=birthday), raise_if_not_default_status=True
214
+ )
215
+ assert_type(register_response.status, Literal[HTTPStatus.CREATED])
216
+ assert_type(register_response.data, bool)
217
+ assert register_response.data is True
218
+
219
+ get_response = client.get_birthday(name, raise_if_not_default_status=True)
220
+ assert_type(get_response.status, Literal[HTTPStatus.OK])
221
+ assert_type(get_response.data, BirthdayData)
222
+ assert get_response.data == BirthdayData(name=name, birthday=birthday)
223
+
224
+ def test_unregistered_birthday(client: BirthdayAppClient) -> None:
225
+ response = client.get_birthday("Elvis")
226
+ assert response.status == HTTPStatus.NOT_FOUND
227
+ assert_type(response.data, GetBirthdayError)
228
+ assert response.data.detail == "No birthday data for Elvis"
229
+ ```
230
+
231
+ Note that:
232
+
233
+ - We can now "call" our endpoints via simple methods like `client.register_birthday()` and `client.get_birthday()`. However, the same HTTP roundtrip and JSON serialization/deserialization as before takes place in the background.
234
+ - Our endpoints receive parameters with the _exact same_ types as we specified them in our original FastAPI app. In this case, we import `BirthdayData` from `birthday_app` and pass it to our endpoint.
235
+ - Everything is type-checked. The above code features a few `assert_type()` calls to demonstrate which types the type checker is aware of, but otherwise these are not needed. The generated client checks whether response data can be deserialized as expected, so our tests do not need to worry about this.
236
+ - Our tests do not repeat implementation details like HTTP methods and URL schemas.
237
+
238
+ ### Comparison to OpenAPI client generators
239
+
240
+ Easy [client generation based on an app's OpenAPI spec](https://fastapi.tiangolo.com/advanced/generate-clients/) is one of the main advantages of FastAPI and fairly common.
241
+
242
+ The main difference between fastapi-typed-client and such tools (like [openapi-python-client](https://github.com/openapi-generators/openapi-python-client)) is that it reuses the types and Pydantic models from our application code instead of generating new ones.
243
+
244
+ This greatly simplifies writing tests, since we are aware of all the types from writing the app implementation. Additionally, it keeps diffs minimal when changing the app implementation and thus the generated clients.
245
+
246
+ ## Usage
247
+
248
+ ### Generating a client for a FastAPI app
249
+
250
+ To generate a new client for your FastAPI app from the command line:
251
+
252
+ ```shell
253
+ fastapi-typed-client generate [OPTIONS] APP_IMPORT_STR
254
+ ```
255
+
256
+ Where `APP_IMPORT_STR` is the FastAPI app import string in the format `module.submodule:app_name`. That is, your app needs to be importable as `from module.submodule import app_name`.
257
+
258
+ The following options are available (see also `fastapi-typed-client generate --help`):
259
+
260
+ - `--output-path PATH`: Path to write the generated client to. Defaults to `--title` (converted to snake_case) + `.py`.
261
+ - `--title TEXT`: Title for the class of the generated client. Defaults to the FastAPI app title (converted to UpperCamelCase) + `Client`.
262
+ - `--async`: Make generated client async.
263
+ - `--import-barrier MODULE`: Module path(s) in format `module.submodule` to set as import barriers. Forces types in submodules to be imported through the barrier rather than directly. Can be specified multiple times.
264
+ - `--import-client-base`: Import the client base from `fastapi_typed_client.client` instead of writing it to the output file. Intended when working with multiple generated clients at once.
265
+ - `--raise-if-not-default-status`: Client methods will raise an exception by default if the respective endpoint does not return its default status code. With or without option, this can also be controlled at each method call with the `raise_if_not_default_status` parameter.
266
+
267
+ Alternatively, for programmatic access, the function `generate_fastapi_typed_client()`, which can be imported from `fastapi_typed_client`, exposes the same functionality as the CLI command. Its parameters correspond one-to-one to the CLI options.
268
+
269
+ ### Instantiating a generated client
270
+
271
+ The following assumes that your FastAPI app is available as `from fastapi_app import app` and your generated client class is named `FastAPIClient` in file `fastapi_client.py` (this may be changed using the `--output-path` and `--title` options).
272
+
273
+ To create an instance of the generated client you need to pass it an instance of a [`httpx.Client`](https://www.python-httpx.org/api/#client) (or of [`httpx.AsyncClient`](https://www.python-httpx.org/api/#asyncclient) if using `--async`) that connects to your `app`. See [FastAPI Testing](https://fastapi.tiangolo.com/tutorial/testing/) or [FastAPI Async Tests](https://fastapi.tiangolo.com/advanced/async-tests/) for how to do this. Then instantiate `FastAPIClient` like this:
274
+
275
+ ```python
276
+ from fastapi_client import FastAPIClient
277
+
278
+ client = FastAPIClient(httpx_client)
279
+ # Do something with client.
280
+ ```
281
+
282
+ For convenience, the classmethod `.from_app()` can be used to directly create a client for your `app`:
283
+
284
+ ```python
285
+ from fastapi_app import app
286
+ from fastapi_client import FastAPIClient
287
+
288
+ with FastAPIClient.from_app(app) as client:
289
+ pass # Do something with client.
290
+ ```
291
+
292
+ This approach uses FastAPI's [TestClient](https://fastapi.tiangolo.com/reference/testclient/) under the hood and thus triggers the [lifespan events](https://fastapi.tiangolo.com/advanced/testing-events/) of your FastAPI app. Because FastAPI does not have an async `TestClient`, this is _not_ the case if you use `--async`. Use something like [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan)'s `LifespanManager` to trigger lifespan events yourself if needed.
293
+
294
+ ### Using a generated client
295
+
296
+ The generated `FastAPIClient` will contain one generated method for each endpoint defined by your FastAPI app.
297
+
298
+ That is, for an endpoint defined as follows:
299
+
300
+ ```python
301
+ @app.get("/endpoint-url/{foo}")
302
+ def endpoint(
303
+ foo: str, # path parameters
304
+ bar: int, # query parameter
305
+ baz: BazModel, # body parameter (with custom Pydantic model)
306
+ ) -> ResponseModel: # custom Pydantic Model for response
307
+ ...
308
+ ```
309
+
310
+ The generated client will contain a method similar to the following:
311
+
312
+ ```python
313
+ from fastapi_app import BazModel, ResponseModel
314
+ from http import HTTPStatus
315
+ from typing import Literal
316
+
317
+ class FastAPIClient:
318
+ def endpoint(
319
+ self,
320
+ foo: str,
321
+ bar: int,
322
+ baz: BazModel,
323
+ *,
324
+ raise_if_not_default_status: bool = False,
325
+ client_exts: FastAPIClientExtensions | None = None
326
+ ) -> FastAPIClientResult[Literal[HTTPStatus.OK], ResponseModel]:
327
+ ...
328
+ ```
329
+
330
+ With an [client instance](#instantiating-a-generated-client) you can then just call this as `client.endpoint(foo="foo", bar=123, baz=BazModel())`. If you are unsure about the parameters and types of your generated client, it is helpful to review the generated `fastapi_client.py`. See [auxiliary classes](#auxiliary-classes), for documentation on classes like `FastAPIClientResult` and `FastAPIClientExtensions`.
331
+
332
+ For endpoints that can return errors (either because they define errors as [additional responses](https://fastapi.tiangolo.com/advanced/additional-responses/) or because they take parameters which can result in a Pydantic `ValidationError`) the return type of the generated endpoint method will be a union of all status codes with their respective response models.
333
+
334
+ If your set the `raise_if_not_default_status` parameter to `True` or use `--raise-if-not-default-status` when generating your client, the return type will just be the default status code (i.e., `200 Ok` or the one defined via `status_code` in the endpoint's decorator) with its response model. Should the endpoint return a different status code, a `FastAPIClientNotDefaultStatusError` will be raised, which contains the response status code and deserialized data.
335
+
336
+ There is experimental support for endpoints returning streams of JSON objects. The detection works by checking if the endpoint's response class is a subclass of both FastAPI's [StreamingResponse](https://fastapi.tiangolo.com/reference/responses/#fastapi.responses.StreamingResponse) and [JSONResponse](https://fastapi.tiangolo.com/reference/responses/#fastapi.responses.JSONResponse) classes. The generated method for this endpoint will then return an iterator over all JSON objects contained in the newline-delimited stream from the endpoint. It can be used like this (see the [test for this feature](./tests/test_core/test_streaming_json_response.py) for an example):
337
+
338
+ ```python
339
+ for item in client.your_streaming_endpoint().data:
340
+ print(item.field)
341
+ ```
342
+
343
+ For now, this detection of streaming JSON output is only available for the default response of an endpoint and not for additional responses.
344
+
345
+ ### Auxiliary classes
346
+
347
+ The following auxiliary classes are either included in the generated `fastapi_client.py` file or imported from `fastapi_typed_client.client` if using `--import-client-base`.
348
+
349
+ #### `FastAPIClientResult[Status: http.HTTPStatus, Model]`
350
+
351
+ Parameterized type that is returned by each endpoint method. The generic parameters `Status` and `Model` specify status code and response model of each endpoint in the type system. Endpoint's with [additional responses](https://fastapi.tiangolo.com/advanced/additional-responses/) return a union of specializations of this type.
352
+
353
+ Instance attributes:
354
+
355
+ - `status: Status`: The [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus) of the response
356
+ - `data: Model`: The deserialized response data
357
+ - `model: type[Model]`: The type used to deserialize the response data
358
+ - `response: Response`: The raw `httpx.Response` object
359
+
360
+ #### `FastAPIClientNotDefaultStatusError`
361
+
362
+ Exception raised when using `raise_if_not_default_status=True` or `--raise-if-not-default-status` and an endpoint returns a non-default status code.
363
+
364
+ Instance attributes:
365
+
366
+ - `default_status: HTTPStatus`: The expected status code
367
+ - `result: FastAPIClientResult`: The actual result received
368
+
369
+ #### `FastAPIClientHTTPValidationError` and `FastAPIClientValidationError`
370
+
371
+ Pydantic models for deserializing `422 Unprocessable Entity` responses from your FastAPI app.
372
+
373
+ Instance attributes of `FastAPIClientHTTPValidationError`:
374
+
375
+ - `detail: Sequence[FastAPIClientValidationError]`: List of validation errors
376
+
377
+ Instance attributes of `FastAPIClientValidationError`:
378
+
379
+ - `loc: Sequence[str | int]`: Location of the error
380
+ - `msg: str`: Error message
381
+ - `type: str`: Error type
382
+
383
+ #### `FastAPIClientExtensions`
384
+
385
+ TypedDict for passing additional options via the `client_exts` parameter to each endpoint. Currently only supports the following field:
386
+
387
+ - `timeout: float | tuple[float | None, float | None, float | None, float | None] | httpx.Timeout | None`: Request timeout, directly passed to [`httpx.Client.request`](https://www.python-httpx.org/api/#client)
388
+
389
+ ### Current limitations
390
+
391
+ The following FastAPI features are not yet supported:
392
+
393
+ - [WebSockets](https://fastapi.tiangolo.com/advanced/websockets/) endpoints
394
+ - Endpoints with [form data](https://fastapi.tiangolo.com/tutorial/request-forms/) or [file upload](https://fastapi.tiangolo.com/tutorial/request-files/) parameters
395
+ - Endpoints that can be reached via more than one HTTP method
396
+ - Endpoints with duplicate parameter names (e.g., a query and a header parameter with the same name)
397
+ - Endpoints using any of `response_model_include`, `response_model_exclude`, `response_model_by_alias`, `response_model_exclude_unset`, `response_model_exclude_defaults`, or `response_model_exclude_none`
398
+ - Endpoints with `FileResponse`, `HTMLResponse`, `PlainTextResponse`, `RedirectResponse` or a custom response class
399
+
400
+ ## Development
401
+
402
+ Contributions welcome! Feel free to create [issues](https://github.com/lschmelzeisen/fastapi-typed-client/issues) and [pull requests](https://github.com/lschmelzeisen/fastapi-typed-client/pulls).
403
+
404
+ There is a `Makefile` with helpers for how to run the development tools ([uv](https://docs.astral.sh/uv/), [Ruff](https://docs.astral.sh/ruff/), [Pyrefly](https://pyrefly.org/), [pytest](https://docs.pytest.org)). Run `make help` for an overview of available commands.
405
+
406
+ ## License
407
+
408
+ Licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0).