개발 이야기/개발툴 및 기타 이야기
보안망에서 FastAPI에 Swagger UI 설정방법
가온아
2024. 12. 22. 01:07
(인터넷이 연결되지 않는)보안망에서 FastAPI를 이용해 API 서버를 만들고 /docs에 접근하면 swagger ui 가 보이지 않는다. fastapi에서 swagger ui 를 등록된 cdn에 연결해 다운로드를 시도하다 실패해 버린다.
만약 필요없다면 다음과 같이 설정해 /docs로 접속해도 아무런 처리가 되지 않도록 설정할 수 있다.
app = FastAPI(docs_url=None, redoc_url=None)
swagger ui를 사용하기 위해서는 swagger ui 프로젝트의 dist 폴더 파일만 있으면 된다. (링크)
이 파일을 다운받아 fastapi 프로젝트에 포함해 배포하면 됩니다. 설정은 다음과 같다.
dist의 파일들을 프로젝트 내의 src/statics에 넣고 다음과 같이 설정한다.
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi import FastAPI
app = FastAPI()
# static 폴더 지정
app.mount("/static", StaticFiles(directory="src/static"), name="static")
# docs 접근에 대한 상세 설정
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title="Custom Swagger UI",
swagger_js_url="/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css",
)
.
.
이제 /docs로 접속하면 swagger ui 가 보인다.
프로젝트에 따라 굳이 swagger ui 는 필요없고 openapi.json 정보만 필요한 경우가 있다. 그럴때는 다음과 같이 설정하면 된다.
app = FastAPI(docs_url=None, redoc_url=None, openapi_url="/openapi.json")
@app.get("/openapi.json", include_in_schema=False)
async def custom_openapi_json():
return app.openapi()
끝!!
반응형