跳转至

OpenAPI

OpenAPI ⚓︎

Bases: Starlette

Source code in star_openapi/openapi.py
 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
class OpenAPI(Starlette):
    def __init__(
        self,
        *,
        info: Info | dict[str, Any] | None = None,
        security_schemes: dict[str, SecurityScheme | dict[str, Any]] | None = None,
        servers: list[Server | dict[str, Any]] | None = None,
        external_docs: ExternalDocumentation | dict[str, Any] | None = None,
        operation_id_callback: Callable = get_operation_id_for_path,
        openapi_extensions: dict[str, Any] | None = None,
        validation_error_status: str | int = 422,
        validation_error_model: Type[BaseModel] = ValidationErrorModel,
        validation_error_callback: Callable = make_validation_error_response,
        responses: ResponseDict | None = None,
        doc_ui: bool = True,
        doc_prefix: str = "/openapi",
        doc_url: str = "/openapi.json",
        **kwargs,
    ):
        """
        OpenAPI class that provides REST API functionality along with Swagger UI and Redoc, etc.

        Args:
            info: Information about the API (title, version, etc.).
                See https://spec.openapis.org/oas/v3.1.0#info-object.
            security_schemes: Security schemes for the API.
                See https://spec.openapis.org/oas/v3.1.0#security-scheme-object.
            servers: An array of Server objects providing connectivity information to a target server.
            external_docs: External documentation for the API.
                See: https://spec.openapis.org/oas/v3.1.0#external-documentation-object.
            operation_id_callback: Callback function for custom operation ID generation.
                Receives name (str), path (str), and method (str) parameters.
                Defaults to `get_operation_id_for_path` from utils.
            openapi_extensions: Extensions to the OpenAPI Schema.
                See https://spec.openapis.org/oas/v3.1.0#specification-extensions.
            validation_error_status:
                HTTP Status of the response given when a validation error is detected by pydantic.
                Defaults to 422.
            validation_error_model: Validation error response model for OpenAPI Specification.
            validation_error_callback: Validation error response callback, the return format corresponds to
                the validation_error_model.
            responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
            doc_ui: Enable OpenAPI document UI (Swagger UI and Redoc).
                Defaults to True.
            doc_prefix: URL prefix used for OpenAPI document and UI.
                Defaults to "/openapi".
            doc_url: URL for accessing the OpenAPI specification document in JSON format.
                Defaults to "/openapi.json".
            **kwargs: Additional kwargs to be passed to Starlette.
        """
        super().__init__(**kwargs)

        self.config = Config()

        # Set OpenAPI version and API information
        self.openapi_version = "3.1.0"
        self.info = info or {"title": "OpenAPI", "version": "1.0.0"}

        # Set security schemes, responses, paths and components
        self.security_schemes = security_schemes

        # Initialize instance variables
        self.paths: dict[str, Any] = {}
        self.components_schemas: dict[str, Any] = {}
        self.components = Components()

        # Initialize lists for tags and tag names
        self.tags: list[Tag] = []
        self.tag_names: list[str] = []

        # Set URL prefixes and endpoints
        self.doc_prefix = doc_prefix
        self.doc_url = doc_url

        # Set servers and external documentation
        self.severs = servers
        self.external_docs = external_docs

        # Set the operation ID callback function
        self.operation_id_callback: Callable = operation_id_callback

        # Set OpenAPI extensions
        self.openapi_extensions = openapi_extensions or {}

        # Set HTTP Response of validation errors within OpenAPI
        self.validation_error_status = str(validation_error_status)
        self.validation_error_model = validation_error_model
        self.add_exception_handler(ValidationError, validation_error_callback)

        # Convert responses key to string
        self.responses = convert_responses_key_to_string(responses or {})

        # Initialize the OpenAPI documentation UI
        if doc_ui:
            self._init_doc()

        # Initialize specification JSON
        self.spec_json: dict[str, Any] = {}

        self.cli = cli

    def _init_doc(self) -> None:
        template = Template(openapi_html_string)

        routes = []
        ui_templates = []
        for entry_point in entry_points(group="star_openapi.plugins"):
            try:
                module_path = entry_point.value
                module_name, class_name = module_path.rsplit(".", 1)
                module = import_module(module_name)
                plugin = getattr(module, class_name)()
                plugin_register = plugin.register
                plugin_name = plugin.name
                plugin_display_name = plugin.display_name
                route = plugin_register(doc_url=self.doc_url.lstrip("/"))
                routes.extend(route)
                ui_templates.append({"name": plugin_name, "display_name": plugin_display_name})
            except (ModuleNotFoundError, AttributeError):  # pragma: no cover
                import traceback

                print(f"Warning: plugin '{entry_point.value}' registration failed.")
                traceback.print_exc()

        routes.append(
            Route(
                "/",
                endpoint=lambda request: HTMLResponse(content=template.render({"ui_templates": ui_templates})),
                methods=["GET"],
                name="index",
            )
        )
        routes.append(
            Route(
                self.doc_url,
                endpoint=lambda request: JSONResponse(self.api_doc),
                methods=["GET"],
                name="openapi",
            )
        )

        self.router.routes.append(Mount(self.doc_prefix, routes=routes, name="openapi"))

    @property
    def api_doc(self) -> dict:
        if self.spec_json:
            return self.spec_json

        self.generate_spec_json()

        return self.spec_json

    def generate_spec_json(self):
        if isinstance(self.info, dict):
            self.info = Info.model_validate(self.info)
        spec = OpenAPISpec(openapi=self.openapi_version, info=self.info, paths=self.paths)

        if self.severs:
            spec.servers = [Server(**server) if isinstance(server, dict) else server for server in self.severs]

        if self.external_docs:
            if isinstance(self.external_docs, dict):
                self.external_docs = ExternalDocumentation.model_validate(self.external_docs)
            spec.externalDocs = self.external_docs

        # Set tags
        if self.tags:
            spec.tags = self.tags

        # Add ValidationErrorModel to components schemas
        schema = get_model_schema(self.validation_error_model)
        self.components_schemas[self.validation_error_model.__name__] = Schema(**schema)

        # Parse definitions
        definitions = schema.get("$defs", {})
        for name, value in definitions.items():
            self.components_schemas[name] = Schema(**value)

        # Set components
        self.components.schemas = self.components_schemas
        self.components.securitySchemes = self.security_schemes
        spec.components = self.components

        # Convert spec to JSON
        self.spec_json = spec.model_dump(mode="json", by_alias=True, exclude_unset=True, warnings=False)

        # Update with OpenAPI extensions
        self.spec_json.update(**self.openapi_extensions)

        # Handle validation error response
        for rule, path_item in self.spec_json["paths"].items():
            for http_method, operation in path_item.items():
                if operation["responses"].get(self.validation_error_status):
                    continue
                operation["responses"][self.validation_error_status] = {
                    "description": HTTP_STATUS[self.validation_error_status],
                    "content": {
                        "application/json": {
                            "schema": {
                                "type": "array",
                                "items": {"$ref": f"{OPENAPI3_REF_PREFIX}/{self.validation_error_model.__name__}"},
                            }
                        }
                    },
                }

    def register_api(self, api: APIRouter):
        """
        Register an APIRouter.

        Args:
            api: The APIBlueprint instance to register.
        """
        for tag in api.tags:
            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.router.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.router.add_websocket_route(path=path_with_prefix, endpoint=route.endpoint, name=route.name)

    def _collect_openapi_info(
        self,
        rule: str,
        func: FunctionType,
        *,
        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,
        request_body: RequestBody | dict[str, Any] | None = None,
        responses: ResponseDict | None = None,
        doc_ui: bool = True,
        method: str = HTTPMethod.GET,
    ) -> ParametersTuple:
        if doc_ui:
            # Convert key to string
            endpoint_responses = convert_responses_key_to_string(responses or {})

            # Global response: combine API responses
            combine_responses = {**self.responses, **endpoint_responses}

            # 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(
                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
            if security:
                operation.security = security

            # Add servers
            if servers:
                operation.servers = servers

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

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

            if isinstance(request_body, dict):
                request_body = RequestBody(**request_body)

            # Parse response
            get_responses(combine_responses, self.components_schemas, operation)

            # Parse parameters
            return parse_parameters(
                func,
                components_schemas=self.components_schemas,
                operation=operation,
                request_body=request_body,
            )
        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,
        responses: ResponseDict | None = None,
        doc_ui: bool = True,
    ):
        """
        Decorator for defining a REST API endpoint with the HTTP GET method.
        More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

        Args:
            rule: The URL rule string.
            tags: Adds metadata to a single tag.
            summary: A short summary of what the operation does.
            description: A verbose explanation of the operation behavior.
            external_docs: Additional external documentation for this operation.
            operation_id: Unique string used to identify the operation.
            deprecated: Declares this operation to be deprecated.
            security: A declaration of which security mechanisms can be used for this operation.
            servers: An alternative server array to service this operation.
            openapi_extensions: Allows extensions to the OpenAPI Schema.
            responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
            doc_ui: Declares this operation to be shown. Default to 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,
                responses=responses,
                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,
        request_body: RequestBody | dict[str, Any] | None = None,
        responses: ResponseDict | None = None,
        doc_ui: bool = True,
    ):
        """
        Decorator for defining a REST API endpoint with the HTTP POST method.
        More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

        Args:
            rule: The URL rule string.
            tags: Adds metadata to a single tag.
            summary: A short summary of what the operation does.
            description: A verbose explanation of the operation behavior.
            external_docs: Additional external documentation for this operation.
            operation_id: Unique string used to identify the operation.
            deprecated: Declares this operation to be deprecated.
            security: A declaration of which security mechanisms can be used for this operation.
            servers: An alternative server array to service this operation.
            openapi_extensions: Allows extensions to the OpenAPI Schema.
            responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
            doc_ui: Declares this operation to be shown. Default to 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,
                request_body=request_body,
                responses=responses,
                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,
        request_body: RequestBody | dict[str, Any] | None = None,
        responses: ResponseDict | None = None,
        doc_ui: bool = True,
    ):
        """
        Decorator for defining a REST API endpoint with the HTTP PUT method.
        More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

        Args:
            rule: The URL rule string.
            tags: Adds metadata to a single tag.
            summary: A short summary of what the operation does.
            description: A verbose explanation of the operation behavior.
            external_docs: Additional external documentation for this operation.
            operation_id: Unique string used to identify the operation.
            deprecated: Declares this operation to be deprecated.
            security: A declaration of which security mechanisms can be used for this operation.
            servers: An alternative server array to service this operation.
            openapi_extensions: Allows extensions to the OpenAPI Schema.
            responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
            doc_ui: Declares this operation to be shown. Default to 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,
                request_body=request_body,
                responses=responses,
                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,
        request_body: RequestBody | dict[str, Any] | None = None,
        responses: ResponseDict | None = None,
        doc_ui: bool = True,
    ):
        """
        Decorator for defining a REST API endpoint with the HTTP DELETE method.
        More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

        Args:
            rule: The URL rule string.
            tags: Adds metadata to a single tag.
            summary: A short summary of what the operation does.
            description: A verbose explanation of the operation behavior.
            external_docs: Additional external documentation for this operation.
            operation_id: Unique string used to identify the operation.
            deprecated: Declares this operation to be deprecated.
            security: A declaration of which security mechanisms can be used for this operation.
            servers: An alternative server array to service this operation.
            openapi_extensions: Allows extensions to the OpenAPI Schema.
            responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
            doc_ui: Declares this operation to be shown. Default to 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,
                request_body=request_body,
                responses=responses,
                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,
        request_body: RequestBody | dict[str, Any] | None = None,
        responses: ResponseDict | None = None,
        doc_ui: bool = True,
    ):
        """
        Decorator for defining a REST API endpoint with the HTTP PATCH method.
        More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

        Args:
            rule: The URL rule string.
            tags: Adds metadata to a single tag.
            summary: A short summary of what the operation does.
            description: A verbose explanation of the operation behavior.
            external_docs: Additional external documentation for this operation.
            operation_id: Unique string used to identify the operation.
            deprecated: Declares this operation to be deprecated.
            security: A declaration of which security mechanisms can be used for this operation.
            servers: An alternative server array to service this operation.
            openapi_extensions: Allows extensions to the OpenAPI Schema.
            responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
            doc_ui: Declares this operation to be shown. Default to 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,
                request_body=request_body,
                responses=responses,
                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__(*, info=None, security_schemes=None, servers=None, external_docs=None, operation_id_callback=get_operation_id_for_path, openapi_extensions=None, validation_error_status=422, validation_error_model=ValidationErrorModel, validation_error_callback=make_validation_error_response, responses=None, doc_ui=True, doc_prefix='/openapi', doc_url='/openapi.json', **kwargs) ⚓︎

OpenAPI class that provides REST API functionality along with Swagger UI and Redoc, etc.

Parameters:

Name Type Description Default
info Info | dict[str, Any] | None

Information about the API (title, version, etc.). See https://spec.openapis.org/oas/v3.1.0#info-object.

None
security_schemes dict[str, SecurityScheme | dict[str, Any]] | None None
servers list[Server | dict[str, Any]] | None

An array of Server objects providing connectivity information to a target server.

None
external_docs ExternalDocumentation | dict[str, Any] | None

External documentation for the API. See: https://spec.openapis.org/oas/v3.1.0#external-documentation-object.

None
operation_id_callback Callable

Callback function for custom operation ID generation. Receives name (str), path (str), and method (str) parameters. Defaults to get_operation_id_for_path from utils.

get_operation_id_for_path
openapi_extensions dict[str, Any] | None

Extensions to the OpenAPI Schema. See https://spec.openapis.org/oas/v3.1.0#specification-extensions.

None
validation_error_status str | int

HTTP Status of the response given when a validation error is detected by pydantic. Defaults to 422.

422
validation_error_model Type[BaseModel]

Validation error response model for OpenAPI Specification.

ValidationErrorModel
validation_error_callback Callable

Validation error response callback, the return format corresponds to the validation_error_model.

make_validation_error_response
responses ResponseDict | None

API responses should be either a subclass of BaseModel, a dictionary, or None.

None
doc_ui bool

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

True
doc_prefix str

URL prefix used for OpenAPI document and UI. Defaults to "/openapi".

'/openapi'
doc_url str

URL for accessing the OpenAPI specification document in JSON format. Defaults to "/openapi.json".

'/openapi.json'
**kwargs

Additional kwargs to be passed to Starlette.

{}
Source code in star_openapi/openapi.py
 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
def __init__(
    self,
    *,
    info: Info | dict[str, Any] | None = None,
    security_schemes: dict[str, SecurityScheme | dict[str, Any]] | None = None,
    servers: list[Server | dict[str, Any]] | None = None,
    external_docs: ExternalDocumentation | dict[str, Any] | None = None,
    operation_id_callback: Callable = get_operation_id_for_path,
    openapi_extensions: dict[str, Any] | None = None,
    validation_error_status: str | int = 422,
    validation_error_model: Type[BaseModel] = ValidationErrorModel,
    validation_error_callback: Callable = make_validation_error_response,
    responses: ResponseDict | None = None,
    doc_ui: bool = True,
    doc_prefix: str = "/openapi",
    doc_url: str = "/openapi.json",
    **kwargs,
):
    """
    OpenAPI class that provides REST API functionality along with Swagger UI and Redoc, etc.

    Args:
        info: Information about the API (title, version, etc.).
            See https://spec.openapis.org/oas/v3.1.0#info-object.
        security_schemes: Security schemes for the API.
            See https://spec.openapis.org/oas/v3.1.0#security-scheme-object.
        servers: An array of Server objects providing connectivity information to a target server.
        external_docs: External documentation for the API.
            See: https://spec.openapis.org/oas/v3.1.0#external-documentation-object.
        operation_id_callback: Callback function for custom operation ID generation.
            Receives name (str), path (str), and method (str) parameters.
            Defaults to `get_operation_id_for_path` from utils.
        openapi_extensions: Extensions to the OpenAPI Schema.
            See https://spec.openapis.org/oas/v3.1.0#specification-extensions.
        validation_error_status:
            HTTP Status of the response given when a validation error is detected by pydantic.
            Defaults to 422.
        validation_error_model: Validation error response model for OpenAPI Specification.
        validation_error_callback: Validation error response callback, the return format corresponds to
            the validation_error_model.
        responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
        doc_ui: Enable OpenAPI document UI (Swagger UI and Redoc).
            Defaults to True.
        doc_prefix: URL prefix used for OpenAPI document and UI.
            Defaults to "/openapi".
        doc_url: URL for accessing the OpenAPI specification document in JSON format.
            Defaults to "/openapi.json".
        **kwargs: Additional kwargs to be passed to Starlette.
    """
    super().__init__(**kwargs)

    self.config = Config()

    # Set OpenAPI version and API information
    self.openapi_version = "3.1.0"
    self.info = info or {"title": "OpenAPI", "version": "1.0.0"}

    # Set security schemes, responses, paths and components
    self.security_schemes = security_schemes

    # Initialize instance variables
    self.paths: dict[str, Any] = {}
    self.components_schemas: dict[str, Any] = {}
    self.components = Components()

    # Initialize lists for tags and tag names
    self.tags: list[Tag] = []
    self.tag_names: list[str] = []

    # Set URL prefixes and endpoints
    self.doc_prefix = doc_prefix
    self.doc_url = doc_url

    # Set servers and external documentation
    self.severs = servers
    self.external_docs = external_docs

    # Set the operation ID callback function
    self.operation_id_callback: Callable = operation_id_callback

    # Set OpenAPI extensions
    self.openapi_extensions = openapi_extensions or {}

    # Set HTTP Response of validation errors within OpenAPI
    self.validation_error_status = str(validation_error_status)
    self.validation_error_model = validation_error_model
    self.add_exception_handler(ValidationError, validation_error_callback)

    # Convert responses key to string
    self.responses = convert_responses_key_to_string(responses or {})

    # Initialize the OpenAPI documentation UI
    if doc_ui:
        self._init_doc()

    # Initialize specification JSON
    self.spec_json: dict[str, Any] = {}

    self.cli = cli

delete(rule, *, name=None, tags=None, summary=None, description=None, external_docs=None, operation_id=None, deprecated=None, security=None, servers=None, openapi_extensions=None, request_body=None, responses=None, doc_ui=True) ⚓︎

Decorator for defining a REST API endpoint with the HTTP DELETE method. More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

Parameters:

Name Type Description Default
rule str

The URL rule string.

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

Adds metadata to a single tag.

None
summary str | None

A short summary of what the operation does.

None
description str | None

A verbose explanation of the operation behavior.

None
external_docs ExternalDocumentation | dict[str, Any] | None

Additional external documentation for this operation.

None
operation_id str | None

Unique string used to identify the operation.

None
deprecated bool | None

Declares this operation to be deprecated.

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

A declaration of which security mechanisms can be used for this operation.

None
servers list[Server | dict[str, Any]] | None

An alternative server array to service this operation.

None
openapi_extensions dict[str, Any] | None

Allows extensions to the OpenAPI Schema.

None
responses ResponseDict | None

API responses should be either a subclass of BaseModel, a dictionary, or None.

None
doc_ui bool

Declares this operation to be shown. Default to True.

True
Source code in star_openapi/openapi.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
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,
    request_body: RequestBody | dict[str, Any] | None = None,
    responses: ResponseDict | None = None,
    doc_ui: bool = True,
):
    """
    Decorator for defining a REST API endpoint with the HTTP DELETE method.
    More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

    Args:
        rule: The URL rule string.
        tags: Adds metadata to a single tag.
        summary: A short summary of what the operation does.
        description: A verbose explanation of the operation behavior.
        external_docs: Additional external documentation for this operation.
        operation_id: Unique string used to identify the operation.
        deprecated: Declares this operation to be deprecated.
        security: A declaration of which security mechanisms can be used for this operation.
        servers: An alternative server array to service this operation.
        openapi_extensions: Allows extensions to the OpenAPI Schema.
        responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
        doc_ui: Declares this operation to be shown. Default to 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,
            request_body=request_body,
            responses=responses,
            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

get(rule, *, name=None, tags=None, summary=None, description=None, external_docs=None, operation_id=None, deprecated=None, security=None, servers=None, openapi_extensions=None, responses=None, doc_ui=True) ⚓︎

Decorator for defining a REST API endpoint with the HTTP GET method. More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

Parameters:

Name Type Description Default
rule str

The URL rule string.

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

Adds metadata to a single tag.

None
summary str | None

A short summary of what the operation does.

None
description str | None

A verbose explanation of the operation behavior.

None
external_docs ExternalDocumentation | dict[str, Any] | None

Additional external documentation for this operation.

None
operation_id str | None

Unique string used to identify the operation.

None
deprecated bool | None

Declares this operation to be deprecated.

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

A declaration of which security mechanisms can be used for this operation.

None
servers list[Server | dict[str, Any]] | None

An alternative server array to service this operation.

None
openapi_extensions dict[str, Any] | None

Allows extensions to the OpenAPI Schema.

None
responses ResponseDict | None

API responses should be either a subclass of BaseModel, a dictionary, or None.

None
doc_ui bool

Declares this operation to be shown. Default to True.

True
Source code in star_openapi/openapi.py
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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,
    responses: ResponseDict | None = None,
    doc_ui: bool = True,
):
    """
    Decorator for defining a REST API endpoint with the HTTP GET method.
    More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

    Args:
        rule: The URL rule string.
        tags: Adds metadata to a single tag.
        summary: A short summary of what the operation does.
        description: A verbose explanation of the operation behavior.
        external_docs: Additional external documentation for this operation.
        operation_id: Unique string used to identify the operation.
        deprecated: Declares this operation to be deprecated.
        security: A declaration of which security mechanisms can be used for this operation.
        servers: An alternative server array to service this operation.
        openapi_extensions: Allows extensions to the OpenAPI Schema.
        responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
        doc_ui: Declares this operation to be shown. Default to 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,
            responses=responses,
            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

patch(rule, *, name=None, tags=None, summary=None, description=None, external_docs=None, operation_id=None, deprecated=None, security=None, servers=None, openapi_extensions=None, request_body=None, responses=None, doc_ui=True) ⚓︎

Decorator for defining a REST API endpoint with the HTTP PATCH method. More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

Parameters:

Name Type Description Default
rule str

The URL rule string.

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

Adds metadata to a single tag.

None
summary str | None

A short summary of what the operation does.

None
description str | None

A verbose explanation of the operation behavior.

None
external_docs ExternalDocumentation | dict[str, Any] | None

Additional external documentation for this operation.

None
operation_id str | None

Unique string used to identify the operation.

None
deprecated bool | None

Declares this operation to be deprecated.

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

A declaration of which security mechanisms can be used for this operation.

None
servers list[Server | dict[str, Any]] | None

An alternative server array to service this operation.

None
openapi_extensions dict[str, Any] | None

Allows extensions to the OpenAPI Schema.

None
responses ResponseDict | None

API responses should be either a subclass of BaseModel, a dictionary, or None.

None
doc_ui bool

Declares this operation to be shown. Default to True.

True
Source code in star_openapi/openapi.py
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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,
    request_body: RequestBody | dict[str, Any] | None = None,
    responses: ResponseDict | None = None,
    doc_ui: bool = True,
):
    """
    Decorator for defining a REST API endpoint with the HTTP PATCH method.
    More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

    Args:
        rule: The URL rule string.
        tags: Adds metadata to a single tag.
        summary: A short summary of what the operation does.
        description: A verbose explanation of the operation behavior.
        external_docs: Additional external documentation for this operation.
        operation_id: Unique string used to identify the operation.
        deprecated: Declares this operation to be deprecated.
        security: A declaration of which security mechanisms can be used for this operation.
        servers: An alternative server array to service this operation.
        openapi_extensions: Allows extensions to the OpenAPI Schema.
        responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
        doc_ui: Declares this operation to be shown. Default to 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,
            request_body=request_body,
            responses=responses,
            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

post(rule, *, name=None, tags=None, summary=None, description=None, external_docs=None, operation_id=None, deprecated=None, security=None, servers=None, openapi_extensions=None, request_body=None, responses=None, doc_ui=True) ⚓︎

Decorator for defining a REST API endpoint with the HTTP POST method. More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

Parameters:

Name Type Description Default
rule str

The URL rule string.

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

Adds metadata to a single tag.

None
summary str | None

A short summary of what the operation does.

None
description str | None

A verbose explanation of the operation behavior.

None
external_docs ExternalDocumentation | dict[str, Any] | None

Additional external documentation for this operation.

None
operation_id str | None

Unique string used to identify the operation.

None
deprecated bool | None

Declares this operation to be deprecated.

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

A declaration of which security mechanisms can be used for this operation.

None
servers list[Server | dict[str, Any]] | None

An alternative server array to service this operation.

None
openapi_extensions dict[str, Any] | None

Allows extensions to the OpenAPI Schema.

None
responses ResponseDict | None

API responses should be either a subclass of BaseModel, a dictionary, or None.

None
doc_ui bool

Declares this operation to be shown. Default to True.

True
Source code in star_openapi/openapi.py
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
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,
    request_body: RequestBody | dict[str, Any] | None = None,
    responses: ResponseDict | None = None,
    doc_ui: bool = True,
):
    """
    Decorator for defining a REST API endpoint with the HTTP POST method.
    More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

    Args:
        rule: The URL rule string.
        tags: Adds metadata to a single tag.
        summary: A short summary of what the operation does.
        description: A verbose explanation of the operation behavior.
        external_docs: Additional external documentation for this operation.
        operation_id: Unique string used to identify the operation.
        deprecated: Declares this operation to be deprecated.
        security: A declaration of which security mechanisms can be used for this operation.
        servers: An alternative server array to service this operation.
        openapi_extensions: Allows extensions to the OpenAPI Schema.
        responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
        doc_ui: Declares this operation to be shown. Default to 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,
            request_body=request_body,
            responses=responses,
            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

put(rule, *, name=None, tags=None, summary=None, description=None, external_docs=None, operation_id=None, deprecated=None, security=None, servers=None, openapi_extensions=None, request_body=None, responses=None, doc_ui=True) ⚓︎

Decorator for defining a REST API endpoint with the HTTP PUT method. More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

Parameters:

Name Type Description Default
rule str

The URL rule string.

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

Adds metadata to a single tag.

None
summary str | None

A short summary of what the operation does.

None
description str | None

A verbose explanation of the operation behavior.

None
external_docs ExternalDocumentation | dict[str, Any] | None

Additional external documentation for this operation.

None
operation_id str | None

Unique string used to identify the operation.

None
deprecated bool | None

Declares this operation to be deprecated.

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

A declaration of which security mechanisms can be used for this operation.

None
servers list[Server | dict[str, Any]] | None

An alternative server array to service this operation.

None
openapi_extensions dict[str, Any] | None

Allows extensions to the OpenAPI Schema.

None
responses ResponseDict | None

API responses should be either a subclass of BaseModel, a dictionary, or None.

None
doc_ui bool

Declares this operation to be shown. Default to True.

True
Source code in star_openapi/openapi.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
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,
    request_body: RequestBody | dict[str, Any] | None = None,
    responses: ResponseDict | None = None,
    doc_ui: bool = True,
):
    """
    Decorator for defining a REST API endpoint with the HTTP PUT method.
    More information goto https://spec.openapis.org/oas/v3.1.0#operation-object

    Args:
        rule: The URL rule string.
        tags: Adds metadata to a single tag.
        summary: A short summary of what the operation does.
        description: A verbose explanation of the operation behavior.
        external_docs: Additional external documentation for this operation.
        operation_id: Unique string used to identify the operation.
        deprecated: Declares this operation to be deprecated.
        security: A declaration of which security mechanisms can be used for this operation.
        servers: An alternative server array to service this operation.
        openapi_extensions: Allows extensions to the OpenAPI Schema.
        responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
        doc_ui: Declares this operation to be shown. Default to 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,
            request_body=request_body,
            responses=responses,
            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

register_api(api) ⚓︎

Register an APIRouter.

Parameters:

Name Type Description Default
api APIRouter

The APIBlueprint instance to register.

required
Source code in star_openapi/openapi.py
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
def register_api(self, api: APIRouter):
    """
    Register an APIRouter.

    Args:
        api: The APIBlueprint instance to register.
    """
    for tag in api.tags:
        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.router.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.router.add_websocket_route(path=path_with_prefix, endpoint=route.endpoint, name=route.name)