기술과 산업/언어 및 프레임워크
FastAPI 시리즈 7화 - Response 모델과 응답 커스터마이징
B컷개발자
2025. 5. 7. 00:48
728x90
FastAPI에서 response_model, status_code, headers, media_type 등 응답(Response) 커스터마이징 방법을 예제 중심으로 정리합니다. 실전 API 응답 설계에 최적화된 내용입니다.
왜 응답 커스터마이징이 중요한가?
FastAPI는 기본적으로 JSON 응답을 반환하지만, 실전 서비스에서는 다양한 응답 포맷, 상태 코드, 헤더 구성이 필요합니다.
예를 들어:
- 응답 데이터 필터링 (민감 정보 제거)
- HTTP 상태 코드 명시
- 사용자 정의 헤더 추가
- JSON 이외의 MIME 타입 사용
이러한 케이스를 FastAPI는 간단한 선언형 문법으로 처리할 수 있습니다.
1. response_model로 응답 필터링
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class UserIn(BaseModel):
name: str
email: str
password: str
class UserOut(BaseModel):
name: str
email: str
@app.post("/users", response_model=UserOut)
def create_user(user: UserIn):
return user
- UserIn: 요청 모델
- UserOut: 응답 모델
- response_model=UserOut 설정 시, 반환 데이터에서 password 필드는 자동 제거
✅ 장점
- 민감 정보 보호
- 명확한 API 응답 스펙 제시
- Swagger UI에 자동 반영
2. 상태 코드 지정 – status_code
from fastapi import status
@app.post("/users", response_model=UserOut, status_code=status.HTTP_201_CREATED)
def create_user(user: UserIn):
return user
- status_code=201로 HTTP 201 Created 명시
- 클라이언트는 단순 200 OK보다 명확한 의미를 해석 가능
▶ status 코드 예시
상태상수의미
| 200 | status.HTTP_200_OK | 기본 응답 |
| 201 | status.HTTP_201_CREATED | 리소스 생성 |
| 204 | status.HTTP_204_NO_CONTENT | 본문 없는 성공 응답 |
| 400 | status.HTTP_400_BAD_REQUEST | 잘못된 요청 |
| 404 | status.HTTP_404_NOT_FOUND | 리소스 없음 |
3. 헤더 커스터마이징 – Response 객체 사용
from fastapi import Response
@app.get("/custom-header")
def get_custom_header(response: Response):
response.headers["X-Service-Version"] = "1.2.3"
return {"message": "Header set"}
- 응답 헤더에 X-Service-Version 추가
- 로그 추적, API 버전 식별 등에 활용 가능
4. MIME 타입 설정 – media_type
from fastapi.responses import HTMLResponse
@app.get("/html", response_class=HTMLResponse)
def get_html():
return "<h1>Hello, FastAPI</h1>"
- 기본 JSON이 아닌 HTML로 응답
- 문서 보기, 메일 템플릿, 결과 미리보기 등 다양한 용도에 활용 가능
▶ 주요 Response 클래스
클래스MIME 타입용도
| JSONResponse | application/json | 기본 응답 |
| HTMLResponse | text/html | HTML 텍스트 |
| PlainTextResponse | text/plain | 일반 텍스트 |
| FileResponse | 파일 다운로드 | |
| StreamingResponse | 대용량 스트리밍 데이터 응답 |
5. 응답 지연 처리 (보너스)
import time
@app.get("/delay")
def delayed_response():
time.sleep(2)
return {"message": "Delayed 2 seconds"}
- 비동기 함수로 처리하면 지연 중에도 다른 요청 처리 가능
import asyncio
@app.get("/async-delay")
async def async_delayed_response():
await asyncio.sleep(2)
return {"message": "Asynchronous delay complete"}
정리 – FastAPI의 응답 처리, 핵심은 선언적 설계
기능구현 방식
| 응답 필터링 | response_model=모델 |
| 상태 코드 지정 | status_code=status.HTTP_XXX |
| 헤더 설정 | Response 객체 활용 |
| MIME 타입 변경 | response_class=XXXResponse |
| 비동기 지연 | async def + await |
FastAPI는 이런 설정이 코드 안에서 직관적으로 관리되고,
Swagger UI에 모두 반영되어 개발과 문서화 사이의 간극을 줄여줍니다.
다음 글 예고
FastAPI 시리즈 8화 - 의존성 주입 시스템(Depends) 실전 활용법
에서는 FastAPI의 또 다른 강력한 기능인 Depends를 활용한
보안 인증, 공통 로직 재사용, DB 연결 관리 등 실무 활용 패턴을 다룹니다.
728x90