Skip to content

Reference

fastapi_mock_middleware.MockAPIMiddleware

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

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'

default_list_size

List size to generate for list responses.

TYPE: int DEFAULT: 10

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',
    default_list_size=10,
)
Source code in fastapi_mock_middleware/middleware.py
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
76
77
78
79
80
81
82
83
def __init__(
        self,
        app,
        not_implemented_error_class: Exception = APINotImplementedError,
        content_mocked_header_name: str = 'X-Content-Mocked',
        default_list_size: int = 10,
):
    """
    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`
        default_list_size: List size to generate for list responses.

    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',
            default_list_size=10,
        )
        ```
    """
    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
    self.default_list_size = default_list_size

get_content async

get_content(scope, list_size=10)

Get generated content conforming to the route response model

Source code in fastapi_mock_middleware/middleware.py
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
164
165
166
167
168
169
170
171
172
async def get_content(self, scope, list_size: int = 10) -> 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() for _ in range(list_size)]
        else:
            content = BaseFactory.__faker__.pylist(list_size, value_types=[item_type], variable_nb_elements=False)
    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, list_size=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

list_size

List size to generate for list responses.

TYPE: int 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
30
31
def __init__(self, *, return_value: Any = None, list_size: int = 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.
        list_size: List size to generate for list responses.
    """
    super().__init__()
    self.return_value = return_value
    self.list_size = list_size