OpenAPI docs

Utilities to handle OpenAPI automatic UI documentation, including Swagger UI (by default at /docs) and ReDoc (by default at /redoc).

fastapi.openapi.docs.get_swagger_ui_html

  1. get_swagger_ui_html(
  2. *,
  3. openapi_url,
  4. title,
  5. swagger_js_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js",
  6. swagger_css_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css",
  7. swagger_favicon_url="https://fastapi.tiangolo.com/img/favicon.png",
  8. oauth2_redirect_url=None,
  9. init_oauth=None,
  10. swagger_ui_parameters=None
  11. )

Generate and return the HTML that loads Swagger UI for the interactive API docs (normally served at /docs).

You would only call this function yourself if you needed to override some parts, for example the URLs to use to load Swagger UI’s JavaScript and CSS.

Read more about it in the FastAPI docs for Configure Swagger UI and the FastAPI docs for Custom Docs UI Static Assets (Self-Hosting).

PARAMETERDESCRIPTION
openapi_url

The OpenAPI URL that Swagger UI should load and use.

This is normally done automatically by FastAPI using the default URL /openapi.json.

TYPE: str

title

The HTML <title> content, normally shown in the browser tab.

TYPE: str

swagger_js_url

The URL to use to load the Swagger UI JavaScript.

It is normally set to a CDN URL.

TYPE: str DEFAULT: https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js

swagger_css_url

The URL to use to load the Swagger UI CSS.

It is normally set to a CDN URL.

TYPE: str DEFAULT: https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css

swagger_favicon_url

The URL of the favicon to use. It is normally shown in the browser tab.

TYPE: str DEFAULT: https://fastapi.tiangolo.com/img/favicon.png

oauth2_redirect_url

The OAuth2 redirect URL, it is normally automatically handled by FastAPI.

TYPE: Optional[str] DEFAULT: None

init_oauth

A dictionary with Swagger UI OAuth2 initialization configurations.

TYPE: Optional[Dict[str, Any]] DEFAULT: None

swagger_ui_parameters

Configuration parameters for Swagger UI.

It defaults to swagger_ui_default_parameters.

TYPE: Optional[Dict[str, Any]] DEFAULT: None

Source code in fastapi/openapi/docs.py

  1. 26
  2. 27
  3. 28
  4. 29
  5. 30
  6. 31
  7. 32
  8. 33
  9. 34
  10. 35
  11. 36
  12. 37
  13. 38
  14. 39
  15. 40
  16. 41
  17. 42
  18. 43
  19. 44
  20. 45
  21. 46
  22. 47
  23. 48
  24. 49
  25. 50
  26. 51
  27. 52
  28. 53
  29. 54
  30. 55
  31. 56
  32. 57
  33. 58
  34. 59
  35. 60
  36. 61
  37. 62
  38. 63
  39. 64
  40. 65
  41. 66
  42. 67
  43. 68
  44. 69
  45. 70
  46. 71
  47. 72
  48. 73
  49. 74
  50. 75
  51. 76
  52. 77
  53. 78
  54. 79
  55. 80
  56. 81
  57. 82
  58. 83
  59. 84
  60. 85
  61. 86
  62. 87
  63. 88
  64. 89
  65. 90
  66. 91
  67. 92
  68. 93
  69. 94
  70. 95
  71. 96
  72. 97
  73. 98
  74. 99
  75. 100
  76. 101
  77. 102
  78. 103
  79. 104
  80. 105
  81. 106
  82. 107
  83. 108
  84. 109
  85. 110
  86. 111
  87. 112
  88. 113
  89. 114
  90. 115
  91. 116
  92. 117
  93. 118
  94. 119
  95. 120
  96. 121
  97. 122
  98. 123
  99. 124
  100. 125
  101. 126
  102. 127
  103. 128
  104. 129
  105. 130
  106. 131
  107. 132
  108. 133
  109. 134
  110. 135
  111. 136
  112. 137
  113. 138
  114. 139
  115. 140
  116. 141
  117. 142
  118. 143
  119. 144
  120. 145
  121. 146
  122. 147
  123. 148
  124. 149
  125. 150
  126. 151
  127. 152
  128. 153
  129. 154
  130. 155
  131. 156
  132. 157
  133. 158
  1. def get_swagger_ui_html(
  2. *,
  3. openapi_url: Annotated[
  4. str,
  5. Doc(
  6. “””
  7. The OpenAPI URL that Swagger UI should load and use.
  8. This is normally done automatically by FastAPI using the default URL
  9. /openapi.json.
  10. “””
  11. ),
  12. ],
  13. title: Annotated[
  14. str,
  15. Doc(
  16. “””
  17. The HTML &lt;title&gt; content, normally shown in the browser tab.
  18. “””
  19. ),
  20. ],
  21. swagger_js_url: Annotated[
  22. str,
  23. Doc(
  24. “””
  25. The URL to use to load the Swagger UI JavaScript.
  26. It is normally set to a CDN URL.
  27. “””
  28. ),
  29. ] = https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js,
  30. swagger_css_url: Annotated[
  31. str,
  32. Doc(
  33. “””
  34. The URL to use to load the Swagger UI CSS.
  35. It is normally set to a CDN URL.
  36. “””
  37. ),
  38. ] = https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css,
  39. swagger_favicon_url: Annotated[
  40. str,
  41. Doc(
  42. “””
  43. The URL of the favicon to use. It is normally shown in the browser tab.
  44. “””
  45. ),
  46. ] = https://fastapi.tiangolo.com/img/favicon.png,
  47. oauth2_redirect_url: Annotated[
  48. Optional[str],
  49. Doc(
  50. “””
  51. The OAuth2 redirect URL, it is normally automatically handled by FastAPI.
  52. “””
  53. ),
  54. ] = None,
  55. init_oauth: Annotated[
  56. Optional[Dict[str, Any]],
  57. Doc(
  58. “””
  59. A dictionary with Swagger UI OAuth2 initialization configurations.
  60. “””
  61. ),
  62. ] = None,
  63. swagger_ui_parameters: Annotated[
  64. Optional[Dict[str, Any]],
  65. Doc(
  66. “””
  67. Configuration parameters for Swagger UI.
  68. It defaults to [swagger_ui_default_parameters][fastapi.openapi.docs.swagger_ui_default_parameters].
  69. “””
  70. ),
  71. ] = None,
  72. ) -> HTMLResponse:
  73. “””
  74. Generate and return the HTML that loads Swagger UI for the interactive
  75. API docs (normally served at /docs).
  76. You would only call this function yourself if you needed to override some parts,
  77. for example the URLs to use to load Swagger UIs JavaScript and CSS.
  78. Read more about it in the
  79. FastAPI docs for Configure Swagger UI
  80. and the FastAPI docs for Custom Docs UI Static Assets (Self-Hosting).
  81. “””
  82. current_swagger_ui_parameters = swagger_ui_default_parameters.copy()
  83. if swagger_ui_parameters:
  84. current_swagger_ui_parameters.update(swagger_ui_parameters)
  85. html = f“””
  86. <!DOCTYPE html>
  87. <html>
  88. <head>
  89. <link type=”text/css rel=”stylesheet href=”{swagger_css_url}“>
  90. <link rel=”shortcut icon href=”{swagger_favicon_url}“>
  91. <title>{title}</title>
  92. </head>
  93. <body>
  94. <div id=”swagger-ui”>
  95. </div>
  96. <script src=”{swagger_js_url}“></script>
  97. <!— SwaggerUIBundle is now available on the page —>
  98. <script>
  99. const ui = SwaggerUIBundle({{
  100. url: {openapi_url}‘,
  101. “””
  102. for key, value in current_swagger_ui_parameters.items():
  103. html += f{json.dumps(key)}: {json.dumps(jsonable_encoder(value))},\n
  104. if oauth2_redirect_url:
  105. html += foauth2RedirectUrl: window.location.origin + {oauth2_redirect_url}‘,”
  106. html += “””
  107. presets: [
  108. SwaggerUIBundle.presets.apis,
  109. SwaggerUIBundle.SwaggerUIStandalonePreset
  110. ],
  111. })”””
  112. if init_oauth:
  113. html += f“””
  114. ui.initOAuth({json.dumps(jsonable_encoder(init_oauth))})
  115. “””
  116. html += “””
  117. </script>
  118. </body>
  119. </html>
  120. “””
  121. return HTMLResponse(html)

fastapi.openapi.docs.get_redoc_html

  1. get_redoc_html(
  2. *,
  3. openapi_url,
  4. title,
  5. redoc_js_url="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js",
  6. redoc_favicon_url="https://fastapi.tiangolo.com/img/favicon.png",
  7. with_google_fonts=True
  8. )

Generate and return the HTML response that loads ReDoc for the alternative API docs (normally served at /redoc).

You would only call this function yourself if you needed to override some parts, for example the URLs to use to load ReDoc’s JavaScript and CSS.

Read more about it in the FastAPI docs for Custom Docs UI Static Assets (Self-Hosting).

PARAMETERDESCRIPTION
openapi_url

The OpenAPI URL that ReDoc should load and use.

This is normally done automatically by FastAPI using the default URL /openapi.json.

TYPE: str

title

The HTML <title> content, normally shown in the browser tab.

TYPE: str

redoc_js_url

The URL to use to load the ReDoc JavaScript.

It is normally set to a CDN URL.

TYPE: str DEFAULT: https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js

redoc_favicon_url

The URL of the favicon to use. It is normally shown in the browser tab.

TYPE: str DEFAULT: https://fastapi.tiangolo.com/img/favicon.png

with_google_fonts

Load and use Google Fonts.

TYPE: bool DEFAULT: True

Source code in fastapi/openapi/docs.py

  1. 161
  2. 162
  3. 163
  4. 164
  5. 165
  6. 166
  7. 167
  8. 168
  9. 169
  10. 170
  11. 171
  12. 172
  13. 173
  14. 174
  15. 175
  16. 176
  17. 177
  18. 178
  19. 179
  20. 180
  21. 181
  22. 182
  23. 183
  24. 184
  25. 185
  26. 186
  27. 187
  28. 188
  29. 189
  30. 190
  31. 191
  32. 192
  33. 193
  34. 194
  35. 195
  36. 196
  37. 197
  38. 198
  39. 199
  40. 200
  41. 201
  42. 202
  43. 203
  44. 204
  45. 205
  46. 206
  47. 207
  48. 208
  49. 209
  50. 210
  51. 211
  52. 212
  53. 213
  54. 214
  55. 215
  56. 216
  57. 217
  58. 218
  59. 219
  60. 220
  61. 221
  62. 222
  63. 223
  64. 224
  65. 225
  66. 226
  67. 227
  68. 228
  69. 229
  70. 230
  71. 231
  72. 232
  73. 233
  74. 234
  75. 235
  76. 236
  77. 237
  78. 238
  79. 239
  80. 240
  81. 241
  82. 242
  83. 243
  84. 244
  85. 245
  86. 246
  87. 247
  88. 248
  89. 249
  90. 250
  91. 251
  92. 252
  93. 253
  1. def get_redoc_html(
  2. *,
  3. openapi_url: Annotated[
  4. str,
  5. Doc(
  6. “””
  7. The OpenAPI URL that ReDoc should load and use.
  8. This is normally done automatically by FastAPI using the default URL
  9. /openapi.json.
  10. “””
  11. ),
  12. ],
  13. title: Annotated[
  14. str,
  15. Doc(
  16. “””
  17. The HTML &lt;title&gt; content, normally shown in the browser tab.
  18. “””
  19. ),
  20. ],
  21. redoc_js_url: Annotated[
  22. str,
  23. Doc(
  24. “””
  25. The URL to use to load the ReDoc JavaScript.
  26. It is normally set to a CDN URL.
  27. “””
  28. ),
  29. ] = https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js,
  30. redoc_favicon_url: Annotated[
  31. str,
  32. Doc(
  33. “””
  34. The URL of the favicon to use. It is normally shown in the browser tab.
  35. “””
  36. ),
  37. ] = https://fastapi.tiangolo.com/img/favicon.png,
  38. with_google_fonts: Annotated[
  39. bool,
  40. Doc(
  41. “””
  42. Load and use Google Fonts.
  43. “””
  44. ),
  45. ] = True,
  46. ) -> HTMLResponse:
  47. “””
  48. Generate and return the HTML response that loads ReDoc for the alternative
  49. API docs (normally served at /redoc).
  50. You would only call this function yourself if you needed to override some parts,
  51. for example the URLs to use to load ReDocs JavaScript and CSS.
  52. Read more about it in the
  53. FastAPI docs for Custom Docs UI Static Assets (Self-Hosting).
  54. “””
  55. html = f“””
  56. <!DOCTYPE html>
  57. <html>
  58. <head>
  59. <title>{title}</title>
  60. <!— needed for adaptive design —>
  61. <meta charset=”utf-8”/>
  62. <meta name=”viewport content=”width=device-width, initial-scale=1”>
  63. “””
  64. if with_google_fonts:
  65. html += “””
  66. <link href=”https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700“ rel=”stylesheet”>
  67. “””
  68. html += f“””
  69. <link rel=”shortcut icon href=”{redoc_favicon_url}“>
  70. <!—
  71. ReDoc doesnt change outer page styles
  72. —>
  73. <style>
  74. body {{
  75. margin: 0;
  76. padding: 0;
  77. }}
  78. </style>
  79. </head>
  80. <body>
  81. <noscript>
  82. ReDoc requires Javascript to function. Please enable it to browse the documentation.
  83. </noscript>
  84. <redoc spec-url=”{openapi_url}“></redoc>
  85. <script src=”{redoc_js_url}“> </script>
  86. </body>
  87. </html>
  88. “””
  89. return HTMLResponse(html)

fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html

  1. get_swagger_ui_oauth2_redirect_html()

Generate the HTML response with the OAuth2 redirection for Swagger UI.

You normally don’t need to use or change this.

Source code in fastapi/openapi/docs.py

  1. 256
  2. 257
  3. 258
  4. 259
  5. 260
  6. 261
  7. 262
  8. 263
  9. 264
  10. 265
  11. 266
  12. 267
  13. 268
  14. 269
  15. 270
  16. 271
  17. 272
  18. 273
  19. 274
  20. 275
  21. 276
  22. 277
  23. 278
  24. 279
  25. 280
  26. 281
  27. 282
  28. 283
  29. 284
  30. 285
  31. 286
  32. 287
  33. 288
  34. 289
  35. 290
  36. 291
  37. 292
  38. 293
  39. 294
  40. 295
  41. 296
  42. 297
  43. 298
  44. 299
  45. 300
  46. 301
  47. 302
  48. 303
  49. 304
  50. 305
  51. 306
  52. 307
  53. 308
  54. 309
  55. 310
  56. 311
  57. 312
  58. 313
  59. 314
  60. 315
  61. 316
  62. 317
  63. 318
  64. 319
  65. 320
  66. 321
  67. 322
  68. 323
  69. 324
  70. 325
  71. 326
  72. 327
  73. 328
  74. 329
  75. 330
  76. 331
  77. 332
  78. 333
  79. 334
  80. 335
  81. 336
  82. 337
  83. 338
  84. 339
  85. 340
  86. 341
  87. 342
  88. 343
  89. 344
  1. def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse:
  2. “””
  3. Generate the HTML response with the OAuth2 redirection for Swagger UI.
  4. You normally dont need to use or change this.
  5. “””
  6. # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html
  7. html = “””
  8. <!doctype html>
  9. <html lang=”en-US”>
  10. <head>
  11. <title>Swagger UI: OAuth2 Redirect</title>
  12. </head>
  13. <body>
  14. <script>
  15. use strict’;
  16. function run () {
  17. var oauth2 = window.opener.swaggerUIRedirectOauth2;
  18. var sentState = oauth2.state;
  19. var redirectUrl = oauth2.redirectUrl;
  20. var isValid, qp, arr;
  21. if (/code|token|error/.test(window.location.hash)) {
  22. qp = window.location.hash.substring(1).replace(‘?’, ‘&’);
  23. } else {
  24. qp = location.search.substring(1);
  25. }
  26. arr = qp.split(“&”);
  27. arr.forEach(function (v,i,_arr) { _arr[i] = ‘“‘ + v.replace(‘=’, ‘“:”‘) + ‘“‘;});
  28. qp = qp ? JSON.parse(‘{‘ + arr.join() + ‘}’,
  29. function (key, value) {
  30. return key === “” ? value : decodeURIComponent(value);
  31. }
  32. ) : {};
  33. isValid = qp.state === sentState;
  34. if ((
  35. oauth2.auth.schema.get(“flow”) === accessCode ||
  36. oauth2.auth.schema.get(“flow”) === authorizationCode ||
  37. oauth2.auth.schema.get(“flow”) === authorization_code
  38. ) && !oauth2.auth.code) {
  39. if (!isValid) {
  40. oauth2.errCb({
  41. authId: oauth2.auth.name,
  42. source: auth”,
  43. level: warning”,
  44. message: Authorization may be unsafe, passed state was changed in server. The passed state wasnt returned from auth server.”
  45. });
  46. }
  47. if (qp.code) {
  48. delete oauth2.state;
  49. oauth2.auth.code = qp.code;
  50. oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
  51. } else {
  52. let oauthErrorMsg;
  53. if (qp.error) {
  54. oauthErrorMsg = “[“+qp.error+”]: +
  55. (qp.error_description ? qp.error_description+ “. : no accessCode received from the server. “) +
  56. (qp.error_uri ? More info: “+qp.error_uri : “”);
  57. }
  58. oauth2.errCb({
  59. authId: oauth2.auth.name,
  60. source: auth”,
  61. level: error”,
  62. message: oauthErrorMsg || “[Authorization failed]: no accessCode received from the server.”
  63. });
  64. }
  65. } else {
  66. oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
  67. }
  68. window.close();
  69. }
  70. if (document.readyState !== loading’) {
  71. run();
  72. } else {
  73. document.addEventListener(‘DOMContentLoaded’, function () {
  74. run();
  75. });
  76. }
  77. </script>
  78. </body>
  79. </html>
  80. “””
  81. return HTMLResponse(content=html)

fastapi.openapi.docs.swagger_ui_default_parameters module-attribute

  1. swagger_ui_default_parameters = {
  2. "dom_id": "#swagger-ui",
  3. "layout": "BaseLayout",
  4. "deepLinking": True,
  5. "showExtensions": True,
  6. "showCommonExtensions": True,
  7. }

Default configurations for Swagger UI.

You can use it as a template to add any other configurations needed.