[python] FastAPI에 Swagger UI 통합하기

FastAPI는 빠르고 현대적인 웹 프레임워크로서, API 개발에 많은 도움을 줍니다. 이 블로그 포스트에서는 FastAPI에 Swagger UI를 통합하여 API 문서화를 쉽게하는 방법에 대해 알아보겠습니다.

Swagger UI란?

Swagger UI는 OpenAPI(Swagger) 스펙을 활용하여 API 문서를 자동으로 생성해주는 도구입니다. Swagger UI는 API 엔드포인트, 매개변수, 응답 형식 등을 시각적으로 표시하여 API 사용자가 쉽게 이해하고 사용할 수 있도록 도와줍니다.

FastAPI에 Swagger UI 추가하기

FastAPI는 기본적으로 Swagger UI를 지원하고 있습니다. 따라서 추가 설정 없이 기본적인 Swagger UI를 사용할 수 있습니다.

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

위의 예제 코드에서는 /items/{item_id} 엔드포인트를 정의하고 있습니다. 이를 FastAPI 서버를 실행한 후 http://localhost:8000/docs에 접속하면 Swagger UI를 확인할 수 있습니다.

Swagger UI 꾸미기

만약 기본적인 Swagger UI 디자인에 만족하지 않는다면, FastAPI에서는 Swagger UI를 활성화할 때 몇 가지 옵션을 설정할 수 있습니다. 예를 들어, 수정 가능한 메시지를 추가하거나 커스텀 CSS를 적용할 수 있습니다.

from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="Custom Swagger UI",
        version="1.0.0",
        description="This is a custom Swagger UI",
        routes=app.routes,
    )
    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi

위의 예제 코드에서는 custom_openapi 함수를 정의하여 커스텀한 Swagger UI를 만들고 있습니다. 이 함수에서는 제목, 버전, 설명 등을 설정한 후 app.openapi에 할당하는 방식으로 Swagger UI를 꾸밀 수 있습니다.

결론

FastAPI에는 Swagger UI를 통합하는 기능이 기본적으로 포함되어 있습니다. 따라서 FastAPI를 사용하여 API를 개발하는 경우, 간단한 설정만으로도 Swagger UI를 활용할 수 있습니다. 또한 FastAPI에서 제공하는 옵션을 활용하여 Swagger UI를 커스터마이징할 수도 있습니다.

더 자세한 내용은 FastAPI 공식 문서를 참조하세요.