カスタムDocs UI静的アセット(セルフホスティング)¶
APIドキュメントはSwagger UIとReDocを使用しており、それぞれJavaScriptとCSSファイルが必要です。
デフォルトでは、これらのファイルはCDNから提供されます。
しかし、これをカスタマイズすることも可能で、特定のCDNを設定したり、ファイルを自分で提供したりできます。
JavaScriptとCSS用のカスタムCDN¶
例えば、https://unpkg.com/のような別のCDNを使用したいとしましょう。
これは、例えば特定のURLが制限されている国に住んでいる場合に役立ちます。
自動ドキュメントを無効にする¶
最初のステップは、自動ドキュメントを無効にすることです。デフォルトでは、これらはデフォルトのCDNを使用しているためです。
無効にするには、FastAPIアプリを作成するときに、それらのURLをNoneに設定します。
from fastapi import FastAPI
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
app = FastAPI(docs_url=None, redoc_url=None)
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js",
swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css",
)
@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
return get_swagger_ui_oauth2_redirect_html()
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
return get_redoc_html(
openapi_url=app.openapi_url,
title=app.title + " - ReDoc",
redoc_js_url="https://unpkg.com/redoc@2/bundles/redoc.standalone.js",
)
@app.get("/users/{username}")
async def read_user(username: str):
return {"message": f"Hello {username}"}
カスタムドキュメントを含める¶
これで、カスタムドキュメント用のパス操作を作成できます。
FastAPIの内部関数を再利用してドキュメントのHTMLページを作成し、必要な引数を渡すことができます。
openapi_url: ドキュメントのHTMLページがAPIのOpenAPIスキーマを取得できるURLです。ここではapp.openapi_url属性を使用できます。title: APIのタイトルです。oauth2_redirect_url: デフォルトを使用するには、ここでapp.swagger_ui_oauth2_redirect_urlを使用できます。swagger_js_url: Swagger UIドキュメントのHTMLがJavaScriptファイルを取得できるURLです。これはカスタムCDNのURLです。swagger_css_url: Swagger UIドキュメントのHTMLがCSSファイルを取得できるURLです。これはカスタムCDNのURLです。
ReDocについても同様です...
from fastapi import FastAPI
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
app = FastAPI(docs_url=None, redoc_url=None)
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js",
swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css",
)
@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
return get_swagger_ui_oauth2_redirect_html()
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
return get_redoc_html(
openapi_url=app.openapi_url,
title=app.title + " - ReDoc",
redoc_js_url="https://unpkg.com/redoc@2/bundles/redoc.standalone.js",
)
@app.get("/users/{username}")
async def read_user(username: str):
return {"message": f"Hello {username}"}
ヒント
swagger_ui_redirectのパス操作は、OAuth2を使用する場合のヘルパーです。
APIをOAuth2プロバイダーと統合すると、取得した資格情報で認証してAPIドキュメントに戻ることができます。そして、実際のOAuth2認証を使用してAPIとやり取りできます。
Swagger UIが舞台裏で処理しますが、この「リダイレクト」ヘルパーが必要です。
テスト用のパス操作を作成する¶
すべてが機能することを確認するために、パス操作を作成します。
from fastapi import FastAPI
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
app = FastAPI(docs_url=None, redoc_url=None)
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js",
swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css",
)
@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
return get_swagger_ui_oauth2_redirect_html()
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
return get_redoc_html(
openapi_url=app.openapi_url,
title=app.title + " - ReDoc",
redoc_js_url="https://unpkg.com/redoc@2/bundles/redoc.standalone.js",
)
@app.get("/users/{username}")
async def read_user(username: str):
return {"message": f"Hello {username}"}
テストする¶
これで、http://127.0.0.1:8000/docsでドキュメントにアクセスし、ページをリロードすると、新しいCDNからアセットがロードされるはずです。
ドキュメント用のJavaScriptとCSSのセルフホスティング¶
JavaScriptとCSSをセルフホスティングすることは、例えば、オフライン時、インターネットアクセスなし、またはローカルネットワークでアプリが動作し続ける必要がある場合に役立ちます。
ここでは、これらのファイルを同じFastAPIアプリ内で自分で提供し、ドキュメントがそれらを使用するように設定する方法を説明します。
プロジェクトのファイル構造¶
プロジェクトのファイル構造が以下のようになっているとしましょう。
.
├── app
│ ├── __init__.py
│ ├── main.py
次に、それらの静的ファイルを保存するディレクトリを作成します。
新しいファイル構造は次のようになるかもしれません。
.
├── app
│ ├── __init__.py
│ ├── main.py
└── static/
ファイルをダウンロードする¶
ドキュメントに必要な静的ファイルをダウンロードし、そのstatic/ディレクトリに配置します。
各リンクを右クリックして、「名前を付けてリンクを保存...」のようなオプションを選択するとよいでしょう。
Swagger UIは以下のファイルを使用します。
そしてReDocは以下のファイルを使用します。
その後、ファイル構造は次のようになるかもしれません。
.
├── app
│ ├── __init__.py
│ ├── main.py
└── static
├── redoc.standalone.js
├── swagger-ui-bundle.js
└── swagger-ui.css
静的ファイルを提供する¶
StaticFilesをインポートします。- 特定のパスに
StaticFiles()インスタンスを「マウント」します。
from fastapi import FastAPI
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
from fastapi.staticfiles import StaticFiles
app = FastAPI(docs_url=None, redoc_url=None)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
swagger_js_url="/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css",
)
@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
return get_swagger_ui_oauth2_redirect_html()
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
return get_redoc_html(
openapi_url=app.openapi_url,
title=app.title + " - ReDoc",
redoc_js_url="/static/redoc.standalone.js",
)
@app.get("/users/{username}")
async def read_user(username: str):
return {"message": f"Hello {username}"}
静的ファイルをテストする¶
アプリケーションを起動し、http://127.0.0.1:8000/static/redoc.standalone.jsにアクセスします。
ReDocの非常に長いJavaScriptファイルが表示されるはずです。
次のような内容で始まるかもしれません。
/*! For license information please see redoc.standalone.js.LICENSE.txt */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
...
これは、アプリから静的ファイルを提供できること、そしてドキュメント用の静的ファイルを正しい場所に配置したことを確認します。
これで、ドキュメントにこれらの静的ファイルを使用するようにアプリを設定できます。
静的ファイル用の自動ドキュメントを無効にする¶
カスタムCDNを使用した場合と同様に、最初のステップは自動ドキュメントを無効にすることです。これらはデフォルトでCDNを使用しているためです。
無効にするには、FastAPIアプリを作成するときに、それらのURLをNoneに設定します。
from fastapi import FastAPI
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
from fastapi.staticfiles import StaticFiles
app = FastAPI(docs_url=None, redoc_url=None)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
swagger_js_url="/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css",
)
@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
return get_swagger_ui_oauth2_redirect_html()
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
return get_redoc_html(
openapi_url=app.openapi_url,
title=app.title + " - ReDoc",
redoc_js_url="/static/redoc.standalone.js",
)
@app.get("/users/{username}")
async def read_user(username: str):
return {"message": f"Hello {username}"}
静的ファイル用のカスタムドキュメントを含める¶
カスタムCDNを使用した場合と同様に、カスタムドキュメント用のパス操作を作成できます。
繰り返しになりますが、FastAPIの内部関数を再利用してドキュメントのHTMLページを作成し、必要な引数を渡すことができます。
openapi_url: ドキュメントのHTMLページがAPIのOpenAPIスキーマを取得できるURLです。ここではapp.openapi_url属性を使用できます。title: APIのタイトルです。oauth2_redirect_url: デフォルトを使用するには、ここでapp.swagger_ui_oauth2_redirect_urlを使用できます。swagger_js_url: Swagger UIドキュメントのHTMLがJavaScriptファイルを取得できるURLです。これは、現在あなたのアプリが提供しているものです。swagger_css_url: Swagger UIドキュメントのHTMLがCSSファイルを取得できるURLです。これは、現在あなたのアプリが提供しているものです。
ReDocについても同様です...
from fastapi import FastAPI
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
from fastapi.staticfiles import StaticFiles
app = FastAPI(docs_url=None, redoc_url=None)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
swagger_js_url="/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css",
)
@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
return get_swagger_ui_oauth2_redirect_html()
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
return get_redoc_html(
openapi_url=app.openapi_url,
title=app.title + " - ReDoc",
redoc_js_url="/static/redoc.standalone.js",
)
@app.get("/users/{username}")
async def read_user(username: str):
return {"message": f"Hello {username}"}
ヒント
swagger_ui_redirectのパス操作は、OAuth2を使用する場合のヘルパーです。
APIをOAuth2プロバイダーと統合すると、取得した資格情報で認証してAPIドキュメントに戻ることができます。そして、実際のOAuth2認証を使用してAPIとやり取りできます。
Swagger UIが舞台裏で処理しますが、この「リダイレクト」ヘルパーが必要です。
静的ファイルをテストするためのパス操作を作成する¶
すべてが機能することを確認するために、パス操作を作成します。
from fastapi import FastAPI
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
from fastapi.staticfiles import StaticFiles
app = FastAPI(docs_url=None, redoc_url=None)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
swagger_js_url="/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css",
)
@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
return get_swagger_ui_oauth2_redirect_html()
@app.get("/redoc", include_in_schema=False)
async def redoc_html():
return get_redoc_html(
openapi_url=app.openapi_url,
title=app.title + " - ReDoc",
redoc_js_url="/static/redoc.standalone.js",
)
@app.get("/users/{username}")
async def read_user(username: str):
return {"message": f"Hello {username}"}
静的ファイルUIをテストする¶
これで、Wi-Fiを切断し、http://127.0.0.1:8000/docsでドキュメントにアクセスし、ページをリロードできるはずです。
インターネットがなくても、APIのドキュメントを表示し、操作できるようになります。