diff --git a/README.md b/README.md index 5d3f6ad..53a60fc 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ async def create_city(city: City) -> City: app = FastAPI() app.include_router(router) -install_openapi(app, router) +install_openapi(app) ``` ## Benchmarks @@ -142,9 +142,13 @@ Things to keep in mind: so coercion differs for some inputs (for example, `" 1.5"` is rejected for `float` and `"nan"` is accepted for `Decimal`). Parameter types must be supported by msgspec; Pydantic-specific types such as `AnyUrl` raise `TypeError` at route registration. -- `install_openapi` adds the msgspec JSON schemas to the OpenAPI document. It is required - for a valid document: call it once after including the routers, passing every - `MsgspecRouter` that is not included directly in another `MsgspecRouter`. +- `install_openapi(app)` adds the msgspec JSON schemas to the OpenAPI document. Call it + once before serving. Routes, webhooks and callbacks are discovered from the application + when the document is built; the optional router arguments remain accepted for + compatibility. Hidden routes do not add msgspec components. As in FastAPI, the document + is cached: set `app.openapi_schema = None` to rebuild it after adding routes. +- Body descriptions and examples, `openapi_extra` request metadata and response examples + are preserved. JSON body routes document their 400, 415 and 422 responses. - A Pydantic body or response model is left to FastAPI; the route parameters are still validated with msgspec. diff --git a/src/msgspec_fastapi/router.py b/src/msgspec_fastapi/router.py index 4fb2439..5fb936b 100644 --- a/src/msgspec_fastapi/router.py +++ b/src/msgspec_fastapi/router.py @@ -4,20 +4,21 @@ from collections.abc import Callable, Coroutine from copy import deepcopy from functools import partial, wraps -from hashlib import sha256 from typing import Annotated, Any, cast, get_args, get_origin, get_type_hints import msgspec from fastapi import APIRouter, FastAPI, HTTPException, Request, Response from fastapi._compat import ModelField -from fastapi.datastructures import DefaultPlaceholder +from fastapi.datastructures import DefaultPlaceholder, _Unset from fastapi.dependencies.models import Dependant from fastapi.exceptions import RequestValidationError, ResponseValidationError from fastapi.openapi.utils import validation_error_definition, validation_error_response_definition from fastapi.params import Body, Depends, Form, Param from fastapi.routing import APIRoute, _effective_route_context_var, iter_route_contexts +from fastapi.utils import deep_dict_update from pydantic import BaseModel from starlette.concurrency import run_in_threadpool +from starlette.routing import compile_path from .responses import MsgspecJSONResponse from .validation import ( @@ -58,19 +59,13 @@ def _metadata(parameter: inspect.Parameter, annotation: Any) -> list[Any]: def _merge_components(target: dict[str, Any], incoming: dict[str, Any]) -> None: for name, schema in incoming.items(): - if name in target and target[name] != schema: - raise ValueError(f'Conflicting OpenAPI component: {name}') + if name in target: + if target[name] != schema: + raise ValueError(f'Conflicting OpenAPI component: {name}') + continue target[name] = deepcopy(schema) -def _schema(annotation: Any, components: dict[str, Any]) -> dict[str, Any]: - (schema,), definitions = msgspec.json.schema_components( - [annotation], ref_template='#/components/schemas/{name}' - ) - _merge_components(components, definitions) - return schema - - def _json_type(annotation: Any) -> bool: if annotation in (inspect.Signature.empty, None) or uses_pydantic(annotation): return False @@ -168,6 +163,9 @@ class MsgspecRoute(APIRoute): def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: context = _effective_route_context_var.get() route = context if context is not None and context.original_route is self else self + body_parameter = getattr(self.endpoint, '_msgspec_body_parameter', None) + if body_parameter in compile_path(route.path)[2]: + raise AssertionError('Path parameters must be scalar values') prepare_parameters(route.dependant) handler = super().get_route_handler() config = getattr(self.endpoint, '_msgspec_body_config', None) @@ -190,39 +188,114 @@ async def handle(request: Request) -> Response: return handle +def _rename_schema_refs(schema: dict[str, Any], names: dict[str, str]) -> None: + if '$ref' in schema: + schema['$ref'] = names.get(schema['$ref'], schema['$ref']) + mapping = schema.get('discriminator', {}).get('mapping', {}) + for key, ref in mapping.items(): + mapping[key] = names.get(ref, ref) + # Visit schema positions only; defaults, examples and property names are data. + for key in ('properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'): + for child in schema.get(key, {}).values(): + if isinstance(child, dict): + _rename_schema_refs(child, names) + for key in ( + 'items', + 'additionalProperties', + 'unevaluatedProperties', + 'propertyNames', + 'contains', + 'not', + 'if', + 'then', + 'else', + 'unevaluatedItems', + 'contentSchema', + ): + child = schema.get(key) + if isinstance(child, dict): + _rename_schema_refs(child, names) + for key in ('anyOf', 'oneOf', 'allOf', 'prefixItems'): + for child in schema.get(key, []): + if isinstance(child, dict): + _rename_schema_refs(child, names) + + def install_openapi(app: FastAPI, *routers: 'MsgspecRouter') -> None: - """Install once after including routers, before serving the application.""" - if not routers: - raise TypeError('Pass the MsgspecRouter instances included in the app') + """Install once before serving; router arguments are kept for compatibility.""" if getattr(app, '_msgspec_openapi_installed', False): raise RuntimeError('msgspec OpenAPI is already installed') # FastAPI builds included contexts lazily; validate them before serving. list(iter_route_contexts(app.routes)) + list(iter_route_contexts(app.webhooks.routes)) original = app.openapi app.openapi_schema = None def openapi() -> dict[str, Any]: + if app.openapi_schema is not None: + return app.openapi_schema document = original() + # Do not retain a partially patched document if schema generation fails. + app.openapi_schema = None components = document.setdefault('components', {}).setdefault('schemas', {}) - for router in routers: - _merge_components(components, router.msgspec_components) - for route in iter_route_contexts(app.routes): - original_route = getattr(route, 'original_route', route) - if not isinstance(original_route, MsgspecRoute): - continue - fields: list[ModelField] = [] - - def collect(dependant: Dependant) -> None: - for group in ('path_params', 'query_params', 'header_params', 'cookie_params'): - fields.extend(getattr(dependant, group)) - for dependency in dependant.dependencies: - collect(dependency) - - collect(route.dependant) - for method in route.methods or (): - operation = ( - document.get('paths', {}).get(route.path_format, {}).get(method.lower(), {}) + targets: list[tuple[Any, dict[str, Any]]] = [] + body_extras: dict[int, tuple[Callable[..., Any], dict[str, Any]]] = {} + + def collect_fields(dependant: Dependant) -> list[ModelField]: + fields = [] + for group in ('path_params', 'query_params', 'header_params', 'cookie_params'): + fields.extend(getattr(dependant, group)) + for dependency in dependant.dependencies: + fields.extend(collect_fields(dependency)) + return fields + + def collect(routes: Any, paths: dict[str, Any]) -> None: + operations = {} + for route in iter_route_contexts(routes): + if isinstance(route.original_route, APIRoute) and route.include_in_schema: + path = route.path_format + if path is None: + continue + for method in route.methods or (): + operations[path, method.lower()] = route + for (path, method), route in operations.items(): + operation = paths.get(path, {}).get(method) + if operation is None: + continue + body_type, output_type, output_code = getattr( + route.endpoint, '_msgspec_openapi', (None, None, None) ) + if body_type is not None: + body_schema = operation['requestBody']['content']['application/json']['schema'] + alias = getattr(route.endpoint, '_msgspec_body_alias', None) + if alias is not None: + body_schema = body_schema['properties'][alias] + extra = getattr(route.endpoint, '_msgspec_body_schema_extra', None) + if extra is not None: + body_extras[id(body_schema)] = extra + targets.append( + ( + body_type, + body_schema, + ) + ) + _merge_components( + components, + { + 'HTTPValidationError': validation_error_response_definition, + 'ValidationError': validation_error_definition, + }, + ) + if output_type is not None: + targets.append( + ( + output_type, + operation['responses'][str(output_code)]['content']['application/json'][ + 'schema' + ], + ) + ) + fields = collect_fields(route.dependant) for parameter in operation.get('parameters', []): for field in fields: if ( @@ -230,11 +303,60 @@ def collect(dependant: Dependant) -> None: and parameter['in'] == cast(Param, field.field_info).in_.value and parameter['name'] == field.alias ): - schema = deepcopy(getattr(field, '_msgspec_schema')) - for key in ('title', 'description', 'default'): - if key in parameter.get('schema', {}): - schema[key] = parameter['schema'][key] + # Replace the Pydantic schema, preserving field metadata. + previous = parameter.get('schema', {}) + schema = { + key: previous[key] + for key in ('title', 'description', 'default') + if key in previous + } parameter['schema'] = schema + targets.append((getattr(field, '_msgspec_type'), schema)) + callbacks = { + callback.name: callback + for callback in route.callbacks or () + if isinstance(callback, APIRoute) + } + for callback in callbacks.values(): + callback_paths = operation.get('callbacks', {}).get(callback.name, {}) + collect([callback], callback_paths) + + collect(app.routes, document.get('paths', {})) + collect(app.webhooks.routes, document.get('webhooks', {})) + if targets: + schemas, definitions = msgspec.json.schema_components( + [annotation for annotation, _ in targets], + ref_template='#/components/schemas/{name}', + ) + # Pydantic and msgspec can use the same short name for different schemas. + reserved = set(components) | set(definitions) + names = {} + for name in definitions: + if name in components: + candidate = name + '_Msgspec' + while candidate in reserved: + candidate += '_' + reserved.add(candidate) + names['#/components/schemas/' + name] = '#/components/schemas/' + candidate + for schema in (*schemas, *definitions.values()): + _rename_schema_refs(schema, names) + definitions = { + names.get('#/components/schemas/' + name, '#/components/schemas/' + name).rsplit( + '/', 1 + )[-1]: schema + for name, schema in definitions.items() + } + _merge_components(components, definitions) + for (_, target), schema in zip(targets, schemas): + schema = deepcopy(schema) + if extra := body_extras.get(id(target)): + callback, metadata = extra + schema.update(metadata) + callback(schema) + deep_dict_update(schema, target) + target.clear() + target.update(schema) + app.openapi_schema = document return document setattr(app, 'openapi', openapi) @@ -250,12 +372,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: if not issubclass(kwargs['route_class'], MsgspecRoute): raise TypeError('route_class must extend MsgspecRoute') super().__init__(*args, **kwargs) - self.msgspec_components: dict[str, Any] = {} - - def include_router(self, router: APIRouter, *args: Any, **kwargs: Any) -> None: - if isinstance(router, MsgspecRouter): - _merge_components(self.msgspec_components, router.msgspec_components) - return super().include_router(router, *args, **kwargs) def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) -> None: override = kwargs.get('route_class_override') @@ -318,6 +434,7 @@ def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) if serializes_untyped_output else None ) + path_parameters = compile_path(path)[2] body = None body_meta = None for parameter in parameters: @@ -335,6 +452,8 @@ def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) if _body_type(parameter.annotation) and not any(isinstance(x, Param) for x in metadata): is_body = True if is_body and _json_type(parameter.annotation): + if parameter.name in path_parameters: + raise AssertionError('Path parameters must be scalar values') if any(isinstance(x, Param) for x in metadata): raise TypeError( 'msgspec Struct query/path/header/cookie parameters are not supported' @@ -377,12 +496,13 @@ def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) kwargs['response_model'] = None kwargs['response_class'] = MsgspecJSONResponse - components: dict[str, Any] = {} responses = deepcopy(kwargs.get('responses') or {}) openapi_extra = deepcopy(kwargs.get('openapi_extra') or {}) default = inspect.Signature.empty decoder = None embedded = False + body_alias = None + schema_body_type = None if body is not None: metadata = ( [x for x in get_args(body.annotation)[1:] if not isinstance(x, Body)] @@ -413,9 +533,24 @@ def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) raise TypeError('Body default_factory is not supported') else: default = body.default + field_schema: dict[str, Any] = {} + if embedded and default is not inspect.Signature.empty: + field_schema['default'] = msgspec.to_builtins(default, str_keys=True) + if body_meta is not None: + for key in ('title', 'description', 'examples', 'deprecated'): + value = getattr(body_meta, key) + if value is not None: + field_schema[key] = value + if isinstance(body_meta.json_schema_extra, dict): + field_schema.update(body_meta.json_schema_extra) + elif body_meta.json_schema_extra is not None and not callable( + body_meta.json_schema_extra + ): + raise TypeError('Body json_schema_extra must be a dict or callable') decode_type = body_type if embedded: assert body_meta is not None + body_alias = body_meta.alias or body.name # One explicit JSON envelope, preserving a possible Body alias. field = ( ('value', body_type) @@ -426,24 +561,35 @@ def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) msgspec.field(default_factory=lambda: deepcopy(default)), ) ) - identity = { - 'schema': msgspec.json.schema(body_type), - 'alias': body_meta.alias or body.name, - 'required': default is inspect.Signature.empty, - } - if default is not inspect.Signature.empty: - identity['default'] = default - name = 'MsgspecBody_' + sha256(msgspec.json.encode(identity)).hexdigest()[:16] decode_type = msgspec.defstruct( - name, [field], rename={'value': body_meta.alias or body.name} + 'MsgspecBody', [field], rename={'value': body_alias} ) decoder = msgspec.json.Decoder(type=decode_type) - body_schema = _schema(decode_type, components) - openapi_extra['requestBody'] = { + schema_callback = body_meta.json_schema_extra if body_meta is not None else None + schema_body_type = body_type + body_schema = {} if callable(schema_callback) else field_schema + request_schema = body_schema + if body_alias is not None: + request_schema = { + 'type': 'object', + 'properties': {body_alias: body_schema}, + } + if default is inspect.Signature.empty: + request_schema['required'] = [body_alias] + media: dict[str, Any] = {'schema': request_schema} + if body_meta is not None and not embedded: + if body_meta.openapi_examples: + media['examples'] = body_meta.openapi_examples + elif body_meta.example is not _Unset: + media['example'] = body_meta.example + request_body = { 'required': default is inspect.Signature.empty, - 'content': {'application/json': {'schema': body_schema}}, + 'content': {'application/json': media}, } + deep_dict_update(request_body, openapi_extra.get('requestBody', {})) + openapi_extra['requestBody'] = request_body responses.setdefault(400, {'description': 'Malformed JSON'}) + responses.setdefault(415, {'description': 'Unsupported Media Type'}) responses.setdefault( 422, { @@ -455,25 +601,16 @@ def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) }, }, ) - _merge_components( - components, - { - 'HTTPValidationError': validation_error_response_definition, - 'ValidationError': validation_error_definition, - }, - ) if validates_output: code = kwargs.get('status_code') or 200 - key = str(code) if str(code) in responses else code - result_meta = responses.setdefault(key, {}) + response_key = str(code) if str(code) in responses else code + result_meta = responses.setdefault(response_key, {}) result_meta.setdefault( 'description', kwargs.get('response_description', 'Successful Response') ) - result_meta.setdefault('content', {})['application/json'] = { - 'schema': _schema(output_type, components) - } - previous_components = deepcopy(self.msgspec_components) - _merge_components(self.msgspec_components, components) + result_meta.setdefault('content', {}).setdefault('application/json', {}).setdefault( + 'schema', {} + ) kwargs['responses'] = responses kwargs['openapi_extra'] = openapi_extra @@ -559,8 +696,24 @@ async def wrapper(**values: Any) -> Any: ), ) setattr(wrapper, '_msgspec_prepared', True) + setattr( + wrapper, + '_msgspec_openapi', + ( + schema_body_type, + output_type if validates_output else None, + kwargs.get('status_code') or 200, + ), + ) if body is not None: setattr(wrapper, '_msgspec_body_config', (decoder, default, embedded)) + setattr(wrapper, '_msgspec_body_parameter', body.name) + if body_alias is not None: + setattr(wrapper, '_msgspec_body_alias', body_alias) + if callable(schema_callback): + setattr( + wrapper, '_msgspec_body_schema_extra', (schema_callback, deepcopy(field_schema)) + ) route_count = len(self.routes) try: result = super().add_api_route(path, wrapper, **kwargs) @@ -569,5 +722,4 @@ async def wrapper(**values: Any) -> Any: return result except Exception: del self.routes[route_count:] - self.msgspec_components = previous_components raise diff --git a/src/msgspec_fastapi/validation.py b/src/msgspec_fastapi/validation.py index 4304c87..afb53f2 100644 --- a/src/msgspec_fastapi/validation.py +++ b/src/msgspec_fastapi/validation.py @@ -278,10 +278,10 @@ def prepare_parameters(dependant: Dependant) -> None: field.field_info.annotation, field.field_info.metadata ) strict = bool(strict) - schema = msgspec.json.schema(target) + msgspec.json.schema(target) field.validate = _parameter_validator(target, strict) field._msgspec_parameter = True - field._msgspec_schema = schema + field._msgspec_type = target for dependency in dependant.dependencies: prepare_parameters(dependency) diff --git a/tests/test_openapi.py b/tests/test_openapi.py new file mode 100644 index 0000000..08695b2 --- /dev/null +++ b/tests/test_openapi.py @@ -0,0 +1,660 @@ +"""OpenAPI coverage with ordinary FastAPI routes as compatibility controls.""" + +from enum import Enum +from typing import Annotated, Any + +import msgspec +import pytest +from fastapi import APIRouter, Body, Depends, FastAPI, Header +from fastapi.testclient import TestClient +from pydantic import BaseModel, create_model + +from msgspec_fastapi import MsgspecRouter, install_openapi +from msgspec_fastapi.router import MsgspecRoute + + +class Choice(str, Enum): + first = 'first' + second = 'second' + + +class Item(msgspec.Struct): + choice: Choice + + +class PydItem(BaseModel): + choice: Choice + + +def assert_local_refs_resolve(document: dict[str, Any]) -> None: + def resolve(ref: str) -> None: + assert ref.startswith('#/'), ref + value = document + for part in ref[2:].split('/'): + part = part.replace('~1', '/').replace('~0', '~') + assert part in value, ref + value = value[part] + + def walk(value: Any) -> None: + if isinstance(value, dict): + for key, child in value.items(): + if key in ('examples', 'example', 'default', 'const', 'enum'): + continue + if key == '$ref' and isinstance(child, str): + resolve(child) + else: + walk(child) + for ref in value.get('discriminator', {}).get('mapping', {}).values(): + resolve(ref) + elif isinstance(value, list): + for child in value: + walk(child) + + walk(document) + + +def dereference(document: dict[str, Any], schema: dict[str, Any]) -> dict[str, Any]: + if '$ref' not in schema: + return schema + return document['components']['schemas'][schema['$ref'].rsplit('/', 1)[-1]] + + +@pytest.mark.parametrize('router_class,model', [(MsgspecRouter, Item), (APIRouter, PydItem)]) +@pytest.mark.parametrize('with_body', [False, True]) +def test_enum_parameter_and_model_references( + router_class: type[APIRouter], model: Any, with_body: bool +) -> None: + router = router_class() + + async def endpoint(choice: Choice) -> Any: + return {'choice': choice} + + router.add_api_route( + '/items', endpoint, methods=['GET'], response_model=model if with_body else None + ) + app = FastAPI() + app.include_router(router) + if router_class is MsgspecRouter: + install_openapi(app) + response = TestClient(app).get('/openapi.json') + assert response.status_code == 200 + document = response.json() + assert_local_refs_resolve(document) + parameter = document['paths']['/items']['get']['parameters'][0]['schema'] + assert dereference(document, parameter)['enum'] == ['first', 'second'] + assert TestClient(app).get('/items?choice=first').json() == {'choice': 'first'} + assert TestClient(app).get('/items?choice=other').status_code == 422 + + +@pytest.mark.parametrize('pydantic', [False, True]) +def test_same_named_models_from_different_modules(pydantic: bool) -> None: + router = APIRouter() if pydantic else MsgspecRouter() + for module, field in [('module_a', 'number'), ('module_b', 'count')]: + model = ( + create_model('Entry', __module__=module, **{field: (int, ...)}) + if pydantic + else msgspec.defstruct('Entry', [(field, int)], module=module) + ) + + async def endpoint() -> Any: + return {} + + router.add_api_route('/' + module, endpoint, response_model=model) + app = FastAPI() + app.include_router(router) + if not pydantic: + install_openapi(app) + document = app.openapi() + assert_local_refs_resolve(document) + for module, field in [('module_a', 'number'), ('module_b', 'count')]: + schema = document['paths']['/' + module]['get']['responses']['200']['content'][ + 'application/json' + ]['schema'] + assert set(dereference(document, schema)['properties']) == {field} + + +def test_pydantic_and_msgspec_components_with_same_name() -> None: + pyd_model = create_model('Item', count=(int, ...)) + ordinary = APIRouter() + + @ordinary.get('/pydantic', response_model=pyd_model) + async def pydantic_endpoint() -> Any: + return {'count': 1} + + router = MsgspecRouter() + + @router.post('/msgspec') + async def msgspec_endpoint(item: Item) -> Item: + return item + + app = FastAPI() + app.include_router(ordinary) + app.include_router(router) + install_openapi(app) + document = app.openapi() + assert_local_refs_resolve(document) + for path, method, field in [('/pydantic', 'get', 'count'), ('/msgspec', 'post', 'choice')]: + schema = document['paths'][path][method]['responses']['200']['content']['application/json'][ + 'schema' + ] + assert set(dereference(document, schema)['properties']) == {field} + + +@pytest.mark.parametrize('arguments', ['none', 'partial', 'plain_parent']) +def test_discovery_does_not_depend_on_router_arguments(arguments: str) -> None: + first = MsgspecRouter() + second = MsgspecRouter() + + @second.post('/items') + async def endpoint(item: Item) -> Item: + return item + + parent = APIRouter() + parent.include_router(second, prefix='/child') + app = FastAPI() + app.include_router(first) + app.include_router(parent, prefix='/api') + install_openapi( + app, *([] if arguments == 'none' else [first] if arguments == 'partial' else [parent]) + ) + document = app.openapi() + assert '/api/child/items' in document['paths'] + assert_local_refs_resolve(document) + assert TestClient(app).post('/api/child/items', json={'choice': 'first'}).json() == { + 'choice': 'first' + } + + +def test_plain_router_with_msgspec_route_and_dependency_parameters() -> None: + router = APIRouter(route_class=MsgspecRoute) + + def dependency(choice: Annotated[Choice, Header()]) -> Choice: + return choice + + @router.get('/items') + async def endpoint(choice: Annotated[Choice, Depends(dependency)]) -> Any: + return {'choice': choice} + + app = FastAPI() + app.include_router(router) + install_openapi(app) + document = app.openapi() + assert_local_refs_resolve(document) + schema = document['paths']['/items']['get']['parameters'][0]['schema'] + assert dereference(document, schema)['enum'] == ['first', 'second'] + + +def test_late_routes_and_openapi_cache() -> None: + router = MsgspecRouter() + app = FastAPI() + app.include_router(router, prefix='/api') + install_openapi(app) + + @router.post('/items') + async def endpoint(item: Item) -> Item: + return item + + first = app.openapi() + assert '/api/items' in first['paths'] + assert app.openapi() is first + assert_local_refs_resolve(first) + router.add_api_route('/more', endpoint, methods=['POST']) + assert '/api/more' not in app.openapi()['paths'] + app.openapi_schema = None + second = app.openapi() + assert '/api/more' in second['paths'] + assert_local_refs_resolve(second) + + +@pytest.mark.parametrize('kind', ['route', 'included']) +def test_hidden_routes_do_not_add_components(kind: str) -> None: + class Hidden(msgspec.Struct): + value: str + + router = MsgspecRouter() + + @router.post('/hidden', include_in_schema=kind != 'route') + async def endpoint(item: Hidden) -> Hidden: + return item + + app = FastAPI() + app.include_router(router, include_in_schema=kind != 'included') + install_openapi(app, router) + document = app.openapi() + assert document['paths'] == {} + assert not document.get('components', {}).get('schemas') + + +def test_webhooks_and_nested_callbacks() -> None: + callbacks = MsgspecRouter() + nested = MsgspecRouter() + + @nested.post('/nested') + async def nested_callback(item: Item, choice: Choice) -> Item: + return item + + @callbacks.post('/callback', callbacks=nested.routes) + async def callback(item: Item, choice: Choice) -> Item: + return item + + webhook = MsgspecRouter() + + @webhook.post('event') + async def event(item: Item, choice: Choice) -> Item: + return item + + router = APIRouter() + + @router.post('/trigger', callbacks=callbacks.routes) + async def trigger() -> None: + pass + + app = FastAPI(webhooks=webhook) + app.include_router(router) + install_openapi(app) + document = app.openapi() + assert_local_refs_resolve(document) + webhook_op = document['webhooks']['event']['post'] + callback_op = document['paths']['/trigger']['post']['callbacks']['callback']['/callback'][ + 'post' + ] + nested_op = callback_op['callbacks']['nested_callback']['/nested']['post'] + for operation in (webhook_op, callback_op, nested_op): + schema = operation['requestBody']['content']['application/json']['schema'] + assert set(dereference(document, schema)['properties']) == {'choice'} + parameter = operation['parameters'][0]['schema'] + assert dereference(document, parameter)['enum'] == ['first', 'second'] + assert '415' in operation['responses'] + + +@pytest.mark.parametrize('router_class', [APIRouter, MsgspecRouter]) +def test_body_and_response_metadata_matches_fastapi(router_class: type[APIRouter]) -> None: + router = router_class() + examples = {'sample': {'summary': 'An example', 'value': 'first'}} + + @router.post( + '/items', + responses={ + 200: { + 'description': 'Custom result', + 'content': { + 'application/json': {'examples': examples}, + 'text/plain': {'example': 'first'}, + }, + } + }, + openapi_extra={ + 'requestBody': { + 'description': 'Request description', + 'x-custom': True, + 'content': {'application/json': {'example': 'second'}}, + } + }, + ) + async def endpoint( + item: Annotated[ + str, + Body( + description='Body description', + examples=['first'], + openapi_examples=examples, + json_schema_extra={'x-schema': True}, + ), + ], + ) -> str: + return item + + app = FastAPI() + app.include_router(router) + if router_class is MsgspecRouter: + install_openapi(app) + document = app.openapi() + operation = document['paths']['/items']['post'] + request = operation['requestBody'] + assert request['required'] is True + assert request['description'] == 'Request description' and request['x-custom'] is True + media = request['content']['application/json'] + assert media['example'] == 'second' and media['examples'] == examples + assert media['schema']['description'] == 'Body description' + assert media['schema']['examples'] == ['first'] and media['schema']['x-schema'] is True + assert media['schema']['type'] == 'string' + result = operation['responses']['200'] + assert result['description'] == 'Custom result' + assert result['content']['application/json']['examples'] == examples + assert result['content']['text/plain']['example'] == 'first' + assert result['content']['application/json']['schema']['type'] == 'string' + + +@pytest.mark.parametrize('annotation', [Item, list[int], Annotated[list[int], Body()]]) +def test_structured_path_parameter_fails_at_registration(annotation: Any) -> None: + router = MsgspecRouter() + + async def endpoint(item: annotation) -> None: + pass + + with pytest.raises(AssertionError, match='Path parameters'): + router.add_api_route('/{item}', endpoint, methods=['POST']) + assert router.routes == [] + + +def test_structured_path_parameter_in_include_prefix_is_rejected() -> None: + router = MsgspecRouter() + + @router.post('/items') + async def endpoint(item: Item) -> None: + pass + + app = FastAPI() + app.include_router(router, prefix='/{item}') + with pytest.raises(AssertionError, match='Path parameters'): + install_openapi(app) + + +def test_415_documentation_and_user_override() -> None: + router = MsgspecRouter() + + @router.post('/items', responses={415: {'description': 'Custom media error'}}) + async def endpoint(item: Item) -> None: + pass + + app = FastAPI() + app.include_router(router) + install_openapi(app) + operation = app.openapi()['paths']['/items']['post'] + assert operation['responses']['415']['description'] == 'Custom media error' + assert ( + TestClient(app) + .post('/items', content='{}', headers={'Content-Type': 'text/plain'}) + .status_code + == 415 + ) + + +def test_install_twice_is_rejected() -> None: + app = FastAPI() + install_openapi(app) + with pytest.raises(RuntimeError, match='already installed'): + install_openapi(app) + + +def test_nested_collisions_and_literal_refs_are_preserved() -> None: + pyd_child = create_model('Child', literal=(str, ...)) + pyd_parent = create_model('Parent', child=(pyd_child, ...)) + example = {'$ref': '#/components/schemas/Child'} + child = msgspec.defstruct( + 'Child', + [('ref', str), ('literal', Annotated[dict[str, str], msgspec.Meta(examples=[example])])], + rename={'ref': '$ref'}, + ) + parent = msgspec.defstruct('Parent', [('child', child)]) + app = FastAPI() + plain = APIRouter() + router = MsgspecRouter() + + async def endpoint() -> Any: + return {} + + plain.add_api_route('/plain', endpoint, response_model=pyd_parent) + router.add_api_route('/msgspec', endpoint, response_model=parent) + app.include_router(plain) + app.include_router(router) + install_openapi(app) + document = app.openapi() + schema = document['paths']['/msgspec']['get']['responses']['200']['content'][ + 'application/json' + ]['schema'] + assert_local_refs_resolve(document) + nested = dereference(document, dereference(document, schema)['properties']['child']) + assert nested['properties']['$ref']['type'] == 'string' + assert nested['properties']['literal']['examples'] == [example] + original = document['paths']['/plain']['get']['responses']['200']['content'][ + 'application/json' + ]['schema'] + original_child = dereference(document, dereference(document, original)['properties']['child']) + assert original_child['properties']['literal']['type'] == 'string' + + +@pytest.mark.parametrize('first_plain,last_plain', [(False, False), (False, True), (True, False)]) +def test_duplicate_operations_use_last_visible_route(first_plain: bool, last_plain: bool) -> None: + app = FastAPI() + first = APIRouter() if first_plain else MsgspecRouter() + last = APIRouter() if last_plain else MsgspecRouter() + first_model = ( + create_model('First', first=(int, ...)) + if first_plain + else msgspec.defstruct('First', [('first', int)]) + ) + last_model = ( + create_model('Last', last=(str, ...)) + if last_plain + else msgspec.defstruct('Last', [('last', str)]) + ) + + async def endpoint_first(item: first_model) -> first_model: + return item + + async def endpoint_last(item: last_model) -> last_model: + return item + + first.add_api_route('/items', endpoint_first, methods=['POST']) + last.add_api_route('/items', endpoint_last, methods=['POST']) + app.include_router(first) + app.include_router(last) + install_openapi(app) + document = app.openapi() + assert_local_refs_resolve(document) + operation = document['paths']['/items']['post'] + schemas = [ + operation['requestBody']['content']['application/json']['schema'], + operation['responses']['200']['content']['application/json']['schema'], + ] + for schema in schemas: + assert set(dereference(document, schema)['properties']) == {'last'} + + +@pytest.mark.parametrize('router_class', [APIRouter, MsgspecRouter]) +def test_embedded_body_metadata_belongs_to_field(router_class: type[APIRouter]) -> None: + router = router_class() + for path, description, examples in [ + ('/first', 'First field', [12]), + ('/second', 'Second field', [24]), + ]: + + async def endpoint( + item: Annotated[ + int, + Body( + embed=True, + alias='number', + title='Field title', + description=description, + examples=examples, + json_schema_extra={'x-field': True}, + ), + ], + ) -> int: + return item + + router.add_api_route(path, endpoint, methods=['POST']) + app = FastAPI() + app.include_router(router) + if router_class is MsgspecRouter: + install_openapi(app) + document = app.openapi() + assert_local_refs_resolve(document) + for path, description, examples in [ + ('/first', 'First field', [12]), + ('/second', 'Second field', [24]), + ]: + schema = document['paths'][path]['post']['requestBody']['content']['application/json'][ + 'schema' + ] + envelope = dereference(document, schema) + assert 'description' not in schema and 'examples' not in schema + field = envelope['properties']['number'] + assert field['type'] == 'integer' + assert field['title'] == 'Field title' + assert field['description'] == description + assert field['examples'] == examples + assert field['x-field'] is True + result = TestClient(app).post(path, json={'number': 12}) + assert result.status_code == 200 and result.json() == 12 + + +@pytest.mark.parametrize('router_class', [APIRouter, MsgspecRouter]) +@pytest.mark.parametrize('embedded', [False, True]) +def test_body_schema_callable_matches_fastapi( + router_class: type[APIRouter], embedded: bool +) -> None: + router = router_class() + calls = [] + + def patch(schema: dict[str, Any]) -> None: + calls.append(schema.copy()) + assert schema['type'] == 'integer' and schema['title'] == 'Field title' + schema['description'] = 'Callback description' + schema['examples'] = [42] + + @router.post( + '/items', + openapi_extra={ + 'requestBody': {'content': {'application/json': {'schema': {'x-operation': True}}}} + }, + ) + async def endpoint( + item: Annotated[ + int, + Body( + embed=embedded, + alias='number', + title='Field title', + description='Original description', + json_schema_extra=patch, + ), + ], + ) -> int: + return item + + app = FastAPI() + app.include_router(router) + if router_class is MsgspecRouter: + install_openapi(app) + assert not calls + assert TestClient(app).post('/items', json={'number': 7} if embedded else 7).json() == 7 + assert not calls + document = app.openapi() + schema = document['paths']['/items']['post']['requestBody']['content']['application/json'][ + 'schema' + ] + assert schema['x-operation'] is True + field = dereference(document, schema)['properties']['number'] if embedded else schema + assert field['description'] == 'Callback description' and field['examples'] == [42] + count = len(calls) + assert count > 0 + assert app.openapi() is document and len(calls) == count + + +def test_embedded_schema_callbacks_are_isolated() -> None: + router = MsgspecRouter() + for path, example in [('/first', 12), ('/second', 24)]: + + def patch(schema: dict[str, Any], value: int = example) -> None: + schema['examples'] = [value] + + async def endpoint(item: Annotated[int, Body(embed=True, json_schema_extra=patch)]) -> int: + return item + + router.add_api_route(path, endpoint, methods=['POST']) + app = FastAPI() + app.include_router(router) + install_openapi(app) + document = app.openapi() + assert_local_refs_resolve(document) + for path, example in [('/first', 12), ('/second', 24)]: + schema = document['paths'][path]['post']['requestBody']['content']['application/json'][ + 'schema' + ] + assert dereference(document, schema)['properties']['item']['examples'] == [example] + + +@pytest.mark.parametrize('router_class', [APIRouter, MsgspecRouter]) +@pytest.mark.parametrize('embedded', [False, True]) +def test_body_schema_dictionary_extra_overrides_metadata( + router_class: type[APIRouter], embedded: bool +) -> None: + router = router_class() + + @router.post('/items') + async def endpoint( + item: Annotated[ + int, Body(embed=embedded, examples=[1], json_schema_extra={'examples': [2]}) + ], + ) -> int: + return item + + app = FastAPI() + app.include_router(router) + if router_class is MsgspecRouter: + install_openapi(app) + document = app.openapi() + schema = document['paths']['/items']['post']['requestBody']['content']['application/json'][ + 'schema' + ] + field = dereference(document, schema)['properties']['item'] if embedded else schema + assert field['examples'] == [2] + + +@pytest.mark.parametrize('router_class', [APIRouter, MsgspecRouter]) +def test_optional_embedded_callback_receives_default(router_class: type[APIRouter]) -> None: + router = router_class() + + def patch(schema: dict[str, Any]) -> None: + schema['examples'] = [schema['default']] + + @router.post('/items') + async def endpoint( + item: Annotated[int, Body(embed=True, alias='number', json_schema_extra=patch)] = 7, + ) -> int: + return item + + app = FastAPI() + app.include_router(router) + if router_class is MsgspecRouter: + install_openapi(app) + document = app.openapi() + body = document['paths']['/items']['post']['requestBody'] + schema = dereference(document, body['content']['application/json']['schema']) + assert not body.get('required') and 'required' not in schema + assert schema['properties']['number']['default'] == 7 + assert schema['properties']['number']['examples'] == [7] + assert TestClient(app).post('/items', json={}).json() == 7 + + +def test_failed_schema_callback_does_not_cache_partial_document() -> None: + attempts = 0 + + def patch(schema: dict[str, Any]) -> None: + nonlocal attempts + attempts += 1 + if attempts == 1: + schema['x-partial'] = True + raise RuntimeError('Schema callback failed') + + router = MsgspecRouter() + + @router.post('/items') + async def endpoint(item: Annotated[int, Body(json_schema_extra=patch)]) -> int: + return item + + app = FastAPI() + app.include_router(router) + install_openapi(app) + with pytest.raises(RuntimeError, match='Schema callback failed'): + app.openapi() + assert app.openapi_schema is None + document = app.openapi() + schema = document['paths']['/items']['post']['requestBody']['content']['application/json'][ + 'schema' + ] + assert schema['type'] == 'integer' and 'x-partial' not in schema + assert attempts == 2 and app.openapi() is document diff --git a/tests/test_router.py b/tests/test_router.py index e93a967..c3d3e87 100644 --- a/tests/test_router.py +++ b/tests/test_router.py @@ -344,9 +344,10 @@ async def endpoint( # noqa: ANN202 - Test an endpoint without a return annotati assert next(p for p in parameters if p['name'] == 'max')['schema']['minimum'] == 1 -def test_install_openapi_requires_routers() -> None: - with pytest.raises(TypeError): - install_openapi(FastAPI()) +def test_install_openapi_accepts_no_router_arguments() -> None: + app = FastAPI() + install_openapi(app) + assert app.openapi()['paths'] == {} @pytest.mark.parametrize(