API Reference¶
Classes¶
- class SwaggerDocs(app: Application, *, validate: bool = True, info: SwaggerInfo | None = None, request_key: str = 'data', title: str | None = None, version: str | None = None, description: str | None = None, components: str | None = None, security: str | None = None, swagger_ui_settings: SwaggerUiSettings | None = None, redoc_ui_settings: ReDocUiSettings | None = None, rapidoc_ui_settings: RapiDocUiSettings | None = None)¶
This class should be used if you want to use documentation through handler doctrings.
- Parameters:
app (aiohttp.web.Application) – aiohttp’s Application instance
validate (bool) – if
False
, request validation is disabled, defaultTrue
info – class:SwaggerInfo
request_key (str) – key name under which the data will be stored in
request
after validation, defaultdata
components (str) – path to file with components definitions (optional)
security (str) – path to file with security definition (optional)
swagger_ui_settings – class:SwaggerUiSettings (optional)
redoc_ui_settings – class:ReDocUiSettings (optional)
rapidoc_ui_settings – class:RapiDocUiSettings (optional)
- register_media_type_handler(media_type: str, handler: Callable[[Request], Awaitable[Tuple[Any, bool]]]) None ¶
This method allows registering custom handler for a media type
Please, see example
Warning
register_media_type_handler must be called before adding route with media type
✘
swagger = SwaggerDocs(app) swagger.add_post("/r", handler) swagger.register_media_type_handler("custom/handler", custom_handler)
✔
swagger = SwaggerDocs(app) swagger.register_media_type_handler("custom/handler", custom_handler) swagger.add_post("/r", handler)
- Parameters:
media_type (str) – The name of custom string format
handler – The handler function that will be executed for the media type
- register_string_format_validator(string_format: str, validator: Callable[[str], None]) None ¶
This method allows registering a custom validator for string format
Please, see example
- Parameters:
string_format (str) – The name of custom string format
validator – The validator function that should be used for validating passed string format
- class SwaggerFile(app: Application, spec_file: str = '', *, validate: bool = True, request_key: str = 'data', swagger_ui_settings: SwaggerUiSettings | None = None, redoc_ui_settings: ReDocUiSettings | None = None, rapidoc_ui_settings: RapiDocUiSettings | None = None)¶
This class should be used if you want to use swagger scheme.
- Parameters:
app (aiohttp.web.Application) – aiohttp’s Application instance
spec_file (str) – path to swagger file scheme
validate (bool) – if
False
, request validation is disabled, defaultTrue
request_key (str) – key name under which the data will be stored in
request
after validation, defaultdata
swagger_ui_settings – class:SwaggerUiSettings (optional)
redoc_ui_settings – class:ReDocUiSettings (optional)
rapidoc_ui_settings – class:RapiDocUiSettings (optional)
- register_media_type_handler(media_type: str, handler: Callable[[Request], Awaitable[Tuple[Any, bool]]]) None ¶
This method allows registering custom handler for a media type
Please, see example
Warning
register_media_type_handler must be called before adding route with media type
✘
swagger = SwaggerDocs(app) swagger.add_post("/r", handler) swagger.register_media_type_handler("custom/handler", custom_handler)
✔
swagger = SwaggerDocs(app) swagger.register_media_type_handler("custom/handler", custom_handler) swagger.add_post("/r", handler)
- Parameters:
media_type (str) – The name of custom string format
handler – The handler function that will be executed for the media type
- register_string_format_validator(string_format: str, validator: Callable[[str], None]) None ¶
This method allows registering a custom validator for string format
Please, see example
- Parameters:
string_format (str) – The name of custom string format
validator – The validator function that should be used for validating passed string format
Settings¶
- class SwaggerInfo(*, title: str, version: str, description: str | None = None, terms_of_service: str | None = None, contact: SwaggerContact | None = None, license: SwaggerLicense | None = None)¶
Decorators¶
- swagger_doc(path: str) Callable ¶
This decorator can be used if you don’t want to include the whole schema into docstring, so it can be placed in the YAML file and provide the path to the file, see docs_decorator_and_docstrings example
- Parameters:
path (str) – path to swagger route schema
UI backends¶
- class SwaggerUiSettings(*, path: str, layout: str = 'StandaloneLayout', deepLinking: bool = True, displayOperationId: bool = False, defaultModelsExpandDepth: int = 1, defaultModelExpandDepth: int = 1, defaultModelRendering: str = 'example', displayRequestDuration: bool = False, docExpansion: str = 'list', filter: bool = False, showExtensions: bool = False, showCommonExtensions: bool = False, supportedSubmitMethods: List[str] = _Nothing.NOTHING, validatorUrl: str | None = 'https://validator.swagger.io/validator', withCredentials: bool = False)¶
Settings for Swagger UI, see: configuration
- Parameters:
layout (str) – The name of a component available via the plugin system to use as the top-level layout for Swagger UI. It must be either
BaseLayout
orStandaloneLayout
. DefaultStandaloneLayout
.deepLinking (bool) – If set to
True
, enables deep linking for tags and operations. See the Deep Linking documentation for more information. DefaultTrue
.displayOperationId (bool) – Controls the display of operationId in operations list. Default
False
.defaultModelsExpandDepth (int) – The default expansion depth for models (set to
-1
completely hide the models). Default1
.defaultModelExpandDepth (int) – The default expansion depth for the model on the model-example section. Default
1
.defaultModelRendering (int) – Controls how the model is shown when the API is first rendered. It must be either
example
ormodel
. Defaultexample
.displayRequestDuration (bool) – Controls the display of the request duration (in milliseconds) for “Try it out” requests. Default
False
.docExpansion (str) – Controls the default expansion setting for the operations and tags. It can be
list
(expands only the tags),full
(expands the tags and operations) ornone
(expands nothing). Defaultlist
.filter (bool) – If set, enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown. Default
False
.showExtensions (bool) – Controls the display of vendor extension (x-) fields and values for Operations, Parameters, and Schema. Default
False
.showCommonExtensions (bool) – Controls the display of extensions (pattern, maxLength, minLength, maximum, minimum) fields and values for Parameters. Default
False
.supportedSubmitMethods (list) – List of HTTP methods that have the “Try it out” feature enabled. An empty array disables “Try it out” for all operations. This does not filter the operations from the display. Available methods:
get
,put
,post
,delete
,options
,head
,patch
,trace
. By default all methods are enabled.validatorUrl (str) – By default, Swagger UI attempts to validate specs against swagger.io’s online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators (Validator Badge). Setting it to
None
will disable validation. Defaulthttps://validator.swagger.io/validator
.withCredentials (bool) – If set to
True
, enables passing credentials, as defined in the Fetch standard, in CORS requests that are sent by the browser. Note that Swagger UI cannot currently set cookies cross-domain (see swagger-js#1163) - as a result, you will have to rely on browser-supplied cookies (which this setting enables sending) that Swagger UI cannot control. DefaultFalse
.
- class ReDocUiSettings(*, path: str, disableSearch: bool = False, expandDefaultServerVariables: bool = False, expandResponses: str = '', maxDisplayedEnumValues: int = 2, hideDownloadButton: bool = False, hideHostname: bool = False, hideLoading: bool = False, hideSingleRequestSampleTab: bool = False, expandSingleSchemaField: bool = False, jsonSampleExpandLevel: int | str = 2, hideSchemaTitles: bool = False, simpleOneOfTypeLabel: bool = False, menuToggle: bool = True, nativeScrollbars: bool = False, noAutoAuth: bool = False, onlyRequiredInSamples: bool = False, pathInMiddlePanel: bool = False, requiredPropsFirst: bool = False, scrollYOffset: int = 0, showExtensions: bool = False, sortPropsAlphabetically: bool = False, sortEnumValuesAlphabetically: bool = False, suppressWarnings: bool = False, payloadSampleIdx: int = 0, untrustedSpec: bool = False)¶
Settings for ReDoc UI, see: ReDoc options
- Parameters:
disableSearch (bool) – Disable search indexing and search box. Default
False
.expandDefaultServerVariables (bool) – Enable expanding default server variables. Default
False
.expandResponses (str) – Specify which responses to expand by default by response codes. Values should be passed as comma-separated list without spaces e.g.
200,201
. Special valueall
expands all responses by default. Be careful: this option can slow-down documentation rendering time. Default is empty string.maxDisplayedEnumValues (int) – Display only specified number of enum values. Hide rest values under spoiler. Default
2
.hideDownloadButton (bool) – Do not show “Download” spec button. THIS DOESN’T MAKE YOUR SPEC PRIVATE, it just hides the button. Default
False
.hideHostname (bool) – If set, the protocol and hostname is not shown in the operation definition. Default
False
.hideLoading (bool) – Do not show loading animation. Useful for small docs. Default
False
.hideSingleRequestSampleTab (bool) – Do not show the request sample tab for requests with only one sample. Default
False
.expandSingleSchemaField (bool) – Automatically expand single field in a schema. Default
False
.jsonSampleExpandLevel (int,str) – Set the default expand level for JSON payload samples (responses and request body). Special value
all
expands all levels. Default2
.hideSchemaTitles (bool) – Do not display schema
title
next to to the type. DefaultFalse
.simpleOneOfTypeLabel (bool) – Show only unique oneOf types in the label without titles. Default
False
.menuToggle (bool) – If
True
clicking second time on expanded menu item will collapse it. DefaultTrue
.nativeScrollbars (bool) – Use native scrollbar for sidemenu instead of perfect-scroll (scrolling performance optimization for big specs). Default
False
.noAutoAuth (bool) – Do not inject Authentication section automatically. Default
False
.onlyRequiredInSamples (bool) – Shows only required fields in request samples. Default
False
.pathInMiddlePanel (bool) – Show path link and HTTP verb in the middle panel instead of the right one. Default
False
.requiredPropsFirst (bool) – Show required properties first ordered in the same order as in
required
array. DefaultFalse
.scrollYOffset (int) – If set, specifies a vertical scroll-offset. This is often useful when there are fixed positioned elements at the top of the page, such as navbars, headers, etc. Default
0
.showExtensions (bool) – Show vendor extensions (“x-” fields). Extensions used by ReDoc are ignored. Default
False
.sortPropsAlphabetically (bool) – Sort properties alphabetically. Default
False
.sortEnumValuesAlphabetically (bool) – Sort enum values alphabetically. Default
False
.suppressWarnings (bool) – If set, warnings are not rendered at the top of documentation (they still are logged to the console). Default
False
.payloadSampleIdx (int) – If set, payload sample will be inserted at this index or last. Indexes start from 0. Default
0
.untrustedSpec (bool) – If set, the spec is considered untrusted and all HTML/markdown is sanitized to prevent XSS. Disabled by default for performance reasons. Enable this option if you work with untrusted user data! Default
False
.
- class RapiDocUiSettings(*, path: str, sort_tags: bool = False, sort_endpoints_by: str = 'path', heading_text: str | None = None, theme: str = 'light', bg_color: str = _Nothing.NOTHING, text_color: str = _Nothing.NOTHING, header_color: str = '#444444', primary_color: str = '#FF791A', font_size: str = 'default', use_path_in_nav_bar: bool = False, nav_bg_color: str | None = None, nav_text_color: str | None = None, nav_hover_bg_color: str | None = None, nav_hover_text_color: str | None = None, nav_accent_color: str | None = None, layout: str = 'row', render_style: str = 'view', schema_style: str = 'tree', schema_expand_level: int = 999, schema_description_expanded: bool = False, default_schema_tab: str = 'model', show_info: bool = True, show_components: bool = False, show_header: bool = True, allow_authentication: bool = True, allow_spec_url_load: bool = True, allow_spec_file_load: bool = True, allow_search: bool = True, allow_try: bool = True, allow_server_selection: bool = True, api_key_name: str = 'Authorization', api_key_value: str | None = None, api_key_location: str = 'header', server_url: str | None = None, default_api_server: str | None = None)¶
Settings for RapiDoc UI, see: RapiDoc API
- Parameters:
sort_tags (bool) – List APIs sorted by tags. Default
False
.sort_endpoints_by (str) – Sort endpoints within each tags by
path
ormethod
. Defaultpath
.heading_text (str) – Heading Text on top-left corner. (Optional)
theme (str) – Is the base theme, which is used for calculating colors for various UI components.
theme
,bg-color
andtext-color
are the base attributes for generating a custom theme. It can be eitherlight
ordark
. Defaultlight
.bg_color (str) – Hex color code for main background. Default
#fff
iftheme
islight
,#333
otherwise.text_color (str) – Hex color code for text. Default
#444
iftheme
islight
,#bbb
otherwise.header_color (str) – Hex color code for the header’s background. Default
#444444
.primary_color (str) – Hex color code on various controls such as buttons, tabs. Default
#FF791A
.font_size (str) – Controls the relative font-sizing for the entire document. Values are
default
,large
andlargest
.use_path_in_nav_bar (bool) – Show API paths in the navigation bar instead of summary/description. Default
False
.nav_bg_color (str) – Navigation bar’s background color. (optional)
nav_text_color (str) – Navigation bar’s Text color. (optional)
nav_hover_bg_color (str) – Background color of the navigation item on mouse-over. (optional)
nav_hover_text_color (str) – Text color of the navigation item on mouse-over. (optional)
nav_accent_color (str) – Current selected item indicator. (optional)
layout (str) – Layout helps in placement of request/response sections. In
column
layout, request & response sections are placed one below the other, Inrow
layout they are placed side by side. This attribute is applicable only when the device width is more than 768px and the render-style isview
. Defaultrow
.render_style (str) – Determines display of api-docs. Currently there are three modes supported.
read
- more suitable for reading,view
more friendly for quick exploring andfocused
show one operation at a time. Defaultview
.schema_style (str) – Two different ways to display object-schemas in the responses and request bodies. It must be either
tree
ortable
. Defaulttree
.schema_expand_level (int) – Schema’s are expanded by default, use this attribute to control how many levels in the schema should be expanded. Default
999
.schema_description_expanded (bool) – Constraint and descriptions information of fields in the schema are collapsed to show only the first line. Set it to
True
if you want them to fully expanded. DefaultFalse
.default_schema_tab (str) – The schemas are displayed in two tabs -
model
andexample
. This option allows you to pick the default tab that you would like to be active. Defaultmodel
.show_info (bool) – Show/hide the documents info section. Default
True
.show_components (bool) – Show/hide the components section both in document and menu. Default
False
.show_header (bool) – Show/hide the header. If you dont want your user to open any other api spec, other than the current one, then set this attribute to
False
. DefaultTrue
.allow_authentication (bool) – Authentication feature, allows the user to select one of the authentication mechanism that’s available in the spec. Default
True
.allow_spec_url_load (bool) – If set to
False
, user will not be able to load any spec url from the UI. DefaultTrue
.allow_spec_file_load (bool) – If set to
False
, user will not be able to load any spec file from the local drive. This attribute is applicable only when the device width is more than 768px, else this feature is not available. DefaultTrue
.allow_search (bool) – If set to
False
, user will not be able to search APIs. DefaultTrue
.allow_try (bool) – ‘TRY’ feature allows you to make REST calls to the API server. To disable this feature set it to
False
. DefaultTrue
.allow_server_selection (bool) – If set to
False
, user will not be able to select API server. The URL specified in the server-url attribute will be used if set, else the first server in the API specification file will be used. DefaultTrue
.api_key_name (str) – Name of the API key that will be send while trying out the APIs. Default
Authorization
.api_key_value (str) – Value of the API key that will be send while trying out the APIs. This can also be provided/overwritten from UI. (optional)
api_key_location (str) – Determines how you want to send the api-key. It must be either
header
orquery
. Defaultheader
.server_url (str) – OpenAPI spec has a provision for providing the server url. (optional)
default_api_server (str) – If you have multiple api-server listed in the spec, use this attribute to select the default API server, where all the API calls will goto. This can be changed later from the UI. (optional)
Exceptions¶
- class RequestValidationFailed(errors: Dict, **kwargs: Any)¶
This exception can be caught in a aiohttp middleware.
- Parameters:
errors (dict) – This dict stores validation errors.