Skip to content

APIRouter

APIRouter ⚓︎

Bases: Router

Source code in star_openapi/router.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
class APIRouter(Router):
    def __init__(
        self,
        *,
        url_prefix: str = "",
        tags: list[Tag | dict[str, Any]] | None = None,
        security: list[dict[str, list[str]]] | None = None,
        operation_id_callback: Callable = get_operation_id_for_path,
        doc_ui: bool = True,
        **kwargs,
    ):
        """
        Based on Router

        Args:
            url_prefix: URL prefix that will be added before all route paths.
            tags: APIRouter tags for every API.
            security: APIRouter security for every API.
            operation_id_callback: Callback function for custom operation_id generation.
            doc_ui: Enable OpenAPI document UI (Swagger UI, Redoc, etc.). Defaults to True.
            **kwargs: Starlette Router kwargs
        """
        super().__init__(**kwargs)

        self.url_prefix = url_prefix
        self.paths: dict[str, Any] = {}
        self.components_schemas: dict[str, Any] = {}
        self.tags = tags or []
        self.tag_names: list[str] = []
        self.security = security or []
        self.operation_id_callback = operation_id_callback
        self.doc_ui = doc_ui

    def register_api(self, api: "APIRouter"):
        for tag in api.tags:
            if isinstance(tag, dict):
                tag = Tag(**tag)
            if tag.name not in self.tag_names:
                # Append tag to the list of tags
                self.tags.append(tag)
                # Append tag name to the list of tag names
                self.tag_names.append(tag.name)

        self.paths.update(**api.paths)

        # Update component schemas with the APIRouter's component schemas
        self.components_schemas.update(**api.components_schemas)

        # Register the APIRouter with the current instance
        for route in api.routes:
            if isinstance(route, Route):
                path_with_prefix = api.url_prefix + route.path
                self.add_route(
                    path=path_with_prefix,
                    endpoint=route.endpoint,
                    methods=route.methods,
                    name=route.name,
                )
            elif isinstance(route, WebSocketRoute):
                path_with_prefix = api.url_prefix + route.path
                self.add_websocket_route(path=path_with_prefix, endpoint=route.endpoint, name=route.name)

    def _collect_openapi_info(
        self,
        rule: str,
        func: Callable,
        *,
        tags: list[Tag | dict[str, Any]] | None = None,
        summary: str | None = None,
        description: str | None = None,
        external_docs: ExternalDocumentation | dict[str, Any] | None = None,
        operation_id: str | None = None,
        deprecated: bool | None = None,
        security: list[dict[str, list[Any]]] | None = None,
        servers: list[Server | dict[str, Any]] | None = None,
        openapi_extensions: dict[str, Any] | None = None,
        doc_ui: bool = True,
        method: str = HTTPMethod.GET,
    ) -> ParametersTuple:
        if self.doc_ui and doc_ui:
            # Create operation
            operation = get_operation(
                func,
                summary=summary,
                description=description,
                openapi_extensions=openapi_extensions,
            )

            # Set external docs
            if external_docs:
                operation.externalDocs = external_docs

            # Unique string used to identify the operation.
            operation.operationId = operation_id or self.operation_id_callback(
                url_prefix=self.url_prefix, name=func.__name__, path=rule, method=method
            )

            # Only set `deprecated` if True, otherwise leave it as None
            if deprecated is not None:
                operation.deprecated = deprecated

            # Add security
            _security = (security or []) + self.security or None
            if _security:
                operation.security = _security

            # Add servers
            if servers:
                operation.servers = servers

            # Store tags
            tags = (tags or []) + self.tags
            parse_and_store_tags(tags, self.tags, self.tag_names, operation)

            # Parse rule: merge url_prefix and format rule from /pet/<petId> to /pet/{petId}
            uri = parse_rule(rule, url_prefix=self.url_prefix)

            # Parse method
            parse_method(uri, method, self.paths, operation)

            # Parse parameters
            return parse_parameters(func, components_schemas=self.components_schemas, operation=operation)
        else:
            return parse_parameters(func, doc_ui=False)

    def get(
        self,
        rule: str,
        *,
        name: str | None = None,
        tags: list[Tag | dict[str, Any]] | None = None,
        summary: str | None = None,
        description: str | None = None,
        external_docs: ExternalDocumentation | dict[str, Any] | None = None,
        operation_id: str | None = None,
        deprecated: bool | None = None,
        security: list[dict[str, list[Any]]] | None = None,
        servers: list[Server | dict[str, Any]] | None = None,
        openapi_extensions: dict[str, Any] | None = None,
        doc_ui: bool = True,
    ):
        def decorator(func) -> Callable:
            header, cookie, path, query, form, body = self._collect_openapi_info(
                rule,
                func,
                tags=tags,
                summary=summary,
                description=description,
                external_docs=external_docs,
                operation_id=operation_id,
                deprecated=deprecated,
                security=security,
                servers=servers,
                openapi_extensions=openapi_extensions,
                doc_ui=doc_ui,
                method=HTTPMethod.GET,
            )
            endpoint = create_endpoint(func, header, cookie, path, query, form, body)
            self.add_route(rule, endpoint, methods=["GET"], name=name, include_in_schema=False)

            return func

        return decorator

    def post(
        self,
        rule: str,
        *,
        name: str | None = None,
        tags: list[Tag | dict[str, Any]] | None = None,
        summary: str | None = None,
        description: str | None = None,
        external_docs: ExternalDocumentation | dict[str, Any] | None = None,
        operation_id: str | None = None,
        deprecated: bool | None = None,
        security: list[dict[str, list[Any]]] | None = None,
        servers: list[Server | dict[str, Any]] | None = None,
        openapi_extensions: dict[str, Any] | None = None,
        doc_ui: bool = True,
    ):
        def decorator(func) -> Callable:
            header, cookie, path, query, form, body = self._collect_openapi_info(
                rule,
                func,
                tags=tags,
                summary=summary,
                description=description,
                external_docs=external_docs,
                operation_id=operation_id,
                deprecated=deprecated,
                security=security,
                servers=servers,
                openapi_extensions=openapi_extensions,
                doc_ui=doc_ui,
                method=HTTPMethod.POST,
            )
            endpoint = create_endpoint(func, header, cookie, path, query, form, body)
            self.add_route(rule, endpoint, methods=["POST"], name=name, include_in_schema=False)

            return func

        return decorator

    def put(
        self,
        rule: str,
        *,
        name: str | None = None,
        tags: list[Tag | dict[str, Any]] | None = None,
        summary: str | None = None,
        description: str | None = None,
        external_docs: ExternalDocumentation | dict[str, Any] | None = None,
        operation_id: str | None = None,
        deprecated: bool | None = None,
        security: list[dict[str, list[Any]]] | None = None,
        servers: list[Server | dict[str, Any]] | None = None,
        openapi_extensions: dict[str, Any] | None = None,
        doc_ui: bool = True,
    ):
        def decorator(func) -> Callable:
            header, cookie, path, query, form, body = self._collect_openapi_info(
                rule,
                func,
                tags=tags,
                summary=summary,
                description=description,
                external_docs=external_docs,
                operation_id=operation_id,
                deprecated=deprecated,
                security=security,
                servers=servers,
                openapi_extensions=openapi_extensions,
                doc_ui=doc_ui,
                method=HTTPMethod.PUT,
            )
            endpoint = create_endpoint(func, header, cookie, path, query, form, body)
            self.add_route(rule, endpoint, methods=["PUT"], name=name, include_in_schema=False)

            return func

        return decorator

    def delete(
        self,
        rule: str,
        *,
        name: str | None = None,
        tags: list[Tag | dict[str, Any]] | None = None,
        summary: str | None = None,
        description: str | None = None,
        external_docs: ExternalDocumentation | dict[str, Any] | None = None,
        operation_id: str | None = None,
        deprecated: bool | None = None,
        security: list[dict[str, list[Any]]] | None = None,
        servers: list[Server | dict[str, Any]] | None = None,
        openapi_extensions: dict[str, Any] | None = None,
        doc_ui: bool = True,
    ):
        def decorator(func) -> Callable:
            header, cookie, path, query, form, body = self._collect_openapi_info(
                rule,
                func,
                tags=tags,
                summary=summary,
                description=description,
                external_docs=external_docs,
                operation_id=operation_id,
                deprecated=deprecated,
                security=security,
                servers=servers,
                openapi_extensions=openapi_extensions,
                doc_ui=doc_ui,
                method=HTTPMethod.DELETE,
            )
            endpoint = create_endpoint(func, header, cookie, path, query, form, body)
            self.add_route(rule, endpoint, methods=["DELETE"], name=name, include_in_schema=False)

            return func

        return decorator

    def patch(
        self,
        rule: str,
        *,
        name: str | None = None,
        tags: list[Tag | dict[str, Any]] | None = None,
        summary: str | None = None,
        description: str | None = None,
        external_docs: ExternalDocumentation | dict[str, Any] | None = None,
        operation_id: str | None = None,
        deprecated: bool | None = None,
        security: list[dict[str, list[Any]]] | None = None,
        servers: list[Server | dict[str, Any]] | None = None,
        openapi_extensions: dict[str, Any] | None = None,
        doc_ui: bool = True,
    ):
        def decorator(func) -> Callable:
            header, cookie, path, query, form, body = self._collect_openapi_info(
                rule,
                func,
                tags=tags,
                summary=summary,
                description=description,
                external_docs=external_docs,
                operation_id=operation_id,
                deprecated=deprecated,
                security=security,
                servers=servers,
                openapi_extensions=openapi_extensions,
                doc_ui=doc_ui,
                method=HTTPMethod.PATCH,
            )
            endpoint = create_endpoint(func, header, cookie, path, query, form, body)
            self.add_route(rule, endpoint, methods=["PATCH"], name=name, include_in_schema=False)

            return func

        return decorator

    def websocket(
        self,
        rule: str,
        *,
        name: str | None = None,
    ):
        def decorator(func) -> Callable:
            self.add_websocket_route(
                rule,
                func,
                name=name,
            )
            return func

        return decorator

__init__(*, url_prefix='', tags=None, security=None, operation_id_callback=get_operation_id_for_path, doc_ui=True, **kwargs) ⚓︎

Based on Router

Parameters:

Name Type Description Default
url_prefix str

URL prefix that will be added before all route paths.

''
tags list[Tag | dict[str, Any]] | None

APIRouter tags for every API.

None
security list[dict[str, list[str]]] | None

APIRouter security for every API.

None
operation_id_callback Callable

Callback function for custom operation_id generation.

get_operation_id_for_path
doc_ui bool

Enable OpenAPI document UI (Swagger UI, Redoc, etc.). Defaults to True.

True
**kwargs

Starlette Router kwargs

{}
Source code in star_openapi/router.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def __init__(
    self,
    *,
    url_prefix: str = "",
    tags: list[Tag | dict[str, Any]] | None = None,
    security: list[dict[str, list[str]]] | None = None,
    operation_id_callback: Callable = get_operation_id_for_path,
    doc_ui: bool = True,
    **kwargs,
):
    """
    Based on Router

    Args:
        url_prefix: URL prefix that will be added before all route paths.
        tags: APIRouter tags for every API.
        security: APIRouter security for every API.
        operation_id_callback: Callback function for custom operation_id generation.
        doc_ui: Enable OpenAPI document UI (Swagger UI, Redoc, etc.). Defaults to True.
        **kwargs: Starlette Router kwargs
    """
    super().__init__(**kwargs)

    self.url_prefix = url_prefix
    self.paths: dict[str, Any] = {}
    self.components_schemas: dict[str, Any] = {}
    self.tags = tags or []
    self.tag_names: list[str] = []
    self.security = security or []
    self.operation_id_callback = operation_id_callback
    self.doc_ui = doc_ui