반응형
🔍 문제 상황
FastAPI로 DELETE API를 만들면서 아래와 같은 요구사항이 생겼다.
- word 값으로만 삭제하지 않고
- type 값도 함께 일치할 때만 삭제하고 싶다
- 즉, (word, type) 쌍이 모두 맞아야 삭제되도록 하고 싶다
🔗 엮인글
[🚀 Dev/Python] - [FastAPI] Swagger UI에서 POST 요청 시 JSON 입력창으로 바뀌는 이유
[🚀 Dev/Python] - [FastAPI] DELETE 요청 시 JSON이 아닌 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
이렇게 요청하면,
- word == "기획전"
- type == "general"
- 인 데이터만 삭제된다.
❗ 자주 하는 실수
@router.delete("by-word-and-type/{word}/{type}") # ❌ 앞에 슬래시(/) 없음!
FastAPI에서는 모든 경로는 반드시 /로 시작해야 한다.
위처럼 쓰면 라우터 등록 자체가 실패하거나, 예상치 못한 경로로 동작하게 된다.
✅ 올바른 방식:
@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 | 선택적 파라미터 처리에 유리 |
이번처럼 word와 type이 모두 필수일 때는 path param이 더 직관적이다.
✨ 결론
- FastAPI에서는 @router.delete("/prefix/{param1}/{param2}") 형태로 여러 개의 path param을 받을 수 있다
- 경로는 항상 /로 시작해야 하며, 타입까지 Enum 등으로 타입 안전하게 받을 수 있다
- Swagger UI에서도 자동으로 잘 렌더링되므로 사용자 친화적인 API가 된다
반응형
'Dev > Python' 카테고리의 다른 글
[Python] requirements.txt 명령어 정리 (0) | 2025.03.30 |
---|---|
[FastAPI] 쿼리 파라미터 vs path 파라미터 설계 전략 (0) | 2025.03.29 |
[FastAPI] DELETE 요청 시 JSON이 아닌 Path Param으로 값 전달하는 방법 (0) | 2025.03.27 |
[FastAPI] Swagger UI에서 POST 요청 시 JSON 입력창으로 바뀌는 이유 (0) | 2025.03.26 |
[FastAPI + PostgreSQL] psycopg2 ENUM 에러 "GENERAL" 해결기 (0) | 2025.03.25 |