반응형
안녕하세요.
이번 시간에는 FastAPI의 문서(docs 및 redoc)에
오류 명세 등을 상세히 적기 위하여 response model을 부여하는 방법을
간략하게 정리해보도록 하겠습니다.
다음과 같은 간단한 FastAPI 서버가 있다고 가정해보도록 하겠습니다.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def my_func():
pass
오류 명세 json 양식
여기서 response model의 정의는 json으로 진행되는데요.
다음과 같은 포맷으로 오류에 대한 명세를 작성해주시면 됩니다.
에러번호(integer) : {
"description": "에러의 제목",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"detail": {
"type": "string",
"description": "redoc에서 보여줄 메시지"
}
},
"example": {"detail": "docs에서 보여줄 메시지"}
}
}
},
}
예를 들어,
제가 작성한 에러의 상세 명세의 예시는 다음과 같습니다.
MY_ERROR_MODEL = {
401 : {
"description": "인증 실패",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"detail": {
"type": "string",
"description": "올바른 인증 정보를 입력해주세요."
}
},
"example": {"detail": "인증 정보 검증에 실패하였습니다."}
}
}
},
},
404 : {
"description": "삭제된 데이터 조회 시도",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"detail": {
"type": "string",
"description": "올바른 데이터 id를 입력해주세요."
}
},
"example": {"detail": "삭제된 데이터 id 입력"}
}
}
},
},
422 : {
"description": "요청 데이터의 유효성 검사 실패",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"detail": {
"type": "string",
"description": "데이터 타입이 이상합니다. 따옴표나 괄호가 맞는지도 확인하세요."
}
},
"example": {"detail": "데이터 타입 오류"}
}
}
},
},
502: {
"description": "API 서버 오류",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"detail": {
"type": "string",
"description": "API 서버 호출 과정에서 문제가 발생하였습니다."
}
},
"example": {"detail": "API 서버 호출 과정 문제 발생"}
}
}
},
},
504: {
"description": "API 서버 응답 시간 초과",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"detail": {
"type": "string",
"description": "API 서버 호출 과정에서 제한된 시간 내 응답이 없습니다."
}
},
"example": {"detail": "API 서버 호출이 오래 걸리는 문제"}
}
}
},
},
}
response model 부여 방법
앞에서 구현한 response model 에러 명세를 docs 및 redoc에 주입하는 방법은
API 호출 함수 데코레이터의 responses 인자에 정의한 모델을 작성해주시면 됩니다.
@app.get("/", responses=MY_ERROR_MODEL)
def my_func():
pass
docs 및 redoc 확인
앞서 구현한 response model의 오류 명세를 docs 및 redoc에서 확인해보면 다음과 같습니다.
docs 예시

redoc 예시(접기)

redoc 예시(펼치기)

FastAPI 서버의 오류 명세를 작성하는 과정에 도움이 되셨기를 바라겠습니다.
잘 봐주셔서 감사드립니다.
'Python > Backend' 카테고리의 다른 글
FastAPI 동기/비동기 설정 시 주의 사항 (0) | 2025.02.17 |
---|---|
FastAPI 서버를 HTTPS로 실행하는 방법 (2) | 2024.12.01 |
FastAPI docs 작성 방법 정리 (0) | 2024.07.30 |