msgspec-fastapi 0.0.2__py3-none-any.whl → 0.0.4__py3-none-any.whl

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.
File without changes
@@ -1,10 +1,13 @@
1
1
  from typing import Any
2
+
2
3
  import msgspec
3
4
  from starlette.responses import JSONResponse
4
5
 
5
6
  _JSON_ENCODER = msgspec.json.Encoder()
6
7
 
8
+
7
9
  class MsgspecJSONResponse(JSONResponse):
8
10
  """Encode JSON with msgspec; use MsgspecRouter for output validation."""
11
+
9
12
  def render(self, content: Any) -> bytes:
10
13
  return _JSON_ENCODER.encode(content)
msgspec_fastapi/router.py CHANGED
@@ -1,39 +1,48 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import inspect
4
+ from collections.abc import Callable, Coroutine
4
5
  from copy import deepcopy
5
6
  from functools import partial, wraps
6
7
  from hashlib import sha256
7
- from typing import Annotated, get_args, get_origin, get_type_hints
8
+ from typing import Annotated, Any, cast, get_args, get_origin, get_type_hints
8
9
 
9
10
  import msgspec
10
- from pydantic import BaseModel
11
11
  from fastapi import APIRouter, FastAPI, HTTPException, Request, Response
12
+ from fastapi._compat import ModelField
12
13
  from fastapi.datastructures import DefaultPlaceholder
14
+ from fastapi.dependencies.models import Dependant
13
15
  from fastapi.exceptions import RequestValidationError, ResponseValidationError
14
16
  from fastapi.openapi.utils import validation_error_definition, validation_error_response_definition
15
17
  from fastapi.params import Body, Depends, Form, Param
16
18
  from fastapi.routing import APIRoute, _effective_route_context_var, iter_route_contexts
19
+ from pydantic import BaseModel
17
20
  from starlette.concurrency import run_in_threadpool
18
21
 
19
22
  from .responses import MsgspecJSONResponse
20
- from .validation import base_type, constrained_type, prepare_parameters, structured_type, uses_pydantic
23
+ from .validation import (
24
+ base_type,
25
+ constrained_type,
26
+ prepare_parameters,
27
+ structured_type,
28
+ uses_pydantic,
29
+ )
21
30
 
22
31
 
23
- def _untyped_encode_hook(value):
32
+ def _untyped_encode_hook(value: Any) -> Any:
24
33
  if isinstance(value, BaseModel):
25
34
  return value.model_dump(mode='json', by_alias=True)
26
35
  raise TypeError(f'Encoding objects of type {type(value).__name__} is unsupported')
27
36
 
28
37
 
29
- def _contains_struct(annotation):
38
+ def _contains_struct(annotation: Any) -> bool:
30
39
  value = base_type(annotation)
31
40
  return (isinstance(value, type) and issubclass(value, msgspec.Struct)) or any(
32
41
  _contains_struct(arg) for arg in get_args(value)
33
42
  )
34
43
 
35
44
 
36
- def _body_type(annotation):
45
+ def _body_type(annotation: Any) -> bool:
37
46
  value = base_type(annotation)
38
47
  if structured_type(value):
39
48
  return True
@@ -42,19 +51,19 @@ def _body_type(annotation):
42
51
  return any(_body_type(arg) for arg in get_args(value))
43
52
 
44
53
 
45
- def _metadata(parameter, annotation):
54
+ def _metadata(parameter: inspect.Parameter, annotation: Any) -> list[Any]:
46
55
  items = list(get_args(annotation)[1:]) if get_origin(annotation) is Annotated else []
47
56
  return [*items, parameter.default]
48
57
 
49
58
 
50
- def _merge_components(target, incoming):
59
+ def _merge_components(target: dict[str, Any], incoming: dict[str, Any]) -> None:
51
60
  for name, schema in incoming.items():
52
61
  if name in target and target[name] != schema:
53
62
  raise ValueError(f'Conflicting OpenAPI component: {name}')
54
63
  target[name] = deepcopy(schema)
55
64
 
56
65
 
57
- def _schema(annotation, components):
66
+ def _schema(annotation: Any, components: dict[str, Any]) -> dict[str, Any]:
58
67
  (schema,), definitions = msgspec.json.schema_components(
59
68
  [annotation], ref_template='#/components/schemas/{name}'
60
69
  )
@@ -62,7 +71,7 @@ def _schema(annotation, components):
62
71
  return schema
63
72
 
64
73
 
65
- def _json_type(annotation):
74
+ def _json_type(annotation: Any) -> bool:
66
75
  if annotation in (inspect.Signature.empty, None) or uses_pydantic(annotation):
67
76
  return False
68
77
  value = base_type(annotation)
@@ -76,8 +85,8 @@ def _json_type(annotation):
76
85
  return True
77
86
 
78
87
 
79
- def _hints(endpoint):
80
- target = endpoint
88
+ def _hints(endpoint: Callable[..., Any]) -> dict[str, Any]:
89
+ target: Any = endpoint
81
90
  while isinstance(target, partial):
82
91
  target = target.func
83
92
  if not inspect.isfunction(target) and not inspect.ismethod(target):
@@ -85,12 +94,19 @@ def _hints(endpoint):
85
94
  return get_type_hints(target, include_extras=True)
86
95
 
87
96
 
88
- def _parse_body(request, raw, config, strict_content_type):
97
+ def _parse_body(
98
+ request: Request,
99
+ raw: bytes,
100
+ config: tuple[msgspec.json.Decoder[Any], Any, bool],
101
+ strict_content_type: bool,
102
+ ) -> Any:
89
103
  decoder, default, embedded = config
90
104
  if not raw:
91
105
  if default is inspect.Signature.empty:
92
106
  # Raised after dependencies run, as in FastAPI.
93
- return RequestValidationError([{'loc': ('body',), 'msg': 'Field required', 'type': 'missing'}])
107
+ return RequestValidationError(
108
+ [{'loc': ('body',), 'msg': 'Field required', 'type': 'missing'}]
109
+ )
94
110
  return deepcopy(default)
95
111
  content_type = request.headers.get('content-type')
96
112
  if content_type:
@@ -113,7 +129,9 @@ def _parse_body(request, raw, config, strict_content_type):
113
129
  raise HTTPException(400, f'Malformed JSON body: {syntax}') from syntax
114
130
  except RecursionError as nested:
115
131
  raise HTTPException(400, 'JSON body is nested too deeply') from nested
116
- return RequestValidationError([{'loc': ('body',), 'msg': str(exc), 'type': 'value_error.msgspec'}])
132
+ return RequestValidationError(
133
+ [{'loc': ('body',), 'msg': str(exc), 'type': 'value_error.msgspec'}]
134
+ )
117
135
  except (msgspec.DecodeError, UnicodeError) as exc:
118
136
  raise HTTPException(400, f'Malformed JSON body: {exc}') from exc
119
137
  except RecursionError as exc:
@@ -121,7 +139,7 @@ def _parse_body(request, raw, config, strict_content_type):
121
139
  return value.value if embedded else value
122
140
 
123
141
 
124
- def _revalidate_without_json(result, output_type, error):
142
+ def _revalidate_without_json(result: Any, output_type: Any, error: Exception) -> Any:
125
143
  """Validate a value whose JSON round trip failed, as for NaN and infinity.
126
144
 
127
145
  JSON encodes non-finite floats as null, and null is not valid for a float field.
@@ -133,18 +151,21 @@ def _revalidate_without_json(result, output_type, error):
133
151
  """
134
152
  if isinstance(error, msgspec.ValidationError):
135
153
  try:
136
- return msgspec.convert(msgspec.to_builtins(result, str_keys=True), output_type, str_keys=True)
154
+ return msgspec.convert(
155
+ msgspec.to_builtins(result, str_keys=True), output_type, str_keys=True
156
+ )
137
157
  except msgspec.ValidationError as exc:
138
158
  error = exc
139
159
  except TypeError:
140
160
  # to_builtins does not support every value JSON encodes, such as msgspec.Raw.
141
161
  pass
142
162
  raise ResponseValidationError(
143
- [{'loc': ('response',), 'msg': str(error), 'type': 'value_error.msgspec'}]) from error
163
+ [{'loc': ('response',), 'msg': str(error), 'type': 'value_error.msgspec'}]
164
+ ) from error
144
165
 
145
166
 
146
167
  class MsgspecRoute(APIRoute):
147
- def get_route_handler(self):
168
+ def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:
148
169
  context = _effective_route_context_var.get()
149
170
  route = context if context is not None and context.original_route is self else self
150
171
  prepare_parameters(route.dependant)
@@ -159,11 +180,13 @@ class MsgspecRoute(APIRoute):
159
180
  if isinstance(strict_content_type, DefaultPlaceholder):
160
181
  strict_content_type = strict_content_type.value
161
182
 
162
- async def handle(request):
183
+ async def handle(request: Request) -> Response:
163
184
  # A body that is not JSON is rejected before dependency side effects.
164
185
  request.scope['_msgspec_body_value'] = _parse_body(
165
- request, await request.body(), config, strict_content_type)
186
+ request, await request.body(), config, strict_content_type
187
+ )
166
188
  return await handler(request)
189
+
167
190
  return handle
168
191
 
169
192
 
@@ -178,7 +201,7 @@ def install_openapi(app: FastAPI, *routers: 'MsgspecRouter') -> None:
178
201
  original = app.openapi
179
202
  app.openapi_schema = None
180
203
 
181
- def openapi():
204
+ def openapi() -> dict[str, Any]:
182
205
  document = original()
183
206
  components = document.setdefault('components', {}).setdefault('schemas', {})
184
207
  for router in routers:
@@ -187,48 +210,54 @@ def install_openapi(app: FastAPI, *routers: 'MsgspecRouter') -> None:
187
210
  original_route = getattr(route, 'original_route', route)
188
211
  if not isinstance(original_route, MsgspecRoute):
189
212
  continue
190
- fields = []
191
- def collect(dependant):
213
+ fields: list[ModelField] = []
214
+
215
+ def collect(dependant: Dependant) -> None:
192
216
  for group in ('path_params', 'query_params', 'header_params', 'cookie_params'):
193
217
  fields.extend(getattr(dependant, group))
194
218
  for dependency in dependant.dependencies:
195
219
  collect(dependency)
220
+
196
221
  collect(route.dependant)
197
- for method in route.methods:
198
- operation = document.get('paths', {}).get(route.path_format, {}).get(method.lower(), {})
222
+ for method in route.methods or ():
223
+ operation = (
224
+ document.get('paths', {}).get(route.path_format, {}).get(method.lower(), {})
225
+ )
199
226
  for parameter in operation.get('parameters', []):
200
227
  for field in fields:
201
- if (getattr(field, '_msgspec_parameter', False)
202
- and parameter['in'] == field.field_info.in_.value
203
- and parameter['name'] == field.alias):
204
- schema = deepcopy(field._msgspec_schema)
228
+ if (
229
+ getattr(field, '_msgspec_parameter', False)
230
+ and parameter['in'] == cast(Param, field.field_info).in_.value
231
+ and parameter['name'] == field.alias
232
+ ):
233
+ schema = deepcopy(getattr(field, '_msgspec_schema'))
205
234
  for key in ('title', 'description', 'default'):
206
235
  if key in parameter.get('schema', {}):
207
236
  schema[key] = parameter['schema'][key]
208
237
  parameter['schema'] = schema
209
238
  return document
210
239
 
211
- app.openapi = openapi
212
- app._msgspec_openapi_installed = True
240
+ setattr(app, 'openapi', openapi)
241
+ setattr(app, '_msgspec_openapi_installed', True)
213
242
 
214
243
 
215
244
  class MsgspecRouter(APIRouter):
216
245
  """Typed msgspec JSON bodies and validated responses for ordinary CRUD routes."""
217
246
 
218
- def __init__(self, *args, **kwargs):
247
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
219
248
  kwargs.setdefault('route_class', MsgspecRoute)
220
249
  kwargs.setdefault('default_response_class', MsgspecJSONResponse)
221
250
  if not issubclass(kwargs['route_class'], MsgspecRoute):
222
251
  raise TypeError('route_class must extend MsgspecRoute')
223
252
  super().__init__(*args, **kwargs)
224
- self.msgspec_components = {}
253
+ self.msgspec_components: dict[str, Any] = {}
225
254
 
226
- def include_router(self, router, *args, **kwargs):
255
+ def include_router(self, router: APIRouter, *args: Any, **kwargs: Any) -> None:
227
256
  if isinstance(router, MsgspecRouter):
228
257
  _merge_components(self.msgspec_components, router.msgspec_components)
229
258
  return super().include_router(router, *args, **kwargs)
230
259
 
231
- def add_api_route(self, path, endpoint, **kwargs):
260
+ def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) -> None:
232
261
  override = kwargs.get('route_class_override')
233
262
  if override is not None and not issubclass(override, MsgspecRoute):
234
263
  raise TypeError('route_class_override must extend MsgspecRoute')
@@ -238,7 +267,10 @@ class MsgspecRouter(APIRouter):
238
267
  return super().add_api_route(path, endpoint, **kwargs)
239
268
  signature = inspect.signature(endpoint)
240
269
  hints = _hints(endpoint)
241
- parameters = [p.replace(annotation=hints.get(p.name, p.annotation)) for p in signature.parameters.values()]
270
+ parameters = [
271
+ p.replace(annotation=hints.get(p.name, p.annotation))
272
+ for p in signature.parameters.values()
273
+ ]
242
274
  return_type = hints.get('return', signature.return_annotation)
243
275
  if return_type is type(None):
244
276
  # As in FastAPI, `-> None` declares no response model.
@@ -257,8 +289,14 @@ class MsgspecRouter(APIRouter):
257
289
  # including subclass instances, are validated against the schema. Unlike Pydantic,
258
290
  # values nested in a trusted instance are encoded as they are (a nested subclass keeps
259
291
  # its extra fields, and the type parameters of a generic Struct are not checked).
260
- output_class = (get_origin(base_type(output_type)) or base_type(output_type)) if validates_output else None
261
- trusts_instances = isinstance(output_class, type) and issubclass(output_class, msgspec.Struct)
292
+ output_class = (
293
+ (get_origin(base_type(output_type)) or base_type(output_type))
294
+ if validates_output
295
+ else None
296
+ )
297
+ trusts_instances = isinstance(output_class, type) and issubclass(
298
+ output_class, msgspec.Struct
299
+ )
262
300
  output_encoder = msgspec.json.Encoder() if validates_output else None
263
301
  response_class = kwargs.get('response_class')
264
302
  if response_class is None or isinstance(response_class, DefaultPlaceholder):
@@ -270,12 +308,15 @@ class MsgspecRouter(APIRouter):
270
308
  and not uses_pydantic(return_type)
271
309
  and response_class is MsgspecJSONResponse
272
310
  )
273
- handles_output = validates_output or serializes_untyped_output or (
274
- explicit is None and _contains_struct(return_type)
311
+ handles_output = (
312
+ validates_output
313
+ or serializes_untyped_output
314
+ or (explicit is None and _contains_struct(return_type))
275
315
  )
276
316
  untyped_encoder = (
277
317
  msgspec.json.Encoder(enc_hook=_untyped_encode_hook)
278
- if serializes_untyped_output else None
318
+ if serializes_untyped_output
319
+ else None
279
320
  )
280
321
  body = None
281
322
  body_meta = None
@@ -288,14 +329,20 @@ class MsgspecRouter(APIRouter):
288
329
  if _contains_struct(parameter.annotation):
289
330
  raise TypeError('msgspec Structs are not supported as Form or File parameters')
290
331
  continue
291
- is_body = _contains_struct(parameter.annotation) or any(isinstance(x, Body) for x in metadata)
332
+ is_body = _contains_struct(parameter.annotation) or any(
333
+ isinstance(x, Body) for x in metadata
334
+ )
292
335
  if _body_type(parameter.annotation) and not any(isinstance(x, Param) for x in metadata):
293
336
  is_body = True
294
337
  if is_body and _json_type(parameter.annotation):
295
338
  if any(isinstance(x, Param) for x in metadata):
296
- raise TypeError('msgspec Struct query/path/header/cookie parameters are not supported')
339
+ raise TypeError(
340
+ 'msgspec Struct query/path/header/cookie parameters are not supported'
341
+ )
297
342
  if body is not None:
298
- raise TypeError('Only one msgspec body parameter is supported; other body fields cannot be combined')
343
+ raise TypeError(
344
+ 'Only one msgspec body parameter is supported; other body fields cannot be combined'
345
+ )
299
346
  body = parameter
300
347
  body_meta = next((x for x in metadata if isinstance(x, Body)), None)
301
348
 
@@ -305,9 +352,13 @@ class MsgspecRouter(APIRouter):
305
352
  raise TypeError('Variadic msgspec endpoints are not supported')
306
353
  if handles_output:
307
354
  if validates_output:
308
- for option in ('response_model_include', 'response_model_exclude',
309
- 'response_model_exclude_unset', 'response_model_exclude_defaults',
310
- 'response_model_exclude_none'):
355
+ for option in (
356
+ 'response_model_include',
357
+ 'response_model_exclude',
358
+ 'response_model_exclude_unset',
359
+ 'response_model_exclude_defaults',
360
+ 'response_model_exclude_none',
361
+ ):
311
362
  if kwargs.get(option):
312
363
  raise TypeError(f'{option} is not supported for msgspec responses')
313
364
  if kwargs.get('response_model_by_alias', True) is False:
@@ -315,19 +366,29 @@ class MsgspecRouter(APIRouter):
315
366
  if validates_output and kwargs.get('status_code') in (204, 304):
316
367
  raise TypeError('A typed msgspec response requires a response body')
317
368
  response_class = kwargs.get('response_class')
318
- if response_class is not None and not isinstance(response_class, DefaultPlaceholder) and response_class is not MsgspecJSONResponse:
319
- raise TypeError('Custom response_class is not supported for typed msgspec responses')
369
+ if (
370
+ response_class is not None
371
+ and not isinstance(response_class, DefaultPlaceholder)
372
+ and response_class is not MsgspecJSONResponse
373
+ ):
374
+ raise TypeError(
375
+ 'Custom response_class is not supported for typed msgspec responses'
376
+ )
320
377
  kwargs['response_model'] = None
321
378
  kwargs['response_class'] = MsgspecJSONResponse
322
379
 
323
- components = {}
380
+ components: dict[str, Any] = {}
324
381
  responses = deepcopy(kwargs.get('responses') or {})
325
382
  openapi_extra = deepcopy(kwargs.get('openapi_extra') or {})
326
383
  default = inspect.Signature.empty
327
384
  decoder = None
328
385
  embedded = False
329
386
  if body is not None:
330
- metadata = [x for x in get_args(body.annotation)[1:] if not isinstance(x, Body)] if get_origin(body.annotation) is Annotated else []
387
+ metadata = (
388
+ [x for x in get_args(body.annotation)[1:] if not isinstance(x, Body)]
389
+ if get_origin(body.annotation) is Annotated
390
+ else []
391
+ )
331
392
  body_type, body_strict = constrained_type(base_type(body.annotation), metadata)
332
393
  if body_strict is False:
333
394
  raise TypeError('JSON msgspec bodies use strict validation')
@@ -340,9 +401,13 @@ class MsgspecRouter(APIRouter):
340
401
  embedded = body_meta.embed is True
341
402
  default = body_meta.default
342
403
  from pydantic_core import PydanticUndefined
404
+
343
405
  if default is PydanticUndefined or default is Ellipsis:
344
406
  default = inspect.Signature.empty
345
- if not isinstance(body.default, Body) and body.default is not inspect.Signature.empty:
407
+ if (
408
+ not isinstance(body.default, Body)
409
+ and body.default is not inspect.Signature.empty
410
+ ):
346
411
  default = body.default
347
412
  if body_meta.default_factory is not None:
348
413
  raise TypeError('Body default_factory is not supported')
@@ -350,39 +415,71 @@ class MsgspecRouter(APIRouter):
350
415
  default = body.default
351
416
  decode_type = body_type
352
417
  if embedded:
418
+ assert body_meta is not None
353
419
  # One explicit JSON envelope, preserving a possible Body alias.
354
- field = ('value', body_type) if default is inspect.Signature.empty else (
355
- 'value', body_type, msgspec.field(default_factory=lambda: deepcopy(default))
420
+ field = (
421
+ ('value', body_type)
422
+ if default is inspect.Signature.empty
423
+ else (
424
+ 'value',
425
+ body_type,
426
+ msgspec.field(default_factory=lambda: deepcopy(default)),
427
+ )
356
428
  )
357
- identity = {'schema': msgspec.json.schema(body_type), 'alias': body_meta.alias or body.name,
358
- 'required': default is inspect.Signature.empty}
429
+ identity = {
430
+ 'schema': msgspec.json.schema(body_type),
431
+ 'alias': body_meta.alias or body.name,
432
+ 'required': default is inspect.Signature.empty,
433
+ }
359
434
  if default is not inspect.Signature.empty:
360
435
  identity['default'] = default
361
436
  name = 'MsgspecBody_' + sha256(msgspec.json.encode(identity)).hexdigest()[:16]
362
- decode_type = msgspec.defstruct(name, [field],
363
- rename={'value': body_meta.alias or body.name})
437
+ decode_type = msgspec.defstruct(
438
+ name, [field], rename={'value': body_meta.alias or body.name}
439
+ )
364
440
  decoder = msgspec.json.Decoder(type=decode_type)
365
441
  body_schema = _schema(decode_type, components)
366
- openapi_extra['requestBody'] = {'required': default is inspect.Signature.empty,
367
- 'content': {'application/json': {'schema': body_schema}}}
442
+ openapi_extra['requestBody'] = {
443
+ 'required': default is inspect.Signature.empty,
444
+ 'content': {'application/json': {'schema': body_schema}},
445
+ }
368
446
  responses.setdefault(400, {'description': 'Malformed JSON'})
369
- responses.setdefault(422, {'description': 'Validation Error', 'content': {
370
- 'application/json': {'schema': {'$ref': '#/components/schemas/HTTPValidationError'}}}})
371
- _merge_components(components, {'HTTPValidationError': validation_error_response_definition,
372
- 'ValidationError': validation_error_definition})
447
+ responses.setdefault(
448
+ 422,
449
+ {
450
+ 'description': 'Validation Error',
451
+ 'content': {
452
+ 'application/json': {
453
+ 'schema': {'$ref': '#/components/schemas/HTTPValidationError'}
454
+ }
455
+ },
456
+ },
457
+ )
458
+ _merge_components(
459
+ components,
460
+ {
461
+ 'HTTPValidationError': validation_error_response_definition,
462
+ 'ValidationError': validation_error_definition,
463
+ },
464
+ )
373
465
  if validates_output:
374
466
  code = kwargs.get('status_code') or 200
375
467
  key = str(code) if str(code) in responses else code
376
468
  result_meta = responses.setdefault(key, {})
377
- result_meta.setdefault('description', kwargs.get('response_description', 'Successful Response'))
378
- result_meta.setdefault('content', {})['application/json'] = {'schema': _schema(output_type, components)}
469
+ result_meta.setdefault(
470
+ 'description', kwargs.get('response_description', 'Successful Response')
471
+ )
472
+ result_meta.setdefault('content', {})['application/json'] = {
473
+ 'schema': _schema(output_type, components)
474
+ }
379
475
  previous_components = deepcopy(self.msgspec_components)
380
476
  _merge_components(self.msgspec_components, components)
381
477
  kwargs['responses'] = responses
382
478
  kwargs['openapi_extra'] = openapi_extra
383
479
 
384
480
  remaining = [p for p in parameters if p is not body]
385
- def injected_name(type_, fallback):
481
+
482
+ def injected_name(type_: type[Request] | type[Response], fallback: str) -> tuple[str, bool]:
386
483
  for p in remaining:
387
484
  annotation = base_type(p.annotation)
388
485
  if isinstance(annotation, type) and issubclass(annotation, type_):
@@ -390,21 +487,31 @@ class MsgspecRouter(APIRouter):
390
487
  names = {p.name for p in parameters}
391
488
  while fallback in names:
392
489
  fallback += '_'
393
- remaining.append(inspect.Parameter(fallback, kind=inspect.Parameter.KEYWORD_ONLY, annotation=type_))
490
+ remaining.append(
491
+ inspect.Parameter(fallback, kind=inspect.Parameter.KEYWORD_ONLY, annotation=type_)
492
+ )
394
493
  return fallback, True
395
- request_name, remove_request = injected_name(Request, '__msgspec_request') if body else (None, False)
396
- response_name, remove_response = injected_name(Response, '__msgspec_response') if handles_output else (None, False)
397
494
 
398
- is_async = inspect.iscoroutinefunction(endpoint) or inspect.iscoroutinefunction(getattr(endpoint, '__call__', None))
495
+ request_name, remove_request = (
496
+ injected_name(Request, '__msgspec_request') if body else (None, False)
497
+ )
498
+ response_name, remove_response = (
499
+ injected_name(Response, '__msgspec_response') if handles_output else (None, False)
500
+ )
501
+
502
+ is_async = inspect.iscoroutinefunction(endpoint) or inspect.iscoroutinefunction(
503
+ getattr(endpoint, '__call__', None)
504
+ )
505
+
399
506
  @wraps(endpoint)
400
- async def wrapper(**values):
401
- sub_response = values.get(response_name)
507
+ async def wrapper(**values: Any) -> Any:
508
+ sub_response = cast(Response, values.get(cast(str, response_name)))
402
509
  if remove_response:
403
- values.pop(response_name)
510
+ values.pop(cast(str, response_name))
404
511
  if body is not None:
405
- request = values[request_name]
512
+ request = values[cast(str, request_name)]
406
513
  if remove_request:
407
- values.pop(request_name)
514
+ values.pop(cast(str, request_name))
408
515
  value = request.scope['_msgspec_body_value']
409
516
  if isinstance(value, RequestValidationError):
410
517
  raise value
@@ -422,13 +529,18 @@ class MsgspecRouter(APIRouter):
422
529
  if validates_output and not (trusts_instances and type(result) is output_class):
423
530
  try:
424
531
  # Typed decoding validates fields and Meta, even for existing Structs.
425
- result = output_decoder.decode(output_encoder.encode(result))
532
+ result = cast(msgspec.json.Decoder[Any], output_decoder).decode(
533
+ cast(msgspec.json.Encoder, output_encoder).encode(result)
534
+ )
426
535
  except (TypeError, ValueError, OverflowError) as exc:
427
536
  result = _revalidate_without_json(result, output_type, exc)
428
537
  status_code = sub_response.status_code or kwargs.get('status_code') or 200
429
538
  if untyped_encoder is not None:
430
- response = Response(untyped_encoder.encode(result), status_code=status_code,
431
- media_type='application/json')
539
+ response = Response(
540
+ untyped_encoder.encode(result),
541
+ status_code=status_code,
542
+ media_type='application/json',
543
+ )
432
544
  else:
433
545
  response = MsgspecJSONResponse(result, status_code=status_code)
434
546
  if response.status_code < 200 or response.status_code in (204, 205, 304):
@@ -438,18 +550,24 @@ class MsgspecRouter(APIRouter):
438
550
  response.raw_headers.extend(sub_response.raw_headers)
439
551
  return response
440
552
 
441
- wrapper.__signature__ = signature.replace(parameters=remaining, return_annotation=inspect.Signature.empty if handles_output else return_type)
442
- wrapper._msgspec_prepared = True
553
+ setattr(
554
+ wrapper,
555
+ '__signature__',
556
+ signature.replace(
557
+ parameters=remaining,
558
+ return_annotation=inspect.Signature.empty if handles_output else return_type,
559
+ ),
560
+ )
561
+ setattr(wrapper, '_msgspec_prepared', True)
443
562
  if body is not None:
444
- wrapper._msgspec_body_config = (decoder, default, embedded)
563
+ setattr(wrapper, '_msgspec_body_config', (decoder, default, embedded))
445
564
  route_count = len(self.routes)
446
565
  try:
447
566
  result = super().add_api_route(path, wrapper, **kwargs)
448
- if body is not None and self.routes[-1].body_field is not None:
567
+ if body is not None and cast(APIRoute, self.routes[-1]).body_field is not None:
449
568
  raise TypeError('Other FastAPI body fields cannot be combined with a msgspec body')
450
569
  return result
451
570
  except Exception:
452
571
  del self.routes[route_count:]
453
572
  self.msgspec_components = previous_components
454
573
  raise
455
-
@@ -1,37 +1,43 @@
1
1
  """Route-local validation for HTTP parameters; no global FastAPI changes."""
2
- import re
3
2
 
4
- from typing import Annotated, Any, Literal, Union, get_args, get_origin, get_type_hints
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Callable, Iterable
5
7
  from dataclasses import is_dataclass
6
- from typing_extensions import is_typeddict
7
8
  from types import UnionType
9
+ from typing import Annotated, Any, Literal, Union, cast, get_args, get_origin, get_type_hints
8
10
 
9
11
  import annotated_types
10
12
  import msgspec
13
+ from fastapi.dependencies.models import Dependant
11
14
  from pydantic import BaseModel
12
15
  from pydantic.fields import FieldInfo
16
+ from typing_extensions import is_typeddict
13
17
 
14
18
 
15
- def base_type(annotation):
19
+ def base_type(annotation: Any) -> Any:
16
20
  return get_args(annotation)[0] if get_origin(annotation) is Annotated else annotation
17
21
 
18
22
 
19
- def structured_type(annotation):
23
+ def structured_type(annotation: Any) -> bool:
20
24
  value = get_origin(base_type(annotation)) or base_type(annotation)
21
25
  return isinstance(value, type) and (
22
- issubclass(value, msgspec.Struct) or is_typeddict(value) or is_dataclass(value)
26
+ issubclass(value, msgspec.Struct)
27
+ or is_typeddict(value)
28
+ or is_dataclass(value)
23
29
  or (issubclass(value, tuple) and hasattr(value, '_fields'))
24
30
  )
25
31
 
26
32
 
27
- def uses_pydantic(annotation):
33
+ def uses_pydantic(annotation: Any) -> bool:
28
34
  value = base_type(annotation)
29
35
  return (isinstance(value, type) and issubclass(value, BaseModel)) or any(
30
36
  uses_pydantic(item) for item in get_args(value)
31
37
  )
32
38
 
33
39
 
34
- def _check_structured_metadata(annotation, seen=None):
40
+ def _check_structured_metadata(annotation: Any, seen: set[Any] | None = None) -> None:
35
41
  if seen is None:
36
42
  seen = set()
37
43
  if get_origin(annotation) is Annotated:
@@ -49,7 +55,7 @@ def _check_structured_metadata(annotation, seen=None):
49
55
  _check_structured_metadata(arg, seen)
50
56
 
51
57
 
52
- def constrained_type(annotation, metadata=()):
58
+ def constrained_type(annotation: Any, metadata: Iterable[Any] = ()) -> tuple[Any, bool | None]:
53
59
  """Translate supported FastAPI constraints, rejecting unhandled validation."""
54
60
  if get_origin(annotation) is Annotated:
55
61
  annotation, *extras = get_args(annotation)
@@ -58,22 +64,24 @@ def constrained_type(annotation, metadata=()):
58
64
  if structured_type(annotation):
59
65
  _check_structured_metadata(annotation)
60
66
  if args and origin is not Literal:
61
- converted = []
67
+ converted: list[Any] = []
62
68
  for arg in args:
63
69
  if arg is Ellipsis:
64
70
  converted.append(arg)
65
71
  continue
66
72
  target, nested_strict = constrained_type(arg)
67
73
  if nested_strict is not None:
68
- raise TypeError('Nested strict constraints are not supported; use a strict top-level parameter')
74
+ raise TypeError(
75
+ 'Nested strict constraints are not supported; use a strict top-level parameter'
76
+ )
69
77
  converted.append(target)
70
- converted = tuple(converted)
78
+ converted_args = tuple(converted)
71
79
  if hasattr(annotation, 'copy_with'):
72
- annotation = annotation.copy_with(converted)
80
+ annotation = annotation.copy_with(converted_args)
73
81
  elif origin in (Union, UnionType):
74
- annotation = Union[converted]
82
+ annotation = Union[converted_args]
75
83
  else:
76
- annotation = origin[converted[0] if len(converted) == 1 else converted]
84
+ annotation = origin[converted_args[0] if len(converted_args) == 1 else converted_args]
77
85
  expanded = []
78
86
  for item in metadata:
79
87
  if isinstance(item, FieldInfo):
@@ -81,21 +89,35 @@ def constrained_type(annotation, metadata=()):
81
89
  else:
82
90
  expanded.append(item)
83
91
  metadata = expanded
84
- constraints = {}
92
+ constraints: dict[str, Any] = {}
85
93
  metas = []
86
94
  strict = None
87
95
  for item in metadata:
88
96
  if isinstance(item, msgspec.Meta):
89
97
  metas.append(item)
90
- elif isinstance(item, (annotated_types.Gt, annotated_types.Ge, annotated_types.Lt,
91
- annotated_types.Le, annotated_types.MultipleOf,
92
- annotated_types.MinLen, annotated_types.MaxLen)):
93
- name = {'MinLen': 'min_length', 'MaxLen': 'max_length'}.get(type(item).__name__,
94
- {'MultipleOf': 'multiple_of'}.get(type(item).__name__, type(item).__name__.lower()))
98
+ elif isinstance(
99
+ item,
100
+ (
101
+ annotated_types.Gt,
102
+ annotated_types.Ge,
103
+ annotated_types.Lt,
104
+ annotated_types.Le,
105
+ annotated_types.MultipleOf,
106
+ annotated_types.MinLen,
107
+ annotated_types.MaxLen,
108
+ ),
109
+ ):
110
+ name = {'MinLen': 'min_length', 'MaxLen': 'max_length'}.get(
111
+ type(item).__name__,
112
+ {'MultipleOf': 'multiple_of'}.get(type(item).__name__, type(item).__name__.lower()),
113
+ )
95
114
  constraints[name] = getattr(item, name)
96
115
  elif type(item).__module__.startswith('pydantic') and type(item).__name__ == 'Strict':
97
116
  strict = item.strict
98
- elif type(item).__module__.startswith('pydantic') and type(item).__name__ == '_PydanticGeneralMetadata':
117
+ elif (
118
+ type(item).__module__.startswith('pydantic')
119
+ and type(item).__name__ == '_PydanticGeneralMetadata'
120
+ ):
99
121
  for name, value in vars(item).items():
100
122
  if name not in ('pattern',):
101
123
  raise TypeError(f'Unsupported msgspec parameter constraint: {name}')
@@ -117,13 +139,12 @@ def constrained_type(annotation, metadata=()):
117
139
  return target, strict
118
140
 
119
141
 
120
-
121
142
  # Unicode White_Space used by Rust str::trim, excluding Python's extra C0 separators.
122
143
  _HTTP_WHITESPACE = '\t\n\v\f\r \x85\xa0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000'
123
144
  _HTTP_INTEGER = re.compile(r'-?(?:0|[1-9][0-9]*)\Z')
124
145
 
125
146
 
126
- def _http_int(value):
147
+ def _http_int(value: Any) -> Any:
127
148
  """Match pydantic-core 2.46.5 str_as_int/clean_int_str on HTTP strings."""
128
149
  if not isinstance(value, str):
129
150
  return value
@@ -151,7 +172,7 @@ def _http_int(value):
151
172
  number = number[offset:]
152
173
  break
153
174
  if char == '.':
154
- number = number[offset - 1:]
175
+ number = number[offset - 1 :]
155
176
  break
156
177
  raise ValueError('Invalid integer parameter')
157
178
  else:
@@ -160,8 +181,12 @@ def _http_int(value):
160
181
  whole, decimal = number.split('.', 1)
161
182
  if decimal and all(char == '0' for char in decimal):
162
183
  number = whole
163
- if ('_' in number and not number.startswith('_') and not number.endswith('_')
164
- and '__' not in number):
184
+ if (
185
+ '_' in number
186
+ and not number.startswith('_')
187
+ and not number.endswith('_')
188
+ and '__' not in number
189
+ ):
165
190
  number = number.replace('_', '')
166
191
  if negative:
167
192
  number = '-' + number
@@ -169,7 +194,8 @@ def _http_int(value):
169
194
  raise ValueError('Invalid integer parameter')
170
195
  return int(number)
171
196
 
172
- def _http_normalizer(annotation):
197
+
198
+ def _http_normalizer(annotation: Any) -> Callable[[Any], Any] | None:
173
199
  """Compile supported transport coercions once at route registration."""
174
200
  annotation = base_type(annotation)
175
201
  origin, args = get_origin(annotation), get_args(annotation)
@@ -180,20 +206,33 @@ def _http_normalizer(annotation):
180
206
  children = tuple(_http_normalizer(arg) for arg in args)
181
207
  if not any(children):
182
208
  return None
183
- def normalize_tuple(value):
184
- return [children[i](item) if i < len(children) and children[i] else item
185
- for i, item in enumerate(value)] if isinstance(value, (list, tuple)) else value
209
+
210
+ def normalize_tuple(value: Any) -> Any:
211
+ return (
212
+ [
213
+ cast(Callable[[Any], Any], children[i])(item)
214
+ if i < len(children) and children[i]
215
+ else item
216
+ for i, item in enumerate(value)
217
+ ]
218
+ if isinstance(value, (list, tuple))
219
+ else value
220
+ )
221
+
186
222
  return normalize_tuple
187
223
  child = _http_normalizer(args[0]) if args else None
188
224
  if child is None:
189
225
  return None
190
- def normalize_sequence(value):
226
+
227
+ def normalize_sequence(value: Any) -> Any:
191
228
  return [child(item) for item in value] if isinstance(value, (list, tuple)) else value
229
+
192
230
  return normalize_sequence
193
231
  if annotation is int:
194
232
  return _http_int
195
233
  if annotation is bool:
196
- def normalize_bool(value):
234
+
235
+ def normalize_bool(value: Any) -> Any:
197
236
  if isinstance(value, str):
198
237
  lowered = value.lower()
199
238
  if lowered in ('yes', 'on', 'y', 't'):
@@ -201,26 +240,33 @@ def _http_normalizer(annotation):
201
240
  if lowered in ('no', 'off', 'n', 'f'):
202
241
  return False
203
242
  return value
243
+
204
244
  return normalize_bool
205
245
  if annotation is bytes:
206
246
  return lambda value: value.encode('utf-8') if isinstance(value, str) else value
207
247
  return None
208
248
 
209
249
 
210
- def _parameter_validator(target, strict):
250
+ def _parameter_validator(
251
+ target: Any, strict: bool
252
+ ) -> Callable[..., tuple[Any, list[dict[str, Any]]]]:
211
253
  normalizer = None if strict else _http_normalizer(target)
212
254
  convert = msgspec.convert
213
- def validate(value: Any, values=None, *, loc=()):
255
+
256
+ def validate(
257
+ value: Any, values: dict[str, Any] | None = None, *, loc: tuple[str | int, ...] = ()
258
+ ) -> tuple[Any, list[dict[str, Any]]]:
214
259
  try:
215
260
  if normalizer is not None:
216
261
  value = normalizer(value)
217
262
  return convert(value, type=target, strict=strict), []
218
263
  except (ValueError, UnicodeError, OverflowError) as exc:
219
264
  return None, [{'loc': loc, 'msg': str(exc), 'type': 'value_error.msgspec'}]
265
+
220
266
  return validate
221
267
 
222
268
 
223
- def prepare_parameters(dependant):
269
+ def prepare_parameters(dependant: Dependant) -> None:
224
270
  """Keep FastAPI extraction/aliases/defaults; replace supported validators."""
225
271
  for group in ('path_params', 'query_params', 'header_params', 'cookie_params'):
226
272
  for field in getattr(dependant, group):
@@ -228,7 +274,9 @@ def prepare_parameters(dependant):
228
274
  continue
229
275
  if getattr(field, '_msgspec_parameter', False):
230
276
  continue
231
- target, strict = constrained_type(field.field_info.annotation, field.field_info.metadata)
277
+ target, strict = constrained_type(
278
+ field.field_info.annotation, field.field_info.metadata
279
+ )
232
280
  strict = bool(strict)
233
281
  schema = msgspec.json.schema(target)
234
282
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: msgspec-fastapi
3
- Version: 0.0.2
3
+ Version: 0.0.4
4
4
  Summary: Experimental FastAPI router that decodes request bodies and encodes responses with msgspec
5
5
  Project-URL: Source, https://github.com/Siyet/msgspec-fastapi
6
6
  Project-URL: Issues, https://github.com/Siyet/msgspec-fastapi/issues
@@ -11,7 +11,7 @@ Classifier: Development Status :: 2 - Pre-Alpha
11
11
  Classifier: Framework :: FastAPI
12
12
  Classifier: Programming Language :: Python :: 3
13
13
  Requires-Python: >=3.11
14
- Requires-Dist: fastapi<0.144,>=0.142.2
14
+ Requires-Dist: fastapi<0.148,>=0.142.2
15
15
  Requires-Dist: msgspec>=0.22.0
16
16
  Description-Content-Type: text/markdown
17
17
 
@@ -23,7 +23,7 @@ increased throughput by 68% on a route with a large JSON body and by 11% to 13%
23
23
  database-backed routes; see the Benchmarks section below.
24
24
 
25
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.143.x. It is a personal project, not part of
26
+ it is pinned to FastAPI 0.142.2 to 0.147.x. It is a personal project, not part of
27
27
  msgspec; feedback is welcome in the issues.
28
28
 
29
29
  ## Installation
@@ -181,5 +181,14 @@ Things to keep in mind:
181
181
  ## Development
182
182
 
183
183
  ```sh
184
+ uv sync --group test --group lint
184
185
  uv run --group test pytest
186
+ uv run --group lint ruff check .
187
+ uv run --group lint ruff format --check .
188
+ uv run --group lint pre-commit install
189
+ uv run --group lint pre-commit run --all-files
185
190
  ```
191
+
192
+ Ruff checks imports, annotations and common Python errors, and formats the code.
193
+ CI runs the same Ruff version as the pre-commit hooks. Test endpoints that exercise the absence
194
+ of a response annotation intentionally omit it.
@@ -0,0 +1,9 @@
1
+ msgspec_fastapi/__init__.py,sha256=qza4iZ78zIdyMQjhSyfu3kExhINEBjVp30ctKDIj6nw,165
2
+ msgspec_fastapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ msgspec_fastapi/responses.py,sha256=cO-XhTVfN2CNBk1raxsbx_ELVbP7mbR5XjWrXqk7Yfg,335
4
+ msgspec_fastapi/router.py,sha256=4fAsXdvM-_2-Lu0LoBqY6hHuU5O5t41pbSrMH0DMqhg,26239
5
+ msgspec_fastapi/validation.py,sha256=_NH0UhiUZ5hpFd14BE-2f65xsiOVgsMtAyLyOdHbTT0,11116
6
+ msgspec_fastapi-0.0.4.dist-info/METADATA,sha256=ZVIvmOllxk4CSG3wuEQU3yOsuGqmyADOxYvr3N6AWXA,9912
7
+ msgspec_fastapi-0.0.4.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
8
+ msgspec_fastapi-0.0.4.dist-info/licenses/LICENSE,sha256=-tcdcjgHx0RS0YgoKnr_WJOaYz5gCXajKEnmMHRvwkc,1526
9
+ msgspec_fastapi-0.0.4.dist-info/RECORD,,
@@ -1,8 +0,0 @@
1
- msgspec_fastapi/__init__.py,sha256=qza4iZ78zIdyMQjhSyfu3kExhINEBjVp30ctKDIj6nw,165
2
- msgspec_fastapi/responses.py,sha256=Ocx51DUVWUU1zCqegwIO-NVqyFJK8Gf-SL4k1GABiEw,332
3
- msgspec_fastapi/router.py,sha256=6LGvnzW-eei5Gky7ugAsoywl8TfWz_VQ8rQRMBOEWxI,23599
4
- msgspec_fastapi/validation.py,sha256=zomhWlcqZzUWTnq7mNp6sVCPU2lh0kMsK2f5eazmAko,10049
5
- msgspec_fastapi-0.0.2.dist-info/METADATA,sha256=YF6oazQ0WVLtKxzosQqnJ1CXW-G46lREjqZcitUXz_E,9491
6
- msgspec_fastapi-0.0.2.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
7
- msgspec_fastapi-0.0.2.dist-info/licenses/LICENSE,sha256=-tcdcjgHx0RS0YgoKnr_WJOaYz5gCXajKEnmMHRvwkc,1526
8
- msgspec_fastapi-0.0.2.dist-info/RECORD,,