msgspec-fastapi 0.0.3__tar.gz → 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.
- msgspec_fastapi-0.1.0/MANIFEST.in +4 -0
- msgspec_fastapi-0.1.0/PKG-INFO +282 -0
- msgspec_fastapi-0.1.0/README.md +253 -0
- msgspec_fastapi-0.1.0/docs/images/benchmark-cpu.svg +394 -0
- msgspec_fastapi-0.1.0/docs/images/benchmark-throughput.svg +439 -0
- msgspec_fastapi-0.1.0/pyproject.toml +72 -0
- msgspec_fastapi-0.1.0/setup.cfg +4 -0
- msgspec_fastapi-0.1.0/setup.py +27 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi/__init__.py +4 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi/_defaults.c +1101 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi/_defaults.pyi +50 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi/_defaults_copy.c +808 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi/body_errors.py +506 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi/defaults.py +342 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi/py.typed +0 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi/responses.py +40 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi/router.py +1236 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi/validation.py +595 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi.egg-info/PKG-INFO +282 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi.egg-info/SOURCES.txt +51 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi.egg-info/dependency_links.txt +1 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi.egg-info/requires.txt +3 -0
- msgspec_fastapi-0.1.0/src/msgspec_fastapi.egg-info/top_level.txt +1 -0
- msgspec_fastapi-0.1.0/tests/test_body_default_ownership.py +169 -0
- msgspec_fastapi-0.1.0/tests/test_body_errors.py +345 -0
- msgspec_fastapi-0.1.0/tests/test_constraint_carriers.py +87 -0
- msgspec_fastapi-0.1.0/tests/test_copy_callbacks.py +72 -0
- msgspec_fastapi-0.1.0/tests/test_copy_protocol_regressions.py +305 -0
- msgspec_fastapi-0.1.0/tests/test_copy_state_protocols.py +358 -0
- msgspec_fastapi-0.1.0/tests/test_copy_type_predicates.py +138 -0
- msgspec_fastapi-0.1.0/tests/test_copy_unpack_order.py +96 -0
- msgspec_fastapi-0.1.0/tests/test_default_accessors.py +165 -0
- msgspec_fastapi-0.1.0/tests/test_default_copy_protocols.py +124 -0
- msgspec_fastapi-0.1.0/tests/test_default_instance_protocols.py +206 -0
- msgspec_fastapi-0.1.0/tests/test_default_slot_bindings.py +314 -0
- msgspec_fastapi-0.1.0/tests/test_diagnostic_plans.py +211 -0
- msgspec_fastapi-0.1.0/tests/test_enum_copy_protocols.py +159 -0
- msgspec_fastapi-0.1.0/tests/test_error_responses.py +595 -0
- msgspec_fastapi-0.1.0/tests/test_instance_builtin_codec.py +41 -0
- msgspec_fastapi-0.1.0/tests/test_metadata_copy.py +118 -0
- msgspec_fastapi-0.1.0/tests/test_native_copier.py +561 -0
- msgspec_fastapi-0.1.0/tests/test_native_guard.py +224 -0
- msgspec_fastapi-0.1.0/tests/test_native_serialization.py +135 -0
- msgspec_fastapi-0.1.0/tests/test_native_type_contract.py +232 -0
- msgspec_fastapi-0.1.0/tests/test_openapi.py +659 -0
- msgspec_fastapi-0.1.0/tests/test_parameter_defaults.py +138 -0
- msgspec_fastapi-0.1.0/tests/test_parameter_getter_copy.py +59 -0
- msgspec_fastapi-0.1.0/tests/test_request_response.py +1194 -0
- msgspec_fastapi-0.1.0/tests/test_router.py +1023 -0
- msgspec_fastapi-0.1.0/tests/test_runtime_codec_boundary.py +96 -0
- msgspec_fastapi-0.1.0/tests/test_sse_boundary.py +147 -0
- msgspec_fastapi-0.1.0/tests/test_stream_adapter.py +120 -0
- msgspec_fastapi-0.0.3/.github/workflows/ci.yml +0 -60
- msgspec_fastapi-0.0.3/.github/workflows/publish.yml +0 -45
- msgspec_fastapi-0.0.3/.gitignore +0 -6
- msgspec_fastapi-0.0.3/PKG-INFO +0 -185
- msgspec_fastapi-0.0.3/README.md +0 -168
- msgspec_fastapi-0.0.3/pyproject.toml +0 -35
- msgspec_fastapi-0.0.3/src/msgspec_fastapi/__init__.py +0 -4
- msgspec_fastapi-0.0.3/src/msgspec_fastapi/responses.py +0 -10
- msgspec_fastapi-0.0.3/src/msgspec_fastapi/router.py +0 -455
- msgspec_fastapi-0.0.3/src/msgspec_fastapi/validation.py +0 -239
- msgspec_fastapi-0.0.3/tests/test_router.py +0 -543
- {msgspec_fastapi-0.0.3 → msgspec_fastapi-0.1.0}/LICENSE +0 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: msgspec-fastapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: FastAPI router that decodes request bodies and encodes responses with msgspec
|
|
5
|
+
Author: Aleksandr Tseluiko
|
|
6
|
+
License-Expression: BSD-3-Clause
|
|
7
|
+
Project-URL: Source, https://github.com/Siyet/msgspec-fastapi
|
|
8
|
+
Project-URL: Issues, https://github.com/Siyet/msgspec-fastapi/issues
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Framework :: FastAPI
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: C
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
20
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: fastapi<0.166,>=0.142.2
|
|
26
|
+
Requires-Dist: msgspec>=0.22.0
|
|
27
|
+
Requires-Dist: regexrs-py<0.3,>=0.2.0
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# msgspec-fastapi
|
|
31
|
+
|
|
32
|
+
A FastAPI router that uses msgspec for JSON request bodies and responses.
|
|
33
|
+
In one benchmark service, moving from Pydantic models to msgspec Structs with this
|
|
34
|
+
router increased the throughput of one saturated API core by 68% on a route with a large
|
|
35
|
+
JSON body and by about 12% on database-backed routes; see the Benchmarks section below.
|
|
36
|
+
|
|
37
|
+
This project uses ZeroVer: the major version will always stay at 0. There will be no
|
|
38
|
+
1.0 release. The API may change in 0.x releases. The router relies on private FastAPI
|
|
39
|
+
internals, so it is pinned to FastAPI 0.142.2 to 0.165.x. It is a personal project,
|
|
40
|
+
not part of msgspec; feedback is welcome in the issues.
|
|
41
|
+
|
|
42
|
+

|
|
43
|
+
|
|
44
|
+

|
|
45
|
+
|
|
46
|
+
## Installation
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
pip install msgspec-fastapi
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The package includes an internal C extension for checking copied defaults and
|
|
53
|
+
metadata. Building from source requires a C11 compiler and CPython headers.
|
|
54
|
+
|
|
55
|
+
On free-threaded CPython 3.14t the package runs with the GIL enabled: the extension is
|
|
56
|
+
not yet marked as safe to run without it, so importing the package enables the GIL and
|
|
57
|
+
emits a `RuntimeWarning`. Set `PYTHON_GIL=1` to enable the GIL from the start and avoid
|
|
58
|
+
the warning; running with `PYTHON_GIL=0` is not supported.
|
|
59
|
+
|
|
60
|
+
## Usage
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
import msgspec
|
|
64
|
+
from fastapi import FastAPI
|
|
65
|
+
from msgspec_fastapi import MsgspecRouter, install_openapi
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class City(msgspec.Struct):
|
|
69
|
+
name: str
|
|
70
|
+
population: int
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
router = MsgspecRouter()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@router.post('/cities')
|
|
77
|
+
async def create_city(city: City) -> City:
|
|
78
|
+
return city
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
app = FastAPI()
|
|
82
|
+
app.include_router(router)
|
|
83
|
+
install_openapi(app)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Benchmarks
|
|
87
|
+
|
|
88
|
+
The router was measured in a small reference-data service on a cloud VM (November 2026).
|
|
89
|
+
Each row compares the same service on FastAPI with Pydantic models against the same
|
|
90
|
+
service with msgspec Structs and `MsgspecRouter`. The database queries (SQLAlchemy ORM),
|
|
91
|
+
event loop and server settings are the same on both sides, and there is no cache.
|
|
92
|
+
|
|
93
|
+
| Request | Requests per second | RPS change | CPU time per response | CPU change |
|
|
94
|
+
|---|---|---|---|---|
|
|
95
|
+
| `POST /cities/validate`, a JSON body of 100 cities (23 KB), no database | 1,786 → 3,000 | **+68.0%** [+66.0%, +70.0%] | 560 → 333 µs | **-40.5%** [-41.2%, -39.7%] |
|
|
96
|
+
| `GET /cities?limit=100`, a page of 100 cities read from PostgreSQL | 489 → 549 | **+12.3%** [+11.1%, +13.4%] | 2,047 → 1,823 µs | **-10.9%** [-11.9%, -10.0%] |
|
|
97
|
+
| `POST /cities/search`, small JSON filter bodies, a page of 100 cities | 419 → 469 | **+11.9%** [+10.8%, +13.0%] | 2,387 → 2,133 µs | **-10.6%** [-11.5%, -9.7%] |
|
|
98
|
+
|
|
99
|
+
The first route returns a constant 16-byte response (`{"accepted":100}`), so the
|
|
100
|
+
difference on this route comes mostly from request decoding and validation, and the gain
|
|
101
|
+
is largest there. On routes that read from a database, API CPU time per response falls
|
|
102
|
+
by about 220 to 250 µs out of roughly 2 ms, so the relative gain is smaller. At a fixed
|
|
103
|
+
load below saturation, measured in two runs per side without an interval, API CPU time
|
|
104
|
+
per response was about 8% (about 155 µs) lower on GET at 300 requests per second, about
|
|
105
|
+
8% (about 200 µs) lower on search at 200 and 39% (about 240 µs) lower on the first route
|
|
106
|
+
at 1,200; the two runs of one variant differed by up to 4%. The memory use of the API
|
|
107
|
+
process (median RSS of about 98 to 102 MiB) differed by less than 1% on all three routes.
|
|
108
|
+
|
|
109
|
+
In the same service, setting `response_model=None` on the GET route made no detectable
|
|
110
|
+
difference in throughput with `MsgspecRouter` (+0.2% [-1.1%, +1.5%], an interval that
|
|
111
|
+
includes zero). This is consistent with an instance of exactly the declared Struct class
|
|
112
|
+
being encoded without revalidation.
|
|
113
|
+
|
|
114
|
+
These numbers are series 10 of
|
|
115
|
+
[world-directory-bench](https://github.com/Siyet/world-directory-bench/tree/series-10#series-10-msgspec-fastapi-010-readme-comparisons),
|
|
116
|
+
which also contains the service, the data preparation scripts and other comparisons in
|
|
117
|
+
the same service, including direct asyncpg queries without the ORM, a Redis cache,
|
|
118
|
+
Litestar and Go.
|
|
119
|
+
|
|
120
|
+
<details>
|
|
121
|
+
<summary>How it was measured</summary>
|
|
122
|
+
|
|
123
|
+
- Host: a KVM cloud VM with 6 vCPUs on a plan advertised with dedicated cores, Ubuntu
|
|
124
|
+
24.04. The API ran as one uvicorn worker pinned to one core, with httptools and uvloop
|
|
125
|
+
(what uvicorn uses when they are installed, for example with `fastapi[standard]`) and
|
|
126
|
+
the access log off. PostgreSQL and the load generator ran on other cores.
|
|
127
|
+
- Data and database: 224,578 cities, 55,246 division records, 501 country records and
|
|
128
|
+
86,185 airports from GeoNames and OurAirports, about 231 MB in PostgreSQL 18.6
|
|
129
|
+
including indexes. The PostgreSQL data directory was on tmpfs (in memory). Database
|
|
130
|
+
access went through the SQLAlchemy ORM with the asyncpg driver.
|
|
131
|
+
- Software: msgspec-fastapi 0.1.0, CPython 3.14.10, FastAPI 0.165.0, Pydantic 2.14.3,
|
|
132
|
+
msgspec 0.22.0, SQLAlchemy 2.1.9 (ORM), asyncpg 0.32.0, uvicorn 0.54.0 with httptools
|
|
133
|
+
0.9.0 and uvloop 0.23.0.
|
|
134
|
+
- Load: a Go generator with 20 closed-loop clients, checking every response body. The
|
|
135
|
+
numbers are throughput at saturation of the single API core. The GET mix sends 9 of
|
|
136
|
+
10 requests to one page and every 10th to a page that is not repeated within the run.
|
|
137
|
+
- Each comparison is 8 blocks in ABBA or BAAB order, so each block measures both
|
|
138
|
+
versions twice; every run starts a fresh process with a 30 s warmup and a 60 s
|
|
139
|
+
measurement. The percentages are computed from the mean of the per-block log ratios,
|
|
140
|
+
with a nominal 95% t interval over the 8 blocks. The requests per second values are
|
|
141
|
+
the geometric means of each side, and the CPU values are the arithmetic means.
|
|
142
|
+
- CPU time per response is the CPU time of the API container in the measurement
|
|
143
|
+
window divided by the number of checked responses. Because the API core was
|
|
144
|
+
saturated, it is close to the inverse of throughput, so the CPU change is not
|
|
145
|
+
independent of the throughput change.
|
|
146
|
+
|
|
147
|
+
</details>
|
|
148
|
+
|
|
149
|
+
Things to keep in mind:
|
|
150
|
+
|
|
151
|
+
- On the control side, FastAPI parses the body with `json.loads` and then validates
|
|
152
|
+
it with Pydantic, which is FastAPI's standard path.
|
|
153
|
+
- The GET and search rows also include changes outside the router: database rows are
|
|
154
|
+
converted to msgspec Structs instead of Pydantic models and, for GET, the query model is
|
|
155
|
+
msgspec instead of Pydantic, so they measure a migration, not the router alone.
|
|
156
|
+
- Both sides check the same constraints, including custom per-record checks written
|
|
157
|
+
in Python. Results for other schemas and other routes will differ.
|
|
158
|
+
- This is one series on one machine. A control that compared the msgspec version of the
|
|
159
|
+
GET route with itself in the same way gave a throughput change of +0.1% [-0.9%,
|
|
160
|
+
+1.1%], an interval that includes zero. Compare the relative effects rather than the
|
|
161
|
+
absolute numbers.
|
|
162
|
+
|
|
163
|
+
## What it does
|
|
164
|
+
|
|
165
|
+
The package uses msgspec for its JSON validation and encoding, without calling Pydantic
|
|
166
|
+
validators or serializers. FastAPI still depends on Pydantic for its own internals.
|
|
167
|
+
|
|
168
|
+
- A msgspec body parameter (a Struct or another type msgspec can decode) is decoded from
|
|
169
|
+
the raw request bytes by a `msgspec.json.Decoder` built once at route registration. A
|
|
170
|
+
body with a non-JSON content type returns 415, malformed JSON or JSON nested too deeply
|
|
171
|
+
returns 400, and a missing or invalid body returns 422. The 415 and 400 responses are
|
|
172
|
+
sent before dependencies run; a 422 is sent after them, as in FastAPI, so a failing
|
|
173
|
+
dependency such as authentication takes precedence. Bodies are decoded in msgspec
|
|
174
|
+
strict mode: for example, the JSON string `"1"` is not accepted for an `int` field,
|
|
175
|
+
unlike FastAPI with Pydantic.
|
|
176
|
+
- A body without a content type follows FastAPI's `strict_content_type` setting: it is
|
|
177
|
+
rejected with 415 by default and parsed as JSON when the setting is `False`. FastAPI
|
|
178
|
+
returns 422 in the first case.
|
|
179
|
+
- A msgspec response type, from the return annotation or `response_model`, is encoded
|
|
180
|
+
with msgspec. An instance of exactly the declared Struct class is encoded without
|
|
181
|
+
revalidation, as FastAPI does for a Pydantic `response_model`; other values are
|
|
182
|
+
validated against the declared type. Nested values and type parameters of a trusted
|
|
183
|
+
instance are not checked. A NaN or infinite value in a `float` field is encoded as
|
|
184
|
+
`null` unless a constraint rejects it. In a `Decimal` field it is encoded as a string,
|
|
185
|
+
while FastAPI with Pydantic rejects non-finite `Decimal` values.
|
|
186
|
+
- With the default `MsgspecJSONResponse`, responses of routes without a return
|
|
187
|
+
annotation or `response_model`, or with `-> None`, are also encoded with msgspec.
|
|
188
|
+
In addition to msgspec's built-in types, `pathlib` paths and standard-library IP
|
|
189
|
+
addresses, interfaces and networks are encoded as strings. Other objects, including
|
|
190
|
+
`BaseModel` instances, `HttpUrl` and `SecretStr`, are unsupported and raise `TypeError`
|
|
191
|
+
during encoding. Values supported directly by msgspec retain its encoding: for example,
|
|
192
|
+
`bytes` are base64-encoded and `Decimal` is encoded as a string.
|
|
193
|
+
- Path, query, header and cookie parameters keep FastAPI extraction, aliases and
|
|
194
|
+
defaults, but are converted with `msgspec.convert(strict=False)` instead of Pydantic,
|
|
195
|
+
so coercion differs for some inputs (for example, `" 1.5"` is rejected for `float`
|
|
196
|
+
and `"nan"` is accepted for `Decimal`). Parameter types must be supported by msgspec;
|
|
197
|
+
Pydantic-specific types such as `AnyUrl` raise `TypeError` at route registration.
|
|
198
|
+
- On the msgspec validation path, string `pattern` constraints from FastAPI parameters,
|
|
199
|
+
`Body` and supported nested `Field` annotations use Rust's `regex` engine through
|
|
200
|
+
`regexrs-py`, without catastrophic backtracking. Patterns are compiled once at route
|
|
201
|
+
registration. Compiled Python `re.Pattern` objects are rejected rather than falling
|
|
202
|
+
back to a backtracking engine.
|
|
203
|
+
Native `msgspec.Meta(pattern=...)` constraints retain msgspec's Python regex behavior
|
|
204
|
+
and are outside this protection.
|
|
205
|
+
- Generator endpoints support JSON Lines with the default response class and SSE with
|
|
206
|
+
`response_class=EventSourceResponse`. Plain yielded items with declared msgspec
|
|
207
|
+
types are validated with the same instance-trust rules as ordinary responses. Untyped
|
|
208
|
+
yielded values are also encoded with msgspec. Explicit instances of the exact
|
|
209
|
+
`ServerSentEvent` class support preformatted `raw_data` and metadata-only events;
|
|
210
|
+
subclasses are unsupported. A non-`None` `data` payload without
|
|
211
|
+
`raw_data` is rejected. For a Struct or Raw payload with event metadata, use
|
|
212
|
+
`ServerSentEvent(raw_data=msgspec.json.encode(payload).decode('utf-8'), id='...')`.
|
|
213
|
+
Explicit `StreamingResponse` keeps raw chunks. Streaming bodies retain dependency
|
|
214
|
+
validation and generator cleanup.
|
|
215
|
+
- Custom response classes are supported. Typed response validation and field projection
|
|
216
|
+
happen before response construction. A `JSONResponse` class that does not inherit
|
|
217
|
+
`MsgspecJSONResponse` receives JSON-compatible values converted with msgspec, including
|
|
218
|
+
for untyped returns. Returned `Response` instances pass through unchanged.
|
|
219
|
+
- Structural JSON body errors include field names, encoded aliases, keys and indices,
|
|
220
|
+
with multiple errors for supported Structs, regular dataclasses, TypedDicts and
|
|
221
|
+
built-in containers. Diagnostics never repeat model validation hooks or default
|
|
222
|
+
factories: types with hooks or unsupported diagnostic shapes retain the original
|
|
223
|
+
first error. The default 422 handler encodes error details with msgspec; custom
|
|
224
|
+
application exception handlers are preserved. Exceptions and uploaded files that
|
|
225
|
+
cannot be encoded with msgspec, such as the exception raised by a validator and stored
|
|
226
|
+
in `ctx['error']`, or a file in `input`, are rendered as empty objects without their
|
|
227
|
+
attributes. In FastAPI responses a plain `ValueError` is rendered the same way, but
|
|
228
|
+
the attributes of uploaded files and custom exceptions are included. Other values in
|
|
229
|
+
error details, for example ones added by dependencies, must also be encodable by this
|
|
230
|
+
encoder or handled by a custom exception handler.
|
|
231
|
+
- `install_openapi(app)` adds the msgspec JSON schemas to the OpenAPI document. Call it
|
|
232
|
+
once before serving. Routes, webhooks and callbacks are discovered from the application
|
|
233
|
+
when the document is built; the optional router arguments remain accepted for
|
|
234
|
+
compatibility. Hidden routes do not add msgspec components. As in FastAPI, the document
|
|
235
|
+
is cached: set `app.openapi_schema = None` to rebuild it after adding routes.
|
|
236
|
+
- Body descriptions and examples, `openapi_extra` request metadata and response examples
|
|
237
|
+
are preserved. JSON body routes document their 400, 415 and 422 responses.
|
|
238
|
+
- JSON body and response types must be supported by msgspec. Pydantic models and
|
|
239
|
+
custom Pydantic types are rejected at route registration. Pydantic data objects are
|
|
240
|
+
also rejected before implicit copies of defaults and route metadata.
|
|
241
|
+
|
|
242
|
+
## Limitations
|
|
243
|
+
|
|
244
|
+
- Only one msgspec body parameter per route, and it cannot be combined with other
|
|
245
|
+
FastAPI body fields. Only JSON bodies are supported: `application/json`,
|
|
246
|
+
`application/*+json`, or a request without a content type when `strict_content_type`
|
|
247
|
+
is `False`. JSON body parameters in `Depends` functions are not supported; declare
|
|
248
|
+
the JSON body on the route endpoint. `Form()` and `File()` parameters are left to FastAPI.
|
|
249
|
+
- On ordinary non-streaming routes, when both the parameters and body are invalid, only
|
|
250
|
+
the parameter errors are returned; FastAPI returns both.
|
|
251
|
+
- A custom `route_class` or `route_class_override` must extend `MsgspecRoute`.
|
|
252
|
+
- Structs, alone or inside containers, are not supported as path, query, header or
|
|
253
|
+
cookie parameters, or as `Form()` and `File()` parameters.
|
|
254
|
+
- Defaults and copied metadata support built-in scalars and exact built-in containers,
|
|
255
|
+
standard-library values such as `datetime`, `Decimal`, `UUID`, `pathlib` paths and IP
|
|
256
|
+
addresses, enums, Structs and dataclasses. They do not support instances of other
|
|
257
|
+
classes (for example an `object()` sentinel), container subclasses, custom
|
|
258
|
+
state/reduction methods, registered copy reducers, dynamic attribute access or custom
|
|
259
|
+
copy descriptors. Ordinary application-defined Python `__deepcopy__` methods and
|
|
260
|
+
default factories remain application code.
|
|
261
|
+
- `response_model_include`, `response_model_exclude`, `response_model_exclude_*` and
|
|
262
|
+
`response_model_by_alias=False` are rejected for typed msgspec responses.
|
|
263
|
+
|
|
264
|
+
## Development
|
|
265
|
+
|
|
266
|
+
```sh
|
|
267
|
+
uv sync --group test --group lint --group typing
|
|
268
|
+
uv run --group test pytest
|
|
269
|
+
uv run --group lint ruff check .
|
|
270
|
+
uv run --group lint ruff format --check .
|
|
271
|
+
uv run --group typing mypy src/msgspec_fastapi --follow-imports=silent
|
|
272
|
+
uv run --group typing python -m mypy.stubtest msgspec_fastapi._defaults
|
|
273
|
+
uv run --group lint pre-commit install
|
|
274
|
+
uv run --group lint pre-commit run --all-files
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
After changing C sources, rebuild the extension with
|
|
278
|
+
`uv sync --reinstall-package msgspec-fastapi --group test --group lint --group typing`.
|
|
279
|
+
|
|
280
|
+
Ruff checks imports, annotations and common Python errors, and formats the code.
|
|
281
|
+
CI runs the same Ruff version as the pre-commit hooks. Test endpoints that exercise the absence
|
|
282
|
+
of a response annotation intentionally omit it.
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
# msgspec-fastapi
|
|
2
|
+
|
|
3
|
+
A FastAPI router that uses msgspec for JSON request bodies and responses.
|
|
4
|
+
In one benchmark service, moving from Pydantic models to msgspec Structs with this
|
|
5
|
+
router increased the throughput of one saturated API core by 68% on a route with a large
|
|
6
|
+
JSON body and by about 12% on database-backed routes; see the Benchmarks section below.
|
|
7
|
+
|
|
8
|
+
This project uses ZeroVer: the major version will always stay at 0. There will be no
|
|
9
|
+
1.0 release. The API may change in 0.x releases. The router relies on private FastAPI
|
|
10
|
+
internals, so it is pinned to FastAPI 0.142.2 to 0.165.x. It is a personal project,
|
|
11
|
+
not part of msgspec; feedback is welcome in the issues.
|
|
12
|
+
|
|
13
|
+

|
|
14
|
+
|
|
15
|
+

|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
pip install msgspec-fastapi
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The package includes an internal C extension for checking copied defaults and
|
|
24
|
+
metadata. Building from source requires a C11 compiler and CPython headers.
|
|
25
|
+
|
|
26
|
+
On free-threaded CPython 3.14t the package runs with the GIL enabled: the extension is
|
|
27
|
+
not yet marked as safe to run without it, so importing the package enables the GIL and
|
|
28
|
+
emits a `RuntimeWarning`. Set `PYTHON_GIL=1` to enable the GIL from the start and avoid
|
|
29
|
+
the warning; running with `PYTHON_GIL=0` is not supported.
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
import msgspec
|
|
35
|
+
from fastapi import FastAPI
|
|
36
|
+
from msgspec_fastapi import MsgspecRouter, install_openapi
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class City(msgspec.Struct):
|
|
40
|
+
name: str
|
|
41
|
+
population: int
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
router = MsgspecRouter()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@router.post('/cities')
|
|
48
|
+
async def create_city(city: City) -> City:
|
|
49
|
+
return city
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
app = FastAPI()
|
|
53
|
+
app.include_router(router)
|
|
54
|
+
install_openapi(app)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Benchmarks
|
|
58
|
+
|
|
59
|
+
The router was measured in a small reference-data service on a cloud VM (November 2026).
|
|
60
|
+
Each row compares the same service on FastAPI with Pydantic models against the same
|
|
61
|
+
service with msgspec Structs and `MsgspecRouter`. The database queries (SQLAlchemy ORM),
|
|
62
|
+
event loop and server settings are the same on both sides, and there is no cache.
|
|
63
|
+
|
|
64
|
+
| Request | Requests per second | RPS change | CPU time per response | CPU change |
|
|
65
|
+
|---|---|---|---|---|
|
|
66
|
+
| `POST /cities/validate`, a JSON body of 100 cities (23 KB), no database | 1,786 → 3,000 | **+68.0%** [+66.0%, +70.0%] | 560 → 333 µs | **-40.5%** [-41.2%, -39.7%] |
|
|
67
|
+
| `GET /cities?limit=100`, a page of 100 cities read from PostgreSQL | 489 → 549 | **+12.3%** [+11.1%, +13.4%] | 2,047 → 1,823 µs | **-10.9%** [-11.9%, -10.0%] |
|
|
68
|
+
| `POST /cities/search`, small JSON filter bodies, a page of 100 cities | 419 → 469 | **+11.9%** [+10.8%, +13.0%] | 2,387 → 2,133 µs | **-10.6%** [-11.5%, -9.7%] |
|
|
69
|
+
|
|
70
|
+
The first route returns a constant 16-byte response (`{"accepted":100}`), so the
|
|
71
|
+
difference on this route comes mostly from request decoding and validation, and the gain
|
|
72
|
+
is largest there. On routes that read from a database, API CPU time per response falls
|
|
73
|
+
by about 220 to 250 µs out of roughly 2 ms, so the relative gain is smaller. At a fixed
|
|
74
|
+
load below saturation, measured in two runs per side without an interval, API CPU time
|
|
75
|
+
per response was about 8% (about 155 µs) lower on GET at 300 requests per second, about
|
|
76
|
+
8% (about 200 µs) lower on search at 200 and 39% (about 240 µs) lower on the first route
|
|
77
|
+
at 1,200; the two runs of one variant differed by up to 4%. The memory use of the API
|
|
78
|
+
process (median RSS of about 98 to 102 MiB) differed by less than 1% on all three routes.
|
|
79
|
+
|
|
80
|
+
In the same service, setting `response_model=None` on the GET route made no detectable
|
|
81
|
+
difference in throughput with `MsgspecRouter` (+0.2% [-1.1%, +1.5%], an interval that
|
|
82
|
+
includes zero). This is consistent with an instance of exactly the declared Struct class
|
|
83
|
+
being encoded without revalidation.
|
|
84
|
+
|
|
85
|
+
These numbers are series 10 of
|
|
86
|
+
[world-directory-bench](https://github.com/Siyet/world-directory-bench/tree/series-10#series-10-msgspec-fastapi-010-readme-comparisons),
|
|
87
|
+
which also contains the service, the data preparation scripts and other comparisons in
|
|
88
|
+
the same service, including direct asyncpg queries without the ORM, a Redis cache,
|
|
89
|
+
Litestar and Go.
|
|
90
|
+
|
|
91
|
+
<details>
|
|
92
|
+
<summary>How it was measured</summary>
|
|
93
|
+
|
|
94
|
+
- Host: a KVM cloud VM with 6 vCPUs on a plan advertised with dedicated cores, Ubuntu
|
|
95
|
+
24.04. The API ran as one uvicorn worker pinned to one core, with httptools and uvloop
|
|
96
|
+
(what uvicorn uses when they are installed, for example with `fastapi[standard]`) and
|
|
97
|
+
the access log off. PostgreSQL and the load generator ran on other cores.
|
|
98
|
+
- Data and database: 224,578 cities, 55,246 division records, 501 country records and
|
|
99
|
+
86,185 airports from GeoNames and OurAirports, about 231 MB in PostgreSQL 18.6
|
|
100
|
+
including indexes. The PostgreSQL data directory was on tmpfs (in memory). Database
|
|
101
|
+
access went through the SQLAlchemy ORM with the asyncpg driver.
|
|
102
|
+
- Software: msgspec-fastapi 0.1.0, CPython 3.14.10, FastAPI 0.165.0, Pydantic 2.14.3,
|
|
103
|
+
msgspec 0.22.0, SQLAlchemy 2.1.9 (ORM), asyncpg 0.32.0, uvicorn 0.54.0 with httptools
|
|
104
|
+
0.9.0 and uvloop 0.23.0.
|
|
105
|
+
- Load: a Go generator with 20 closed-loop clients, checking every response body. The
|
|
106
|
+
numbers are throughput at saturation of the single API core. The GET mix sends 9 of
|
|
107
|
+
10 requests to one page and every 10th to a page that is not repeated within the run.
|
|
108
|
+
- Each comparison is 8 blocks in ABBA or BAAB order, so each block measures both
|
|
109
|
+
versions twice; every run starts a fresh process with a 30 s warmup and a 60 s
|
|
110
|
+
measurement. The percentages are computed from the mean of the per-block log ratios,
|
|
111
|
+
with a nominal 95% t interval over the 8 blocks. The requests per second values are
|
|
112
|
+
the geometric means of each side, and the CPU values are the arithmetic means.
|
|
113
|
+
- CPU time per response is the CPU time of the API container in the measurement
|
|
114
|
+
window divided by the number of checked responses. Because the API core was
|
|
115
|
+
saturated, it is close to the inverse of throughput, so the CPU change is not
|
|
116
|
+
independent of the throughput change.
|
|
117
|
+
|
|
118
|
+
</details>
|
|
119
|
+
|
|
120
|
+
Things to keep in mind:
|
|
121
|
+
|
|
122
|
+
- On the control side, FastAPI parses the body with `json.loads` and then validates
|
|
123
|
+
it with Pydantic, which is FastAPI's standard path.
|
|
124
|
+
- The GET and search rows also include changes outside the router: database rows are
|
|
125
|
+
converted to msgspec Structs instead of Pydantic models and, for GET, the query model is
|
|
126
|
+
msgspec instead of Pydantic, so they measure a migration, not the router alone.
|
|
127
|
+
- Both sides check the same constraints, including custom per-record checks written
|
|
128
|
+
in Python. Results for other schemas and other routes will differ.
|
|
129
|
+
- This is one series on one machine. A control that compared the msgspec version of the
|
|
130
|
+
GET route with itself in the same way gave a throughput change of +0.1% [-0.9%,
|
|
131
|
+
+1.1%], an interval that includes zero. Compare the relative effects rather than the
|
|
132
|
+
absolute numbers.
|
|
133
|
+
|
|
134
|
+
## What it does
|
|
135
|
+
|
|
136
|
+
The package uses msgspec for its JSON validation and encoding, without calling Pydantic
|
|
137
|
+
validators or serializers. FastAPI still depends on Pydantic for its own internals.
|
|
138
|
+
|
|
139
|
+
- A msgspec body parameter (a Struct or another type msgspec can decode) is decoded from
|
|
140
|
+
the raw request bytes by a `msgspec.json.Decoder` built once at route registration. A
|
|
141
|
+
body with a non-JSON content type returns 415, malformed JSON or JSON nested too deeply
|
|
142
|
+
returns 400, and a missing or invalid body returns 422. The 415 and 400 responses are
|
|
143
|
+
sent before dependencies run; a 422 is sent after them, as in FastAPI, so a failing
|
|
144
|
+
dependency such as authentication takes precedence. Bodies are decoded in msgspec
|
|
145
|
+
strict mode: for example, the JSON string `"1"` is not accepted for an `int` field,
|
|
146
|
+
unlike FastAPI with Pydantic.
|
|
147
|
+
- A body without a content type follows FastAPI's `strict_content_type` setting: it is
|
|
148
|
+
rejected with 415 by default and parsed as JSON when the setting is `False`. FastAPI
|
|
149
|
+
returns 422 in the first case.
|
|
150
|
+
- A msgspec response type, from the return annotation or `response_model`, is encoded
|
|
151
|
+
with msgspec. An instance of exactly the declared Struct class is encoded without
|
|
152
|
+
revalidation, as FastAPI does for a Pydantic `response_model`; other values are
|
|
153
|
+
validated against the declared type. Nested values and type parameters of a trusted
|
|
154
|
+
instance are not checked. A NaN or infinite value in a `float` field is encoded as
|
|
155
|
+
`null` unless a constraint rejects it. In a `Decimal` field it is encoded as a string,
|
|
156
|
+
while FastAPI with Pydantic rejects non-finite `Decimal` values.
|
|
157
|
+
- With the default `MsgspecJSONResponse`, responses of routes without a return
|
|
158
|
+
annotation or `response_model`, or with `-> None`, are also encoded with msgspec.
|
|
159
|
+
In addition to msgspec's built-in types, `pathlib` paths and standard-library IP
|
|
160
|
+
addresses, interfaces and networks are encoded as strings. Other objects, including
|
|
161
|
+
`BaseModel` instances, `HttpUrl` and `SecretStr`, are unsupported and raise `TypeError`
|
|
162
|
+
during encoding. Values supported directly by msgspec retain its encoding: for example,
|
|
163
|
+
`bytes` are base64-encoded and `Decimal` is encoded as a string.
|
|
164
|
+
- Path, query, header and cookie parameters keep FastAPI extraction, aliases and
|
|
165
|
+
defaults, but are converted with `msgspec.convert(strict=False)` instead of Pydantic,
|
|
166
|
+
so coercion differs for some inputs (for example, `" 1.5"` is rejected for `float`
|
|
167
|
+
and `"nan"` is accepted for `Decimal`). Parameter types must be supported by msgspec;
|
|
168
|
+
Pydantic-specific types such as `AnyUrl` raise `TypeError` at route registration.
|
|
169
|
+
- On the msgspec validation path, string `pattern` constraints from FastAPI parameters,
|
|
170
|
+
`Body` and supported nested `Field` annotations use Rust's `regex` engine through
|
|
171
|
+
`regexrs-py`, without catastrophic backtracking. Patterns are compiled once at route
|
|
172
|
+
registration. Compiled Python `re.Pattern` objects are rejected rather than falling
|
|
173
|
+
back to a backtracking engine.
|
|
174
|
+
Native `msgspec.Meta(pattern=...)` constraints retain msgspec's Python regex behavior
|
|
175
|
+
and are outside this protection.
|
|
176
|
+
- Generator endpoints support JSON Lines with the default response class and SSE with
|
|
177
|
+
`response_class=EventSourceResponse`. Plain yielded items with declared msgspec
|
|
178
|
+
types are validated with the same instance-trust rules as ordinary responses. Untyped
|
|
179
|
+
yielded values are also encoded with msgspec. Explicit instances of the exact
|
|
180
|
+
`ServerSentEvent` class support preformatted `raw_data` and metadata-only events;
|
|
181
|
+
subclasses are unsupported. A non-`None` `data` payload without
|
|
182
|
+
`raw_data` is rejected. For a Struct or Raw payload with event metadata, use
|
|
183
|
+
`ServerSentEvent(raw_data=msgspec.json.encode(payload).decode('utf-8'), id='...')`.
|
|
184
|
+
Explicit `StreamingResponse` keeps raw chunks. Streaming bodies retain dependency
|
|
185
|
+
validation and generator cleanup.
|
|
186
|
+
- Custom response classes are supported. Typed response validation and field projection
|
|
187
|
+
happen before response construction. A `JSONResponse` class that does not inherit
|
|
188
|
+
`MsgspecJSONResponse` receives JSON-compatible values converted with msgspec, including
|
|
189
|
+
for untyped returns. Returned `Response` instances pass through unchanged.
|
|
190
|
+
- Structural JSON body errors include field names, encoded aliases, keys and indices,
|
|
191
|
+
with multiple errors for supported Structs, regular dataclasses, TypedDicts and
|
|
192
|
+
built-in containers. Diagnostics never repeat model validation hooks or default
|
|
193
|
+
factories: types with hooks or unsupported diagnostic shapes retain the original
|
|
194
|
+
first error. The default 422 handler encodes error details with msgspec; custom
|
|
195
|
+
application exception handlers are preserved. Exceptions and uploaded files that
|
|
196
|
+
cannot be encoded with msgspec, such as the exception raised by a validator and stored
|
|
197
|
+
in `ctx['error']`, or a file in `input`, are rendered as empty objects without their
|
|
198
|
+
attributes. In FastAPI responses a plain `ValueError` is rendered the same way, but
|
|
199
|
+
the attributes of uploaded files and custom exceptions are included. Other values in
|
|
200
|
+
error details, for example ones added by dependencies, must also be encodable by this
|
|
201
|
+
encoder or handled by a custom exception handler.
|
|
202
|
+
- `install_openapi(app)` adds the msgspec JSON schemas to the OpenAPI document. Call it
|
|
203
|
+
once before serving. Routes, webhooks and callbacks are discovered from the application
|
|
204
|
+
when the document is built; the optional router arguments remain accepted for
|
|
205
|
+
compatibility. Hidden routes do not add msgspec components. As in FastAPI, the document
|
|
206
|
+
is cached: set `app.openapi_schema = None` to rebuild it after adding routes.
|
|
207
|
+
- Body descriptions and examples, `openapi_extra` request metadata and response examples
|
|
208
|
+
are preserved. JSON body routes document their 400, 415 and 422 responses.
|
|
209
|
+
- JSON body and response types must be supported by msgspec. Pydantic models and
|
|
210
|
+
custom Pydantic types are rejected at route registration. Pydantic data objects are
|
|
211
|
+
also rejected before implicit copies of defaults and route metadata.
|
|
212
|
+
|
|
213
|
+
## Limitations
|
|
214
|
+
|
|
215
|
+
- Only one msgspec body parameter per route, and it cannot be combined with other
|
|
216
|
+
FastAPI body fields. Only JSON bodies are supported: `application/json`,
|
|
217
|
+
`application/*+json`, or a request without a content type when `strict_content_type`
|
|
218
|
+
is `False`. JSON body parameters in `Depends` functions are not supported; declare
|
|
219
|
+
the JSON body on the route endpoint. `Form()` and `File()` parameters are left to FastAPI.
|
|
220
|
+
- On ordinary non-streaming routes, when both the parameters and body are invalid, only
|
|
221
|
+
the parameter errors are returned; FastAPI returns both.
|
|
222
|
+
- A custom `route_class` or `route_class_override` must extend `MsgspecRoute`.
|
|
223
|
+
- Structs, alone or inside containers, are not supported as path, query, header or
|
|
224
|
+
cookie parameters, or as `Form()` and `File()` parameters.
|
|
225
|
+
- Defaults and copied metadata support built-in scalars and exact built-in containers,
|
|
226
|
+
standard-library values such as `datetime`, `Decimal`, `UUID`, `pathlib` paths and IP
|
|
227
|
+
addresses, enums, Structs and dataclasses. They do not support instances of other
|
|
228
|
+
classes (for example an `object()` sentinel), container subclasses, custom
|
|
229
|
+
state/reduction methods, registered copy reducers, dynamic attribute access or custom
|
|
230
|
+
copy descriptors. Ordinary application-defined Python `__deepcopy__` methods and
|
|
231
|
+
default factories remain application code.
|
|
232
|
+
- `response_model_include`, `response_model_exclude`, `response_model_exclude_*` and
|
|
233
|
+
`response_model_by_alias=False` are rejected for typed msgspec responses.
|
|
234
|
+
|
|
235
|
+
## Development
|
|
236
|
+
|
|
237
|
+
```sh
|
|
238
|
+
uv sync --group test --group lint --group typing
|
|
239
|
+
uv run --group test pytest
|
|
240
|
+
uv run --group lint ruff check .
|
|
241
|
+
uv run --group lint ruff format --check .
|
|
242
|
+
uv run --group typing mypy src/msgspec_fastapi --follow-imports=silent
|
|
243
|
+
uv run --group typing python -m mypy.stubtest msgspec_fastapi._defaults
|
|
244
|
+
uv run --group lint pre-commit install
|
|
245
|
+
uv run --group lint pre-commit run --all-files
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
After changing C sources, rebuild the extension with
|
|
249
|
+
`uv sync --reinstall-package msgspec-fastapi --group test --group lint --group typing`.
|
|
250
|
+
|
|
251
|
+
Ruff checks imports, annotations and common Python errors, and formats the code.
|
|
252
|
+
CI runs the same Ruff version as the pre-commit hooks. Test endpoints that exercise the absence
|
|
253
|
+
of a response annotation intentionally omit it.
|