Skip to content

Reference

fastapi_mock_middleware.MockAPIMiddleware

MockAPIMiddleware(app, not_implemented_error_class=APINotImplementedError, content_mocked_header_name='X-Content-Mocked')

Mock API middleware

Mocks unimplemented endpoint responses with generated data according to their response models.

PARAMETER DESCRIPTION
app

ASGI application

not_implemented_error_class

Exception class on raising which middleware returns mocked response: Default: APINotImplementedError. It's not encouraged to use the built-in NotImplementedError not to confuse with the one intended for API mocking.

TYPE: Exception DEFAULT: APINotImplementedError

content_mocked_header_name

response header name indicating that the response has been mocked. Default: X-Content-Mocked

TYPE: str DEFAULT: 'X-Content-Mocked'

Usage example
app = FastAPI()
app.add_middleware(MockAPIMiddleware)
Usage example with arguments
app = FastAPI()
app.add_middleware(MockAPIMiddleware,
                   not_implemented_error_class=APINotImplementedError,
                   content_mocked_header_name='X-Content-Mocked')
Source code in fastapi_mock_middleware/middleware.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def __init__(
        self,
        app,
        not_implemented_error_class: Exception = APINotImplementedError,
        content_mocked_header_name: str = 'X-Content-Mocked'
):
    """
    Mock API middleware

    Mocks unimplemented endpoint responses with generated data according
    to their response models.

    Args:
        app: ASGI application
        not_implemented_error_class: Exception class on raising which
            middleware returns mocked response: Default:
            `APINotImplementedError`. It's not encouraged to use the
            built-in NotImplementedError not to confuse with the one
            intended for API mocking.
        content_mocked_header_name: response header name indicating that the
            response has been mocked. Default: `X-Content-Mocked`

    Usage example:
        ```python
        app = FastAPI()
        app.add_middleware(MockAPIMiddleware)
        ```

    Usage example with arguments:
        ```python
        app = FastAPI()
        app.add_middleware(MockAPIMiddleware,
                           not_implemented_error_class=APINotImplementedError,
                           content_mocked_header_name='X-Content-Mocked')
        ```
    """
    logger.warning(self.warning_msg % self.__class__.__name__)
    self.app = app
    self.not_implemented_error_class = not_implemented_error_class
    self.content_mocked_header_name = content_mocked_header_name

get_content async

get_content(scope)

Get generated content conforming to the route response model

Source code in fastapi_mock_middleware/middleware.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
async def get_content(self, scope) -> Optional[dict]:
    """Get generated content conforming to the route response model"""
    route: APIRoute = scope['route']
    if not route.response_model:
        return None
    if route.response_model is Any:
        return {}

    content = None
    factory_class = self.get_mock_factory_class(route.response_model)
    if factory_class:
        factory = factory_class.create_factory(model=route.response_model, __use_defaults__=True)
        content = factory.build()
    elif isinstance(route.response_model, GenericAlias) and issubclass(get_origin(route.response_model), Sequence):
        # e.g. list[Model]
        item_type = get_args(route.response_model)[0]
        factory_class = self.get_mock_factory_class(item_type)
        if factory_class:
            factory = factory_class.create_factory(model=item_type, __use_defaults__=True)
            content = [factory.build()]
        else:
            content = BaseFactory.__faker__.pylist(1, value_types=[item_type])
    elif isinstance(route.response_model, GenericAlias) and issubclass(get_origin(route.response_model), Mapping):
        # e.g. dict[str, Model]
        key_type, value_type = get_args(route.response_model)
        factory_class = self.get_mock_factory_class(value_type)
        if factory_class:
            factory = factory_class.create_factory(model=value_type, __use_defaults__=True)
            content = {
                key_type(): factory.build()
            }
        else:
            content = BaseFactory.__faker__.pydict(1, value_types=[value_type])
    else:
        provider = BaseFactory.get_provider_map().get(route.response_model, None)
        if provider:
            content = provider()
        else:
            raise ValueError(f'Cannot mock {route.response_model.__name__}')

    content = await serialize_response(
        field=route.response_field,
        response_content=content,
        include=route.response_model_include,
        exclude=route.response_model_exclude,
        by_alias=route.response_model_by_alias,
        exclude_unset=route.response_model_exclude_unset,
        exclude_defaults=route.response_model_exclude_defaults,
        exclude_none=route.response_model_exclude_none,
    )
    return content

fastapi_mock_middleware.APINotImplementedError

APINotImplementedError(*, return_value=None)

Bases: NotImplementedError

API NotImplementedError

Exception class to be risen on unimplemented endpoints for mocking their response data by MockAPIMiddleware

PARAMETER DESCRIPTION
return_value

Value to return as mock data. Optional, in most cases autogenerated data should be enough. Use when specific data is required or in complex cases where data mocking according to response model did not work as expected.

TYPE: Any DEFAULT: None

Source code in fastapi_mock_middleware/middleware.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def __init__(self, *, return_value: Any = None):
    """
    API NotImplementedError

    Exception class to be risen on unimplemented endpoints for mocking their
    response data by `MockAPIMiddleware`

    Args:
        return_value: Value to return as mock data. Optional, in most cases
            autogenerated data should be enough. Use when specific data
            is required or in complex cases where data mocking according to
            response model did not work as expected.
    """
    super().__init__()
    self.return_value = return_value