본문 바로가기

[FastAPI] DELETE 요청 시 JSON이 아닌 Path Param으로 값 전달하는 방법

@Jeeqong 2025. 3. 27. 03:46
반응형

FastAPI에서 DELETE 요청 시 path param 여러 개 받는 방법

🔍  문제 상황

FastAPI로 DELETE API를 만들면서 아래와 같은 요구사항이 생겼다.

  • word 값으로만 삭제하지 않고
  • type 값도 함께 일치할 때만 삭제하고 싶다
  • 즉, (word, type) 쌍이 모두 맞아야 삭제되도록 하고 싶다

🔗 엮인글

[🚀 Dev/Python] - [FastAPI] Swagger UI에서 POST 요청 시 JSON 입력창으로 바뀌는 이유

[🚀 Dev/Python] - [FastAPI] DELETE 요청 시 path param 여러 개 받는 방법

[🚀 Dev/Python] - [FastAPI] 쿼리 파라미터 vs path 파라미터 설계 전략

[🚀 Dev/Python] - [FastAPI] 다중 필터 검색 API 설계 (예: /products?brand=..&category=..)

[🚀 Dev/Python] - [FastAPI] 페이징, 정렬, 리스트 파라미터까지 포함한 검색 API 확장 설계

[🚀 Dev/Nextjs] - [Nextjs] 필터 UI → FastAPI 다중 필터 API 연결 가이드



❓ 어떻게 라우터를 구성해야 할까?

FastAPI는 RESTful 스타일에 맞게 path param 여러 개를 받을 수 있다.

예를 들어 아래와 같은 경로를 만들 수 있다:

@router.delete("/by-word-and-type/{word}/{type}")

✅ 실제 구현 예시

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.db.enums import ExcludeWordType
from app.crud import crud_exclude_words

router = APIRouter()

@router.delete("/by-word-and-type/{word}/{type}")
def delete_exclude_word(
    word: str,
    type: ExcludeWordType,
    db: Session = Depends(get_db)
):
    return crud_exclude_words.delete_by_word_and_type(db, word, type)


📌 요청 예시

DELETE /exclude_words/by-word-and-type/공구/general


❗ 자주 하는 실수

@router.delete("by-word-and-type/{word}/{type}")  # ❌ 앞에 슬래시(/) 없음!

✅ 올바른 방식:

@router.delete("/by-word-and-type/{word}/{type}")


✅ path vs query 비교

방식 예시 요청 장점
path param /by-word-and-type/공구/general RESTful, 명확한 리소스 식별
query param /by-word-and-type?word=공구&type=general 선택적 파라미터 처리에 유리

결론

  • FastAPI에서 path param 여러 개 받는 건 아주 자연스러운 방식이다
  • 경로는 반드시 /로 시작해야 함
  • Swagger UI에서도 자동 인식되어 사용자가 쉽게 테스트할 수 있다
반응형
Jeeqong
@Jeeqong :: JQVAULT

Jeeqong's vault : 정보/기록을 쌓아두는 공간 웹개발 포스팅 일상 리뷰를 기록하는 공간입니다.

공감하셨다면 ❤️ 구독도 환영합니다! 🤗

목차