반응형
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에서도 자동 인식되어 사용자가 쉽게 테스트할 수 있다
반응형
'Dev > Python' 카테고리의 다른 글
[FastAPI] 쿼리 파라미터 vs path 파라미터 설계 전략 (0) | 2025.03.29 |
---|---|
[FastAPI] DELETE 요청 시 path param 여러 개 받는 방법 (0) | 2025.03.28 |
[FastAPI] Swagger UI에서 POST 요청 시 JSON 입력창으로 바뀌는 이유 (0) | 2025.03.26 |
[FastAPI + PostgreSQL] psycopg2 ENUM 에러 "GENERAL" 해결기 (0) | 2025.03.25 |
[Python] 주석(Comment) vs. 독스트링(Docstring) 차이점 (0) | 2025.03.24 |