msgspec-fastapi 0.0.1__tar.gz → 0.0.3__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,60 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ workflow_dispatch:
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ concurrency:
13
+ group: ${{ github.workflow }}-${{ github.ref }}
14
+ cancel-in-progress: true
15
+
16
+ jobs:
17
+ test:
18
+ name: Python ${{ matrix.python }}, ${{ matrix.bounds }} dependency bounds
19
+ runs-on: ubuntu-latest
20
+ strategy:
21
+ fail-fast: false
22
+ matrix:
23
+ python: ["3.11", "3.12", "3.13", "3.14"]
24
+ bounds: [latest, lowest]
25
+ env:
26
+ PYTHON: ${{ matrix.python }}
27
+ steps:
28
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
29
+ with:
30
+ persist-credentials: false
31
+ - uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0
32
+ with:
33
+ enable-cache: false
34
+ - name: Install
35
+ run: uv sync --python "$PYTHON" --group test
36
+ - name: Install the lowest supported FastAPI and msgspec
37
+ if: matrix.bounds == 'lowest'
38
+ run: uv pip install "fastapi==0.142.2" "msgspec==0.22.0"
39
+ - name: Show versions
40
+ run: uv run --no-sync python -c "import sys, fastapi, msgspec, pydantic, starlette; print(sys.version); print(fastapi.__version__, msgspec.__version__, pydantic.__version__, starlette.__version__)"
41
+ - name: Check the lowest versions
42
+ if: matrix.bounds == 'lowest'
43
+ # `uv run` without --no-sync would reinstall the locked versions.
44
+ run: uv run --no-sync python -c "import fastapi, msgspec; assert (fastapi.__version__, msgspec.__version__) == ('0.142.2', '0.22.0')"
45
+ - name: Test
46
+ run: uv run --no-sync pytest
47
+
48
+ build:
49
+ runs-on: ubuntu-latest
50
+ steps:
51
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
52
+ with:
53
+ persist-credentials: false
54
+ - uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0
55
+ with:
56
+ enable-cache: false
57
+ - name: Build
58
+ run: uv build
59
+ - name: Check the distributions
60
+ run: uvx twine@7.0.0 check --strict dist/*
@@ -0,0 +1,185 @@
1
+ Metadata-Version: 2.5
2
+ Name: msgspec-fastapi
3
+ Version: 0.0.3
4
+ Summary: Experimental FastAPI router that decodes request bodies and encodes responses with msgspec
5
+ Project-URL: Source, https://github.com/Siyet/msgspec-fastapi
6
+ Project-URL: Issues, https://github.com/Siyet/msgspec-fastapi/issues
7
+ Author: Aleksandr Tseluiko
8
+ License-Expression: BSD-3-Clause
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Framework :: FastAPI
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.11
14
+ Requires-Dist: fastapi<0.148,>=0.142.2
15
+ Requires-Dist: msgspec>=0.22.0
16
+ Description-Content-Type: text/markdown
17
+
18
+ # msgspec-fastapi
19
+
20
+ An experimental FastAPI router that uses msgspec for JSON request bodies and responses.
21
+ In one benchmark service, moving from Pydantic models to msgspec Structs with this router
22
+ increased throughput by 68% on a route with a large JSON body and by 11% to 13% on
23
+ database-backed routes; see the Benchmarks section below.
24
+
25
+ This is a prototype. Its API may change, and it relies on private FastAPI internals, so
26
+ it is pinned to FastAPI 0.142.2 to 0.147.x. It is a personal project, not part of
27
+ msgspec; feedback is welcome in the issues.
28
+
29
+ ## Installation
30
+
31
+ ```sh
32
+ pip install msgspec-fastapi
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ```python
38
+ import msgspec
39
+ from fastapi import FastAPI
40
+ from msgspec_fastapi import MsgspecRouter, install_openapi
41
+
42
+
43
+ class City(msgspec.Struct):
44
+ name: str
45
+ population: int
46
+
47
+
48
+ router = MsgspecRouter()
49
+
50
+
51
+ @router.post('/cities')
52
+ async def create_city(city: City) -> City:
53
+ return city
54
+
55
+
56
+ app = FastAPI()
57
+ app.include_router(router)
58
+ install_openapi(app, router)
59
+ ```
60
+
61
+ ## Benchmarks
62
+
63
+ The router was measured in a small reference-data service on a cloud VM with dedicated
64
+ vCPUs (October 2026). Each row compares the same service on FastAPI with Pydantic models
65
+ against the same service with msgspec Structs and `MsgspecRouter`. The database queries
66
+ (SQLAlchemy ORM), event loop and server settings are the same on both sides, and there
67
+ is no cache.
68
+
69
+ | Request | Requests per second | RPS change | CPU time per response | CPU change |
70
+ |---|---|---|---|---|
71
+ | `POST /cities/validate`, a JSON body of 100 cities (23 KB), no database | 1,610 → 2,703 | **+67.9%** [+67.0%, +68.7%] | 621 → 370 µs | **-40.4%** [-40.7%, -40.1%] |
72
+ | `GET /cities?limit=100`, a page of 100 cities read from PostgreSQL | 514 → 569 | **+10.7%** [+9.9%, +11.5%] | 1,944 → 1,757 µs | **-9.7%** [-10.3%, -9.0%] |
73
+ | `POST /cities/search`, small JSON filter bodies, a page of 100 cities | 447 → 505 | **+12.9%** [+12.1%, +13.7%] | 2,237 → 1,981 µs | **-11.4%** [-12.1%, -10.8%] |
74
+
75
+ The first route returns a constant 16-byte response (`{"accepted":100}`), so the
76
+ difference on this route comes mostly from request decoding and validation, and the gain
77
+ is largest there. On routes that read from a database, API CPU time per response falls by
78
+ about 190 to 260 µs out of roughly 2 ms, so the relative gain is smaller.
79
+
80
+ In the same service, setting `response_model=None` on the GET route made no detectable
81
+ difference in throughput with `MsgspecRouter` (0.0% [-1.0%, +1.0%]). This is consistent
82
+ with an instance of exactly the declared Struct class being encoded without
83
+ revalidation.
84
+
85
+ The benchmark sources, the data preparation scripts and the results of all 14
86
+ comparisons, including direct asyncpg queries without the ORM, uvloop, a Redis cache,
87
+ Litestar and Go, are in
88
+ [world-directory-bench](https://github.com/Siyet/world-directory-bench).
89
+
90
+ <details>
91
+ <summary>How it was measured</summary>
92
+
93
+ - Host: a cloud VM with 6 dedicated vCPUs (AMD EPYC-Rome, KVM), Ubuntu 24.04. The API
94
+ ran as one uvicorn worker (h11, asyncio) pinned to one core; PostgreSQL and the load
95
+ generator ran on other cores.
96
+ - Data and database: 224,578 cities, 55,246 division records, 501 country records and
97
+ 86,185 airports from GeoNames and OurAirports, about 231 MB in PostgreSQL 18.6
98
+ including indexes. The PostgreSQL data directory was on tmpfs (in memory). Database
99
+ access went through the SQLAlchemy ORM with the asyncpg driver.
100
+ - Software: CPython 3.14.7, FastAPI 0.142.2, Pydantic 2.13.5, msgspec 0.22.0,
101
+ SQLAlchemy 2.1.3 (ORM), asyncpg 0.31.0, uvicorn 0.54.0. The router code on the
102
+ measured paths was the same as msgspec-fastapi 0.0.1.
103
+ - Load: a Go generator with 20 closed-loop clients, checking every response body. The
104
+ numbers are throughput at saturation of the single API core. The GET mix sends 9 of
105
+ 10 requests to one page and every 10th to a page that is not repeated within the run.
106
+ - Each comparison is 8 blocks in ABBA or BAAB order, so each block measures both
107
+ versions twice; every run starts a fresh process with a 30 s warmup and a 60 s
108
+ measurement. The percentages are computed from the mean of the per-block log ratios,
109
+ with a nominal 95% t interval over the 8 blocks. The requests per second values are
110
+ the geometric means of each side, and the CPU values are the arithmetic means.
111
+ - CPU time per response is the CPU time of the API container in the measurement
112
+ window divided by the number of checked responses. Because the API core was
113
+ saturated, it is close to the inverse of throughput.
114
+
115
+ </details>
116
+
117
+ Things to keep in mind:
118
+
119
+ - On the control side, FastAPI parses the body with `json.loads` and then validates
120
+ it with Pydantic, which is FastAPI's standard path.
121
+ - The GET and search rows also include changes outside the router: database rows are
122
+ converted to msgspec Structs instead of Pydantic models and, for GET, the query model is
123
+ msgspec instead of Pydantic, so they measure a migration, not the router alone.
124
+ - Both sides check the same constraints, including custom per-record checks written
125
+ in Python. Results for other schemas and other routes will differ.
126
+ - This is one series on one machine. The host slowed down near the end of the series: a
127
+ static control was about 10% slower after the series than before it. The blocks of
128
+ all comparisons ran in 8 rounds, and the lasting slowdown began during the last
129
+ round. Leaving out any single round, the last one included, changes each estimate by
130
+ less than 0.32 percentage points. Compare the relative effects rather than the
131
+ absolute numbers.
132
+
133
+ ## What it does
134
+
135
+ - A msgspec body parameter (a Struct or another type msgspec can decode) is decoded from
136
+ the raw request bytes by a `msgspec.json.Decoder` built once at route registration. A
137
+ body with a non-JSON content type returns 415, malformed JSON or JSON nested too deeply
138
+ returns 400, and a missing or invalid body returns 422. The 415 and 400 responses are
139
+ sent before dependencies run; a 422 is sent after them, as in FastAPI, so a failing
140
+ dependency such as authentication takes precedence. Bodies are decoded in msgspec
141
+ strict mode: for example, the JSON string `"1"` is not accepted for an `int` field,
142
+ unlike FastAPI with Pydantic.
143
+ - A body without a content type follows FastAPI's `strict_content_type` setting: it is
144
+ rejected with 415 by default and parsed as JSON when the setting is `False`. FastAPI
145
+ returns 422 in the first case.
146
+ - A msgspec response type, from the return annotation or `response_model`, is encoded
147
+ with msgspec. An instance of exactly the declared Struct class is encoded without
148
+ revalidation, as FastAPI does for a Pydantic `response_model`; other values are
149
+ validated against the declared type. Nested values and type parameters of a trusted
150
+ instance are not checked. A NaN or infinite value in a `float` field is encoded as
151
+ `null` unless a constraint rejects it. In a `Decimal` field it is encoded as a string,
152
+ while FastAPI with Pydantic rejects non-finite `Decimal` values.
153
+ - Responses of routes without a return annotation or `response_model`, or with
154
+ `-> None`, are also encoded with msgspec, so the output can differ from FastAPI's
155
+ `jsonable_encoder` (for example, `bytes` are base64-encoded and `Decimal` is encoded as
156
+ a string).
157
+ - Path, query, header and cookie parameters keep FastAPI extraction, aliases and
158
+ defaults, but are converted with `msgspec.convert(strict=False)` instead of Pydantic,
159
+ so coercion differs for some inputs (for example, `" 1.5"` is rejected for `float`
160
+ and `"nan"` is accepted for `Decimal`). Parameter types must be supported by msgspec;
161
+ Pydantic-specific types such as `AnyUrl` raise `TypeError` at route registration.
162
+ - `install_openapi` adds the msgspec JSON schemas to the OpenAPI document. It is required
163
+ for a valid document: call it once after including the routers, passing every
164
+ `MsgspecRouter` that is not included directly in another `MsgspecRouter`.
165
+ - A Pydantic body or response model is left to FastAPI; the route parameters are still
166
+ validated with msgspec.
167
+
168
+ ## Limitations
169
+
170
+ - Only one msgspec body parameter per route, and it cannot be combined with other
171
+ FastAPI body fields. Only JSON bodies are supported: `application/json`,
172
+ `application/*+json`, or a request without a content type when `strict_content_type`
173
+ is `False`. `Form()` and `File()` parameters are left to FastAPI.
174
+ - When both the parameters and the body are invalid, only the parameter errors are
175
+ returned; FastAPI returns both.
176
+ - Structs, alone or inside containers, are not supported as path, query, header or
177
+ cookie parameters, or as `Form()` and `File()` parameters.
178
+ - `response_model_include`, `response_model_exclude`, `response_model_exclude_*` and
179
+ `response_model_by_alias=False` are rejected for typed msgspec responses.
180
+
181
+ ## Development
182
+
183
+ ```sh
184
+ uv run --group test pytest
185
+ ```
@@ -0,0 +1,168 @@
1
+ # msgspec-fastapi
2
+
3
+ An experimental 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 router
5
+ increased throughput by 68% on a route with a large JSON body and by 11% to 13% on
6
+ database-backed routes; see the Benchmarks section below.
7
+
8
+ This is a prototype. Its API may change, and it relies on private FastAPI internals, so
9
+ it is pinned to FastAPI 0.142.2 to 0.147.x. It is a personal project, not part of
10
+ msgspec; feedback is welcome in the issues.
11
+
12
+ ## Installation
13
+
14
+ ```sh
15
+ pip install msgspec-fastapi
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```python
21
+ import msgspec
22
+ from fastapi import FastAPI
23
+ from msgspec_fastapi import MsgspecRouter, install_openapi
24
+
25
+
26
+ class City(msgspec.Struct):
27
+ name: str
28
+ population: int
29
+
30
+
31
+ router = MsgspecRouter()
32
+
33
+
34
+ @router.post('/cities')
35
+ async def create_city(city: City) -> City:
36
+ return city
37
+
38
+
39
+ app = FastAPI()
40
+ app.include_router(router)
41
+ install_openapi(app, router)
42
+ ```
43
+
44
+ ## Benchmarks
45
+
46
+ The router was measured in a small reference-data service on a cloud VM with dedicated
47
+ vCPUs (October 2026). Each row compares the same service on FastAPI with Pydantic models
48
+ against the same service with msgspec Structs and `MsgspecRouter`. The database queries
49
+ (SQLAlchemy ORM), event loop and server settings are the same on both sides, and there
50
+ is no cache.
51
+
52
+ | Request | Requests per second | RPS change | CPU time per response | CPU change |
53
+ |---|---|---|---|---|
54
+ | `POST /cities/validate`, a JSON body of 100 cities (23 KB), no database | 1,610 → 2,703 | **+67.9%** [+67.0%, +68.7%] | 621 → 370 µs | **-40.4%** [-40.7%, -40.1%] |
55
+ | `GET /cities?limit=100`, a page of 100 cities read from PostgreSQL | 514 → 569 | **+10.7%** [+9.9%, +11.5%] | 1,944 → 1,757 µs | **-9.7%** [-10.3%, -9.0%] |
56
+ | `POST /cities/search`, small JSON filter bodies, a page of 100 cities | 447 → 505 | **+12.9%** [+12.1%, +13.7%] | 2,237 → 1,981 µs | **-11.4%** [-12.1%, -10.8%] |
57
+
58
+ The first route returns a constant 16-byte response (`{"accepted":100}`), so the
59
+ difference on this route comes mostly from request decoding and validation, and the gain
60
+ is largest there. On routes that read from a database, API CPU time per response falls by
61
+ about 190 to 260 µs out of roughly 2 ms, so the relative gain is smaller.
62
+
63
+ In the same service, setting `response_model=None` on the GET route made no detectable
64
+ difference in throughput with `MsgspecRouter` (0.0% [-1.0%, +1.0%]). This is consistent
65
+ with an instance of exactly the declared Struct class being encoded without
66
+ revalidation.
67
+
68
+ The benchmark sources, the data preparation scripts and the results of all 14
69
+ comparisons, including direct asyncpg queries without the ORM, uvloop, a Redis cache,
70
+ Litestar and Go, are in
71
+ [world-directory-bench](https://github.com/Siyet/world-directory-bench).
72
+
73
+ <details>
74
+ <summary>How it was measured</summary>
75
+
76
+ - Host: a cloud VM with 6 dedicated vCPUs (AMD EPYC-Rome, KVM), Ubuntu 24.04. The API
77
+ ran as one uvicorn worker (h11, asyncio) pinned to one core; PostgreSQL and the load
78
+ generator ran on other cores.
79
+ - Data and database: 224,578 cities, 55,246 division records, 501 country records and
80
+ 86,185 airports from GeoNames and OurAirports, about 231 MB in PostgreSQL 18.6
81
+ including indexes. The PostgreSQL data directory was on tmpfs (in memory). Database
82
+ access went through the SQLAlchemy ORM with the asyncpg driver.
83
+ - Software: CPython 3.14.7, FastAPI 0.142.2, Pydantic 2.13.5, msgspec 0.22.0,
84
+ SQLAlchemy 2.1.3 (ORM), asyncpg 0.31.0, uvicorn 0.54.0. The router code on the
85
+ measured paths was the same as msgspec-fastapi 0.0.1.
86
+ - Load: a Go generator with 20 closed-loop clients, checking every response body. The
87
+ numbers are throughput at saturation of the single API core. The GET mix sends 9 of
88
+ 10 requests to one page and every 10th to a page that is not repeated within the run.
89
+ - Each comparison is 8 blocks in ABBA or BAAB order, so each block measures both
90
+ versions twice; every run starts a fresh process with a 30 s warmup and a 60 s
91
+ measurement. The percentages are computed from the mean of the per-block log ratios,
92
+ with a nominal 95% t interval over the 8 blocks. The requests per second values are
93
+ the geometric means of each side, and the CPU values are the arithmetic means.
94
+ - CPU time per response is the CPU time of the API container in the measurement
95
+ window divided by the number of checked responses. Because the API core was
96
+ saturated, it is close to the inverse of throughput.
97
+
98
+ </details>
99
+
100
+ Things to keep in mind:
101
+
102
+ - On the control side, FastAPI parses the body with `json.loads` and then validates
103
+ it with Pydantic, which is FastAPI's standard path.
104
+ - The GET and search rows also include changes outside the router: database rows are
105
+ converted to msgspec Structs instead of Pydantic models and, for GET, the query model is
106
+ msgspec instead of Pydantic, so they measure a migration, not the router alone.
107
+ - Both sides check the same constraints, including custom per-record checks written
108
+ in Python. Results for other schemas and other routes will differ.
109
+ - This is one series on one machine. The host slowed down near the end of the series: a
110
+ static control was about 10% slower after the series than before it. The blocks of
111
+ all comparisons ran in 8 rounds, and the lasting slowdown began during the last
112
+ round. Leaving out any single round, the last one included, changes each estimate by
113
+ less than 0.32 percentage points. Compare the relative effects rather than the
114
+ absolute numbers.
115
+
116
+ ## What it does
117
+
118
+ - A msgspec body parameter (a Struct or another type msgspec can decode) is decoded from
119
+ the raw request bytes by a `msgspec.json.Decoder` built once at route registration. A
120
+ body with a non-JSON content type returns 415, malformed JSON or JSON nested too deeply
121
+ returns 400, and a missing or invalid body returns 422. The 415 and 400 responses are
122
+ sent before dependencies run; a 422 is sent after them, as in FastAPI, so a failing
123
+ dependency such as authentication takes precedence. Bodies are decoded in msgspec
124
+ strict mode: for example, the JSON string `"1"` is not accepted for an `int` field,
125
+ unlike FastAPI with Pydantic.
126
+ - A body without a content type follows FastAPI's `strict_content_type` setting: it is
127
+ rejected with 415 by default and parsed as JSON when the setting is `False`. FastAPI
128
+ returns 422 in the first case.
129
+ - A msgspec response type, from the return annotation or `response_model`, is encoded
130
+ with msgspec. An instance of exactly the declared Struct class is encoded without
131
+ revalidation, as FastAPI does for a Pydantic `response_model`; other values are
132
+ validated against the declared type. Nested values and type parameters of a trusted
133
+ instance are not checked. A NaN or infinite value in a `float` field is encoded as
134
+ `null` unless a constraint rejects it. In a `Decimal` field it is encoded as a string,
135
+ while FastAPI with Pydantic rejects non-finite `Decimal` values.
136
+ - Responses of routes without a return annotation or `response_model`, or with
137
+ `-> None`, are also encoded with msgspec, so the output can differ from FastAPI's
138
+ `jsonable_encoder` (for example, `bytes` are base64-encoded and `Decimal` is encoded as
139
+ a string).
140
+ - Path, query, header and cookie parameters keep FastAPI extraction, aliases and
141
+ defaults, but are converted with `msgspec.convert(strict=False)` instead of Pydantic,
142
+ so coercion differs for some inputs (for example, `" 1.5"` is rejected for `float`
143
+ and `"nan"` is accepted for `Decimal`). Parameter types must be supported by msgspec;
144
+ Pydantic-specific types such as `AnyUrl` raise `TypeError` at route registration.
145
+ - `install_openapi` adds the msgspec JSON schemas to the OpenAPI document. It is required
146
+ for a valid document: call it once after including the routers, passing every
147
+ `MsgspecRouter` that is not included directly in another `MsgspecRouter`.
148
+ - A Pydantic body or response model is left to FastAPI; the route parameters are still
149
+ validated with msgspec.
150
+
151
+ ## Limitations
152
+
153
+ - Only one msgspec body parameter per route, and it cannot be combined with other
154
+ FastAPI body fields. Only JSON bodies are supported: `application/json`,
155
+ `application/*+json`, or a request without a content type when `strict_content_type`
156
+ is `False`. `Form()` and `File()` parameters are left to FastAPI.
157
+ - When both the parameters and the body are invalid, only the parameter errors are
158
+ returned; FastAPI returns both.
159
+ - Structs, alone or inside containers, are not supported as path, query, header or
160
+ cookie parameters, or as `Form()` and `File()` parameters.
161
+ - `response_model_include`, `response_model_exclude`, `response_model_exclude_*` and
162
+ `response_model_by_alias=False` are rejected for typed msgspec responses.
163
+
164
+ ## Development
165
+
166
+ ```sh
167
+ uv run --group test pytest
168
+ ```
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "msgspec-fastapi"
7
- version = "0.0.1"
7
+ version = "0.0.3"
8
8
  description = "Experimental FastAPI router that decodes request bodies and encodes responses with msgspec"
9
9
  readme = "README.md"
10
10
  license = "BSD-3-Clause"
@@ -17,7 +17,7 @@ classifiers = [
17
17
  "Programming Language :: Python :: 3",
18
18
  ]
19
19
  dependencies = [
20
- "fastapi>=0.142.2,<0.144",
20
+ "fastapi>=0.142.2,<0.148",
21
21
  "msgspec>=0.22.0",
22
22
  ]
23
23
 
@@ -26,7 +26,7 @@ Source = "https://github.com/Siyet/msgspec-fastapi"
26
26
  Issues = "https://github.com/Siyet/msgspec-fastapi/issues"
27
27
 
28
28
  [dependency-groups]
29
- test = ["pytest", "httpx", "httpx2"]
29
+ test = ["pytest", "httpx", "httpx2", "python-multipart"]
30
30
 
31
31
  [tool.hatch.build.targets.wheel]
32
32
  packages = ["src/msgspec_fastapi"]
@@ -12,7 +12,7 @@ from fastapi import APIRouter, FastAPI, HTTPException, Request, Response
12
12
  from fastapi.datastructures import DefaultPlaceholder
13
13
  from fastapi.exceptions import RequestValidationError, ResponseValidationError
14
14
  from fastapi.openapi.utils import validation_error_definition, validation_error_response_definition
15
- from fastapi.params import Body, Depends, Param
15
+ from fastapi.params import Body, Depends, Form, Param
16
16
  from fastapi.routing import APIRoute, _effective_route_context_var, iter_route_contexts
17
17
  from starlette.concurrency import run_in_threadpool
18
18
 
@@ -85,16 +85,23 @@ def _hints(endpoint):
85
85
  return get_type_hints(target, include_extras=True)
86
86
 
87
87
 
88
- def _parse_body(request, raw, config):
88
+ def _parse_body(request, raw, config, strict_content_type):
89
89
  decoder, default, embedded = config
90
90
  if not raw:
91
91
  if default is inspect.Signature.empty:
92
- raise RequestValidationError([{'loc': ('body',), 'msg': 'Field required', 'type': 'missing'}])
92
+ # Raised after dependencies run, as in FastAPI.
93
+ return RequestValidationError([{'loc': ('body',), 'msg': 'Field required', 'type': 'missing'}])
93
94
  return deepcopy(default)
94
- media_type = request.headers.get('content-type', '').split(';')[0].strip().lower()
95
- if media_type and media_type != 'application/json' and not (
96
- media_type.startswith('application/') and media_type.endswith('+json')
97
- ):
95
+ content_type = request.headers.get('content-type')
96
+ if content_type:
97
+ media_type = content_type.split(';')[0].strip().lower()
98
+ if media_type != 'application/json' and not (
99
+ media_type.startswith('application/') and media_type.endswith('+json')
100
+ ):
101
+ raise HTTPException(415, 'Expected a JSON request body')
102
+ elif strict_content_type:
103
+ # Like FastAPI's strict_content_type: a body without a content type can be sent
104
+ # cross-origin without a CORS preflight, so it is not parsed as JSON.
98
105
  raise HTTPException(415, 'Expected a JSON request body')
99
106
  try:
100
107
  value = decoder.decode(raw)
@@ -104,12 +111,38 @@ def _parse_body(request, raw, config):
104
111
  msgspec.json.decode(raw)
105
112
  except (msgspec.DecodeError, UnicodeError) as syntax:
106
113
  raise HTTPException(400, f'Malformed JSON body: {syntax}') from syntax
107
- raise RequestValidationError([{'loc': ('body',), 'msg': str(exc), 'type': 'value_error.msgspec'}]) from exc
114
+ except RecursionError as nested:
115
+ raise HTTPException(400, 'JSON body is nested too deeply') from nested
116
+ return RequestValidationError([{'loc': ('body',), 'msg': str(exc), 'type': 'value_error.msgspec'}])
108
117
  except (msgspec.DecodeError, UnicodeError) as exc:
109
118
  raise HTTPException(400, f'Malformed JSON body: {exc}') from exc
119
+ except RecursionError as exc:
120
+ raise HTTPException(400, 'JSON body is nested too deeply') from exc
110
121
  return value.value if embedded else value
111
122
 
112
123
 
124
+ def _revalidate_without_json(result, output_type, error):
125
+ """Validate a value whose JSON round trip failed, as for NaN and infinity.
126
+
127
+ JSON encodes non-finite floats as null, and null is not valid for a float field.
128
+ FastAPI with Pydantic encodes them as null in a response, so validate the Python
129
+ values instead, with object keys converted to strings. A validation error from this
130
+ check is reported, because the one from the JSON round trip can point at a
131
+ non-finite float instead of the actual problem. Values that cannot be encoded as
132
+ JSON are not revalidated.
133
+ """
134
+ if isinstance(error, msgspec.ValidationError):
135
+ try:
136
+ return msgspec.convert(msgspec.to_builtins(result, str_keys=True), output_type, str_keys=True)
137
+ except msgspec.ValidationError as exc:
138
+ error = exc
139
+ except TypeError:
140
+ # to_builtins does not support every value JSON encodes, such as msgspec.Raw.
141
+ pass
142
+ raise ResponseValidationError(
143
+ [{'loc': ('response',), 'msg': str(error), 'type': 'value_error.msgspec'}]) from error
144
+
145
+
113
146
  class MsgspecRoute(APIRoute):
114
147
  def get_route_handler(self):
115
148
  context = _effective_route_context_var.get()
@@ -122,9 +155,14 @@ class MsgspecRoute(APIRoute):
122
155
  if route.body_field is not None:
123
156
  raise TypeError('Other FastAPI body fields cannot be combined with a msgspec body')
124
157
 
158
+ strict_content_type = route.strict_content_type
159
+ if isinstance(strict_content_type, DefaultPlaceholder):
160
+ strict_content_type = strict_content_type.value
161
+
125
162
  async def handle(request):
126
- # Invalid JSON must be rejected before dependency side effects.
127
- request.scope['_msgspec_body_value'] = _parse_body(request, await request.body(), config)
163
+ # A body that is not JSON is rejected before dependency side effects.
164
+ request.scope['_msgspec_body_value'] = _parse_body(
165
+ request, await request.body(), config, strict_content_type)
128
166
  return await handler(request)
129
167
  return handle
130
168
 
@@ -194,13 +232,17 @@ class MsgspecRouter(APIRouter):
194
232
  override = kwargs.get('route_class_override')
195
233
  if override is not None and not issubclass(override, MsgspecRoute):
196
234
  raise TypeError('route_class_override must extend MsgspecRoute')
197
- # Included routes already have a prepared signature and response metadata.
235
+ # Routes copied from another MsgspecRouter with add_api_route already have a
236
+ # prepared signature and response metadata.
198
237
  if getattr(endpoint, '_msgspec_prepared', False):
199
238
  return super().add_api_route(path, endpoint, **kwargs)
200
239
  signature = inspect.signature(endpoint)
201
240
  hints = _hints(endpoint)
202
241
  parameters = [p.replace(annotation=hints.get(p.name, p.annotation)) for p in signature.parameters.values()]
203
242
  return_type = hints.get('return', signature.return_annotation)
243
+ if return_type is type(None):
244
+ # As in FastAPI, `-> None` declares no response model.
245
+ return_type = None
204
246
  explicit = kwargs.get('response_model', inspect.Signature.empty)
205
247
  inferred = explicit is inspect.Signature.empty or isinstance(explicit, DefaultPlaceholder)
206
248
  output_type = return_type if inferred else explicit
@@ -241,6 +283,11 @@ class MsgspecRouter(APIRouter):
241
283
  metadata = _metadata(parameter, parameter.annotation)
242
284
  if any(isinstance(x, Depends) for x in metadata):
243
285
  continue
286
+ # Form and File parameters are left to FastAPI.
287
+ if any(isinstance(x, Form) for x in metadata):
288
+ if _contains_struct(parameter.annotation):
289
+ raise TypeError('msgspec Structs are not supported as Form or File parameters')
290
+ continue
244
291
  is_body = _contains_struct(parameter.annotation) or any(isinstance(x, Body) for x in metadata)
245
292
  if _body_type(parameter.annotation) and not any(isinstance(x, Param) for x in metadata):
246
293
  is_body = True
@@ -359,6 +406,8 @@ class MsgspecRouter(APIRouter):
359
406
  if remove_request:
360
407
  values.pop(request_name)
361
408
  value = request.scope['_msgspec_body_value']
409
+ if isinstance(value, RequestValidationError):
410
+ raise value
362
411
  values[body.name] = value
363
412
  if is_async:
364
413
  result = await endpoint(**values)
@@ -375,7 +424,7 @@ class MsgspecRouter(APIRouter):
375
424
  # Typed decoding validates fields and Meta, even for existing Structs.
376
425
  result = output_decoder.decode(output_encoder.encode(result))
377
426
  except (TypeError, ValueError, OverflowError) as exc:
378
- raise ResponseValidationError([{'loc': ('response',), 'msg': str(exc), 'type': 'value_error.msgspec'}]) from exc
427
+ result = _revalidate_without_json(result, output_type, exc)
379
428
  status_code = sub_response.status_code or kwargs.get('status_code') or 200
380
429
  if untyped_encoder is not None:
381
430
  response = Response(untyped_encoder.encode(result), status_code=status_code,
@@ -1,9 +1,10 @@
1
1
  """Tests for MsgspecRouter request decoding, parameter validation and response encoding."""
2
- from typing import Annotated, Generic, TypeVar
2
+ from typing import Annotated, Any, Generic, TypeVar
3
3
 
4
4
  import msgspec
5
5
  import pytest
6
- from fastapi import APIRouter, Depends, FastAPI, Query, Response
6
+ from fastapi import APIRouter, Depends, FastAPI, File, Form, Header, HTTPException, Query, Response
7
+ from fastapi.exceptions import ResponseValidationError
7
8
  from fastapi.responses import HTMLResponse, PlainTextResponse
8
9
  from fastapi.testclient import TestClient
9
10
  from pydantic import BaseModel, Field
@@ -319,3 +320,224 @@ def test_scalar_query_coercion_matches_fastapi(annotation, value):
319
320
  assert actual.status_code == expected.status_code
320
321
  if expected.status_code == 200:
321
322
  assert actual.json() == expected.json()
323
+
324
+
325
+ def strict_content_type_app(level, strict):
326
+ calls = []
327
+
328
+ def dependency():
329
+ calls.append(1)
330
+
331
+ async def endpoint(city: City):
332
+ return city
333
+
334
+ app = FastAPI(**({'strict_content_type': strict} if level == 'app' else {}))
335
+ router = MsgspecRouter(**({'strict_content_type': strict} if level == 'router' else {}))
336
+ router.add_api_route('/value', endpoint, methods=['POST'], dependencies=[Depends(dependency)],
337
+ **({'strict_content_type': strict} if level == 'route' else {}))
338
+ app.include_router(router)
339
+ return TestClient(app, raise_server_exceptions=False), calls
340
+
341
+
342
+ @pytest.mark.parametrize('level', ['app', 'router', 'route'])
343
+ @pytest.mark.parametrize('strict', [True, False])
344
+ def test_body_without_content_type_follows_strict_content_type(level, strict):
345
+ client, calls = strict_content_type_app(level, strict)
346
+ result = client.post('/value', content=b'{"population": 1}')
347
+ assert 'content-type' not in result.request.headers
348
+ if strict:
349
+ assert result.status_code == 415 and calls == []
350
+ else:
351
+ assert result.status_code == 200 and result.json() == {'population': 1}
352
+
353
+
354
+ def test_route_strict_content_type_overrides_app():
355
+ app = FastAPI(strict_content_type=False)
356
+ router = MsgspecRouter()
357
+
358
+ async def endpoint(city: City):
359
+ return city
360
+
361
+ router.add_api_route('/value', endpoint, methods=['POST'], strict_content_type=True)
362
+ app.include_router(router)
363
+ result = TestClient(app, raise_server_exceptions=False).post('/value', content=b'{"population": 1}')
364
+ assert result.status_code == 415
365
+
366
+
367
+ @pytest.mark.parametrize('content_type', ['', ';', 'text/plain', 'application/x-www-form-urlencoded'])
368
+ def test_body_with_non_json_content_type_is_rejected(content_type):
369
+ client, calls = strict_content_type_app('app', False)
370
+ result = client.post('/value', content=b'{"population": 1}', headers={'Content-Type': content_type})
371
+ expected = 200 if content_type == '' else 415
372
+ assert result.status_code == expected
373
+ assert calls == ([1] if expected == 200 else [])
374
+
375
+
376
+ @pytest.mark.parametrize('content_type', ['application/json; charset=utf-8', 'application/merge-patch+json'])
377
+ def test_body_with_json_content_type_is_accepted(content_type):
378
+ client, _ = strict_content_type_app('app', True)
379
+ result = client.post('/value', content=b'{"population": 1}', headers={'Content-Type': content_type})
380
+ assert result.status_code == 200 and result.json() == {'population': 1}
381
+
382
+
383
+ @pytest.mark.parametrize('annotation', [City, list[int], list[Any]])
384
+ def test_deeply_nested_json_body_is_rejected(annotation):
385
+ router = MsgspecRouter()
386
+
387
+ async def endpoint(value: annotation):
388
+ return {}
389
+
390
+ router.add_api_route('/value', endpoint, methods=['POST'])
391
+ app = FastAPI()
392
+ app.include_router(router)
393
+ depth = 200_000
394
+ result = TestClient(app, raise_server_exceptions=False).post(
395
+ '/value', content=b'[' * depth + b']' * depth, headers={'Content-Type': 'application/json'})
396
+ assert result.status_code == 400
397
+
398
+
399
+ class Reading(msgspec.Struct):
400
+ value: float
401
+
402
+
403
+ class LabeledReading(Reading):
404
+ label: str = ''
405
+
406
+
407
+ @pytest.mark.parametrize('annotation,value,expected', [
408
+ (float, float('nan'), None),
409
+ (float, float('inf'), None),
410
+ (dict[str, float], {'a': float('-inf')}, {'a': None}),
411
+ (Reading, LabeledReading(float('nan'), 'x'), {'value': None}),
412
+ (list[Reading], [Reading(float('nan'))], [{'value': None}]),
413
+ (dict[str, float], {1: float('nan')}, {'1': None}),
414
+ (dict[int, float], {'1': float('nan')}, {'1': None}),
415
+ ])
416
+ def test_non_finite_floats_in_typed_response_are_encoded_as_null(annotation, value, expected):
417
+ # FastAPI with Pydantic also encodes these as null instead of failing.
418
+ result = response(setup(value, model=annotation))
419
+ assert result.status_code == 200 and result.json() == expected
420
+
421
+
422
+ class Measurement(msgspec.Struct):
423
+ value: float
424
+ count: int
425
+
426
+
427
+ @pytest.mark.parametrize('annotation,value,message', [
428
+ (Annotated[float, msgspec.Meta(ge=0)], float('nan'), 'Expected `float` >= 0.0'),
429
+ (Annotated[float, msgspec.Meta(ge=0)], float('-inf'), 'Expected `float` >= 0.0'),
430
+ (Measurement, {'value': float('nan'), 'count': 'x'}, 'Expected `int`, got `str` - at `$.count`'),
431
+ (Reading, {'value': 'x'}, 'Expected `float`, got `str` - at `$.value`'),
432
+ (float, 'nan', 'Expected `float`, got `str`'),
433
+ (float, msgspec.Raw(b'"x"'), 'Expected `float`, got `str`'),
434
+ ])
435
+ def test_invalid_typed_response_is_still_rejected(annotation, value, message):
436
+ router = MsgspecRouter()
437
+
438
+ async def endpoint():
439
+ return value
440
+
441
+ router.add_api_route('/value', endpoint, methods=['GET'], response_model=annotation)
442
+ app = FastAPI()
443
+ app.include_router(router)
444
+ with pytest.raises(ResponseValidationError) as info:
445
+ TestClient(app).get('/value')
446
+ assert info.value.errors()[0]['msg'] == message
447
+
448
+
449
+ def auth_app():
450
+ calls = []
451
+
452
+ def authenticate(token: Annotated[str | None, Header()] = None):
453
+ calls.append(token)
454
+ if token != 'secret':
455
+ raise HTTPException(401, 'Not authenticated')
456
+
457
+ router = MsgspecRouter()
458
+
459
+ @router.post('/value', dependencies=[Depends(authenticate)])
460
+ async def endpoint(city: City):
461
+ return city
462
+
463
+ app = FastAPI()
464
+ app.include_router(router)
465
+ return TestClient(app, raise_server_exceptions=False), calls
466
+
467
+
468
+ @pytest.mark.parametrize('body', [{'population': -1}, {}, None])
469
+ def test_body_validation_errors_are_reported_after_dependencies(body):
470
+ # As in FastAPI, a failing dependency such as authentication takes precedence over
471
+ # a body that does not match the schema.
472
+ client, calls = auth_app()
473
+ options = {} if body is None else {'json': body}
474
+ assert client.post('/value', **options).status_code == 401
475
+ assert calls == [None]
476
+ result = client.post('/value', headers={'token': 'secret'}, **options)
477
+ assert result.status_code == 422
478
+ assert result.json()['detail'][0]['loc'] == ['body']
479
+
480
+
481
+ def test_malformed_body_is_still_rejected_before_dependencies():
482
+ client, calls = auth_app()
483
+ assert client.post('/value', content=b'{', headers={'Content-Type': 'application/json'}).status_code == 400
484
+ assert calls == []
485
+
486
+
487
+ @pytest.mark.parametrize('router_class', [APIRouter, MsgspecRouter])
488
+ def test_none_return_annotation_declares_no_response_model(router_class):
489
+ router = router_class()
490
+
491
+ @router.delete('/value', status_code=204)
492
+ async def delete() -> None:
493
+ pass
494
+
495
+ @router.get('/value')
496
+ async def get() -> None:
497
+ pass
498
+
499
+ app = FastAPI()
500
+ app.include_router(router)
501
+ client = TestClient(app)
502
+ deleted = client.delete('/value')
503
+ assert deleted.status_code == 204 and deleted.content == b''
504
+ assert client.get('/value').json() is None
505
+ responses = app.openapi()['paths']['/value']['get']['responses']
506
+ assert responses['200']['content']['application/json']['schema'] == {}
507
+
508
+
509
+ def test_form_and_file_parameters_are_left_to_fastapi():
510
+ router = MsgspecRouter()
511
+
512
+ @router.post('/value')
513
+ async def endpoint(name: Annotated[str, Form()], data: Annotated[bytes, File()]):
514
+ return {'name': name, 'size': len(data)}
515
+
516
+ app = FastAPI()
517
+ app.include_router(router)
518
+ result = TestClient(app).post('/value', data={'name': 'x'}, files={'data': b'abc'})
519
+ assert result.status_code == 200 and result.json() == {'name': 'x', 'size': 3}
520
+
521
+
522
+ def test_struct_form_parameter_is_rejected():
523
+ router = MsgspecRouter()
524
+
525
+ async def endpoint(city: Annotated[City, Form()]):
526
+ return city
527
+
528
+ with pytest.raises(TypeError, match='Form or File'):
529
+ router.add_api_route('/value', endpoint, methods=['POST'])
530
+
531
+
532
+ @pytest.mark.parametrize('annotation,value', [(str, '\ud800'), (Any, {None: 1})])
533
+ def test_unencodable_typed_response_raises_response_validation_error(annotation, value):
534
+ router = MsgspecRouter()
535
+
536
+ async def endpoint():
537
+ return value
538
+
539
+ router.add_api_route('/value', endpoint, methods=['GET'], response_model=annotation)
540
+ app = FastAPI()
541
+ app.include_router(router)
542
+ with pytest.raises(ResponseValidationError):
543
+ TestClient(app).get('/value')
@@ -1,98 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: msgspec-fastapi
3
- Version: 0.0.1
4
- Summary: Experimental FastAPI router that decodes request bodies and encodes responses with msgspec
5
- Project-URL: Source, https://github.com/Siyet/msgspec-fastapi
6
- Project-URL: Issues, https://github.com/Siyet/msgspec-fastapi/issues
7
- Author: Aleksandr Tseluiko
8
- License-Expression: BSD-3-Clause
9
- License-File: LICENSE
10
- Classifier: Development Status :: 2 - Pre-Alpha
11
- Classifier: Framework :: FastAPI
12
- Classifier: Programming Language :: Python :: 3
13
- Requires-Python: >=3.11
14
- Requires-Dist: fastapi<0.144,>=0.142.2
15
- Requires-Dist: msgspec>=0.22.0
16
- Description-Content-Type: text/markdown
17
-
18
- # msgspec-fastapi
19
-
20
- An experimental FastAPI router that uses msgspec for JSON request bodies and responses.
21
-
22
- This is a prototype. Its API may change, and it relies on private FastAPI internals, so
23
- it is pinned to FastAPI 0.142.2 to 0.143.x. It is a personal project, not part of
24
- msgspec; feedback is welcome in the issues.
25
-
26
- ## Installation
27
-
28
- ```sh
29
- pip install msgspec-fastapi
30
- ```
31
-
32
- ## Usage
33
-
34
- ```python
35
- import msgspec
36
- from fastapi import FastAPI
37
- from msgspec_fastapi import MsgspecRouter, install_openapi
38
-
39
-
40
- class City(msgspec.Struct):
41
- name: str
42
- population: int
43
-
44
-
45
- router = MsgspecRouter()
46
-
47
-
48
- @router.post('/cities')
49
- async def create_city(city: City) -> City:
50
- return city
51
-
52
-
53
- app = FastAPI()
54
- app.include_router(router)
55
- install_openapi(app, router)
56
- ```
57
-
58
- ## What it does
59
-
60
- - A msgspec body parameter (a Struct or another type msgspec can decode) is decoded from
61
- the raw request bytes by a `msgspec.json.Decoder` built once at route registration.
62
- A non-JSON content type returns 415, malformed JSON returns 400, and a missing or
63
- invalid body returns 422. Bodies are decoded in msgspec strict mode: for example, the
64
- JSON string `"1"` is not accepted for an `int` field, unlike FastAPI with Pydantic.
65
- - A msgspec response type, from the return annotation or `response_model`, is encoded
66
- with msgspec. An instance of exactly the declared Struct class is encoded without
67
- revalidation, as FastAPI does for a Pydantic `response_model`; other values are
68
- validated against the declared type. Nested values and type parameters of a trusted
69
- instance are not checked.
70
- - Responses of routes without a return annotation or `response_model` are also encoded
71
- with msgspec, so the output can differ from FastAPI's `jsonable_encoder` (for example,
72
- `bytes` are base64-encoded and `Decimal` is encoded as a string).
73
- - Path, query, header and cookie parameters keep FastAPI extraction, aliases and
74
- defaults, but are converted with `msgspec.convert(strict=False)` instead of Pydantic,
75
- so coercion differs for some inputs (for example, `" 1.5"` is rejected for `float`
76
- and `"nan"` is accepted for `Decimal`). Parameter types must be supported by msgspec;
77
- Pydantic-specific types such as `AnyUrl` raise `TypeError` at route registration.
78
- - `install_openapi` adds the msgspec JSON schemas to the OpenAPI document. It is required
79
- for a valid document: call it once after including the routers, passing every
80
- `MsgspecRouter` that is not included directly in another `MsgspecRouter`.
81
- - A Pydantic body or response model is left to FastAPI; the route parameters are still
82
- validated with msgspec.
83
-
84
- ## Limitations
85
-
86
- - Only one msgspec body parameter per route, and it cannot be combined with other
87
- FastAPI body fields. Only JSON bodies are supported: `application/json`,
88
- `application/*+json`, or a request without a content type.
89
- - Structs, alone or inside containers, are not supported as path, query, header or
90
- cookie parameters.
91
- - `response_model_include`, `response_model_exclude`, `response_model_exclude_*` and
92
- `response_model_by_alias=False` are rejected for typed msgspec responses.
93
-
94
- ## Development
95
-
96
- ```sh
97
- uv run --group test pytest
98
- ```
@@ -1,81 +0,0 @@
1
- # msgspec-fastapi
2
-
3
- An experimental FastAPI router that uses msgspec for JSON request bodies and responses.
4
-
5
- This is a prototype. Its API may change, and it relies on private FastAPI internals, so
6
- it is pinned to FastAPI 0.142.2 to 0.143.x. It is a personal project, not part of
7
- msgspec; feedback is welcome in the issues.
8
-
9
- ## Installation
10
-
11
- ```sh
12
- pip install msgspec-fastapi
13
- ```
14
-
15
- ## Usage
16
-
17
- ```python
18
- import msgspec
19
- from fastapi import FastAPI
20
- from msgspec_fastapi import MsgspecRouter, install_openapi
21
-
22
-
23
- class City(msgspec.Struct):
24
- name: str
25
- population: int
26
-
27
-
28
- router = MsgspecRouter()
29
-
30
-
31
- @router.post('/cities')
32
- async def create_city(city: City) -> City:
33
- return city
34
-
35
-
36
- app = FastAPI()
37
- app.include_router(router)
38
- install_openapi(app, router)
39
- ```
40
-
41
- ## What it does
42
-
43
- - A msgspec body parameter (a Struct or another type msgspec can decode) is decoded from
44
- the raw request bytes by a `msgspec.json.Decoder` built once at route registration.
45
- A non-JSON content type returns 415, malformed JSON returns 400, and a missing or
46
- invalid body returns 422. Bodies are decoded in msgspec strict mode: for example, the
47
- JSON string `"1"` is not accepted for an `int` field, unlike FastAPI with Pydantic.
48
- - A msgspec response type, from the return annotation or `response_model`, is encoded
49
- with msgspec. An instance of exactly the declared Struct class is encoded without
50
- revalidation, as FastAPI does for a Pydantic `response_model`; other values are
51
- validated against the declared type. Nested values and type parameters of a trusted
52
- instance are not checked.
53
- - Responses of routes without a return annotation or `response_model` are also encoded
54
- with msgspec, so the output can differ from FastAPI's `jsonable_encoder` (for example,
55
- `bytes` are base64-encoded and `Decimal` is encoded as a string).
56
- - Path, query, header and cookie parameters keep FastAPI extraction, aliases and
57
- defaults, but are converted with `msgspec.convert(strict=False)` instead of Pydantic,
58
- so coercion differs for some inputs (for example, `" 1.5"` is rejected for `float`
59
- and `"nan"` is accepted for `Decimal`). Parameter types must be supported by msgspec;
60
- Pydantic-specific types such as `AnyUrl` raise `TypeError` at route registration.
61
- - `install_openapi` adds the msgspec JSON schemas to the OpenAPI document. It is required
62
- for a valid document: call it once after including the routers, passing every
63
- `MsgspecRouter` that is not included directly in another `MsgspecRouter`.
64
- - A Pydantic body or response model is left to FastAPI; the route parameters are still
65
- validated with msgspec.
66
-
67
- ## Limitations
68
-
69
- - Only one msgspec body parameter per route, and it cannot be combined with other
70
- FastAPI body fields. Only JSON bodies are supported: `application/json`,
71
- `application/*+json`, or a request without a content type.
72
- - Structs, alone or inside containers, are not supported as path, query, header or
73
- cookie parameters.
74
- - `response_model_include`, `response_model_exclude`, `response_model_exclude_*` and
75
- `response_model_by_alias=False` are rejected for typed msgspec responses.
76
-
77
- ## Development
78
-
79
- ```sh
80
- uv run --group test pytest
81
- ```
File without changes