この回答はGPT-4による自動生成回答です
FastAPIのAPIドキュメントは、Swagger UIを利用して生成されています。権限に応じてエンドポイントを表示・非表示にするためには、カスタムテンプレートを使用してSwagger UIを調整する必要があります。
以下の手順で実装できます。
- FastAPIアプリケーションでカスタムテンプレートを使用するように設定します。
python
1from fastapi import FastAPI
2from fastapi.openapi.docs import get_swagger_ui_html
3
4app = FastAPI()
5
6@app.get("/docs", include_in_schema=False)
7async def custom_swagger_ui_html():
8 return get_swagger_ui_html(openapi_url="/openapi.json", title="Custom Swagger UI")
- カスタムテンプレートを作成し、権限に応じてエンドポイントを表示・非表示にするJavaScriptコードを追加します。
html
1<!-- custom_swagger_ui.html -->
2{% extends "swagger_ui.html" %}
3
4{% block scripts %}
5{{ super() }}
6<script>
7 // ここに権限に応じてエンドポイントを表示・非表示にするコードを追加
8 // 例: 管理者権限がある場合のみ、特定のエンドポイントを表示
9 document.addEventListener("DOMContentLoaded", function () {
10 const isAdmin = /* 管理者権限の判定 */;
11 if (!isAdmin) {
12 const endpointElements = document.querySelectorAll('.opblock-summary');
13 endpointElements.forEach(function (element) {
14 if (element.getAttribute('data-path') === '/admin/endpoint') {
15 element.style.display = 'none';
16 }
17 });
18 }
19 });
20</script>
21{% endblock %}
- FastAPIアプリケーションでカスタムテンプレートを使用するように設定します。
python
1from fastapi import FastAPI
2from fastapi.openapi.docs import get_swagger_ui_html
3from fastapi.templating import Jinja2Templates
4
5app = FastAPI()
6templates = Jinja2Templates(directory="templates")
7
8@app.get("/docs", include_in_schema=False)
9async def custom_swagger_ui_html(request: Request):
10 return templates.TemplateResponse("custom_swagger_ui.html", {"request": request, "openapi_url": "/openapi.json", "title": "Custom Swagger UI"})
これで、権限に応じてエンドポイントが表示・非表示になるカスタムSwagger UIが実装できます。ただし、権限の判定やエンドポイントの表示・非表示の条件は、実際の要件に応じて調整してください。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。