|
| 1 | +Customising the OpenAPI schema |
| 2 | +============================== |
| 3 | + |
| 4 | +The generation of the OpenAPI schema by Quart-Schema can be customised |
| 5 | +by changing the :attr:`QuartSchema.openapi_provider_class`. For |
| 6 | +example to only include routes within a specific blueprint named |
| 7 | +``bp``, |
| 8 | + |
| 9 | +.. code-block:: python |
| 10 | +
|
| 11 | + from quart_schema import OpenAPIProvider, QuartSchema |
| 12 | +
|
| 13 | + class BlueprintOnlyOpenAPIProvider(OpenAPIProvider): |
| 14 | + def __init__(self, blueprint_name: str, app: Quart, extension: QuartSchema) -> None: |
| 15 | + super().__init__(app, extension) |
| 16 | + self._blueprint_prefix = f"{blueprint_name}." |
| 17 | +
|
| 18 | + def generate_rules(self) -> Iterable[Rule]: |
| 19 | + for rule in self._app.url_map.iter_rules(): |
| 20 | + hidden = getattr( |
| 21 | + self._app.view_functions[rule.endpoint], QUART_SCHEMA_HIDDEN_ATTRIBUTE, False |
| 22 | + ) |
| 23 | + if rule.endpoint.beginswith(self._blueprint_prefix) and not hidden and not rule.websocket: |
| 24 | + yield rule |
| 25 | +
|
| 26 | + quart_schema = QuartSchema(app, openapi_provider_class=CustomerOpenAPIProvider) |
| 27 | +
|
| 28 | +
|
| 29 | +It is also possible to alter how the operation ID is generated, |
| 30 | + |
| 31 | +.. code-block:: python |
| 32 | +
|
| 33 | + from quart_schema import OpenAPIProvider, QuartSchema |
| 34 | +
|
| 35 | + class CustomOperationIdOpenAPIProvider(OpenAPIProvider): |
| 36 | + def operation_id(self, method: str, func: Callable) -> Optional[str]: |
| 37 | + return func.__name__ |
| 38 | +
|
| 39 | + quart_schema = QuartSchema(app, openapi_provider_class=CustomerOpenAPIProvider) |
| 40 | +
|
| 41 | +There are many more aspects that can be customised, see the |
| 42 | +:class:`OpenAPIProvider` for options. |
| 43 | + |
| 44 | +Custom routes |
| 45 | +------------- |
| 46 | + |
| 47 | +It is also possible to combine the above into a custom route, |
| 48 | + |
| 49 | +.. code-block:: python |
| 50 | +
|
| 51 | + @blueprint.get("/custom.json") |
| 52 | + async def custom_openapi(): |
| 53 | + schema = BlueprintOnlyOpenAPIProvider(blueprint.name, current_app, quart_schema).schema() |
| 54 | + return current_app.json.response(schema) |
| 55 | +
|
| 56 | +Please note this assumes the blueprint is not nested as the name will |
| 57 | +be prefixed with the parents blueprint's names. |
0 commit comments