Python/FastAPI

[FastAPI] (3) FastAPI 열거형 enum - GET

yubi5050 2022. 10. 5. 04:54

Enum이란?

열거형 (Enumeration) 객체로, Python 에서 Query Parameters, Path Parameters에 대한 Entity 정의를 하기 위해 사용

Case 1

from enum import Enum
class Score(str, Enum):
    A="A"
    B="B"
    C="C"

@app.get("/grade")
def get_grade(score:Score):
    return {"score":score}

요청 1) curl localhost:8000/grade?score=A => { "score":A } 반환

요청 2) curl localhost:8000/grade => 422 entity error 발생

요청 3) curl localhost:8000/grade?score=D => 422 entity error 발생

 

Case 2 - 기본값 추가

from enum import Enum
class Score(str, Enum):
    A="A"
    B="B"
    C="C"

@app.get("/grade")
def get_grade(score:Score = Score.B):
    return {"score":score}

요청 1) curl localhost:8000/grade?score=A => { "score":A } 반환

요청 2) curl localhost:8000/grade => { "score":B } 반환