Published on

FastAPI 문서 시스템 /docs, redoc, swagger 비교

Authors
  • avatar
    Name
    devnmin
    Twitter

🚀 FastAPI 문서 시스템 개요

FastAPI는 API 문서화를 자동으로 제공하는 기능을 포함하고 있습니다. 즉, 코드만 작성하면 멋진 API 문서를 그냥 덤으로 얻을 수 있다는 뜻이죠! 😎 (삽입할 이미지: FastAPI 로고 또는 API 문서 예시 화면)

📖 FastAPI에서 제공하는 문서화 도구

FastAPI는 기본적으로 다음과 같은 문서화 도구를 제공합니다. 하나하나 살펴보겠습니다!

🎨 Swagger UI (/docs)

  • FastAPI의 기본 문서화 인터페이스이자, API를 편하게 테스트할 수 있는 친구입니다.
  • 버튼 클릭 몇 번으로 GET, POST 요청을 바로 날려볼 수 있습니다! (삽입할 이미지: Swagger UI 예제 화면)
  • docs_url 설정을 통해 원하는 경로로 변경 가능!
Swagger UI 예제 화면

📜 ReDoc (/redoc)

  • 보기 좋고 정리된 API 문서를 원한다면? ReDoc을 선택하세요!
  • 깔끔한 디자인과 UX 덕분에 눈이 편안해집니다. 🌿
  • 하지만 직접 API 요청 테스트는 불가능합니다. (삽입할 이미지: ReDoc 예제 화면)
ReDoc 예제 화면

🔍 OpenAPI 스펙 (/openapi.json)

  • API 구조를 JSON 형식으로 확인할 수 있는 URL입니다.
  • '자동 API 클라이언트 생성'이라는 강력한 기능을 지원합니다.
  • UI가 없어서 심심할 수 있지만, 백엔드 개발자에게는 보물 같은 존재! 🏆
OpenAPI JSON 예제 화면

🆚 문서화 도구 비교

기능Swagger UI (/docs)ReDoc (/redoc)OpenAPI JSON (/openapi.json)
UI 제공 여부
API 테스트
가독성중간높음낮음
설정 가능 여부

🔧 FastAPI 문서 시스템 설정하는 법

FastAPI의 문서 시스템은 아주 간단한 코드 몇 줄로 원하는 대로 설정할 수 있습니다! 🎯


from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List

app = FastAPI(
    docs_url="/api-docs",
    redoc_url="/api-redoc",
    openapi_url="/api-openapi.json"
)

# 데이터 저장소 역할을 하는 임시 딕셔너리
items = {}

# Pydantic 모델 정의
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    quantity: int

@app.get("/", tags=["Root"])
def read_root():
    return {"message": "Welcome to FastAPI Sample!"}

# 모든 아이템 조회
@app.get("/items", response_model=List[Item], tags=["Items"])
def get_items():
    return list(items.values())

# 특정 아이템 조회
@app.get("/items/{item_id}", response_model=Item, tags=["Items"])
def get_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return items[item_id]

# 새 아이템 생성
@app.post("/items/{item_id}", response_model=Item, tags=["Items"])
def create_item(item_id: int, item: Item):
    if item_id in items:
        raise HTTPException(status_code=400, detail="Item already exists")
    items[item_id] = item
    return item

# 아이템 업데이트
@app.put("/items/{item_id}", response_model=Item, tags=["Items"])
def update_item(item_id: int, item: Item):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    items[item_id] = item
    return item

# 아이템 삭제
@app.delete("/items/{item_id}", tags=["Items"])
def delete_item(item_id: int):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    del items[item_id]
    return {"message": "Item deleted"}


이제 /docs, /redoc, /openapi.json 대신 원하는 URL에서 API 문서를 확인할 수 있습니다! 🎉 추가적인 설정을 한다면 /api-docs, /api-redoc, /api-openapi.json 경로로 접속할 수 있습니다.

✨ 결론

FastAPI의 문서화 도구들은 API 개발을 한층 더 편하게 만들어 줍니다. 🚀

  • Swagger UI는 테스트하기 편하고,
  • ReDoc은 보기 좋으며,
  • OpenAPI JSON은 개발자들이 환호하는 기능을 제공합니다.

여러분의 프로젝트에 맞는 문서화 도구를 선택해서 활용하세요! Happy coding! 😆