콘텐츠로 이동

코드 이해하기

이 페이지에서는 생성하기에서 만든 shop 프로젝트의 main.py를 읽고, 각 엔드포인트에 올바른 요청과 잘못된 요청을 보내 봅니다. FastAPI가 쿼리 매개변수, 경로 매개변수, JSON 요청 본문을 읽는 방법과 이 값들을 검증하고 잘못된 값에 422로 응답하는 방법을 배웁니다. 또한 응답 모델과 상태 코드가 응답의 형태를 정하는 방법, HTTPException으로 오류를 반환하는 방법, 그리고 async def를 써야 하는 경우도 함께 살펴봅니다.

main.py를 읽는 방법

main.py는 위에서 아래로 읽습니다. 파일에서 FastAPI의 개념이 처음 사용되는 곳에는 그 개념을 설명하는 한두 줄짜리 주석이 있고, 주석의 마지막 줄에는 해당 개념을 다루는 FastAPI 튜토리얼 페이지의 링크가 있습니다. 각 개념에는 주석을 한 번만 달기 때문에, 뒤에 나오는 엔드포인트가 같은 일을 하더라도 그곳에는 주석이 없습니다.

직접 따라 해 보려면 프로젝트 폴더에서 fastkit runserver로 서버를 실행하고, 두 번째 터미널에서 아래 요청을 보냅니다. 아이템은 메모리에만 저장되므로, /docs에서 이미 아이템을 만들었다면 먼저 서버를 다시 시작하세요. 서버를 다시 시작하지 않으면 ID가 아래 예시와 달라지므로, POST 요청이 반환한 ID를 대신 사용해야 합니다. 같은 요청을 http://127.0.0.1:8000/docs에서 "Try it out"으로 보낼 수도 있습니다.

앱과 모델

pydantic 모델은 JSON 객체의 필드와 그 타입을 속성으로 선언하는 클래스입니다. FastAPI는 이 모델을 사용해 요청 본문을 읽고, 검증한 다음, Python 객체로 변환합니다. Field(...)는 제약 조건을 추가합니다. 여기서는 이름을 1자 이상 100자 이하로, 가격을 0보다 크게 제한합니다.

main.py
app = FastAPI(title="shop")


# An argument typed with a pydantic model (`item: Item`) is the validated JSON body.
# https://fastapi.tiangolo.com/tutorial/body/
class Item(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    price: float = Field(gt=0)
    description: str | None = None


# The return type of an endpoint is its response model: it shapes the output.
# https://fastapi.tiangolo.com/tutorial/response-model/
class StoredItem(Item):
    id: int


items: dict[int, StoredItem] = {}

StoredItem은 id가 추가된 Item입니다. 클라이언트는 Item을 보내고, API는 StoredItem으로 응답합니다. items는 아이템을 메모리에 보관하는 평범한 딕셔너리이므로, 서버를 다시 시작하면 저장된 아이템이 모두 사라집니다.

쿼리 매개변수

쿼리 매개변수는 /?name=Ada처럼 URL의 ? 뒤에 오는 key=value 쌍입니다. FastAPI에서는 str이나 int 같은 단순한 타입을 가진 인자가 경로에 포함되어 있지 않으면 기본적으로 쿼리 매개변수로 취급됩니다. 반면에 타입이 pydantic 모델인 인자는 다음 섹션에서 보듯이 요청 본문에서 읽습니다. Query(...)는 제약 조건을 추가하고, 기본값("World")을 지정하면 이 매개변수는 선택 사항이 됩니다.

main.py
@app.get("/")
async def read_root(
    # A str, int or bool argument not in the path is a query parameter: /?name=Ada
    # https://fastapi.tiangolo.com/tutorial/query-params/
    name: Annotated[str, Query(min_length=1, max_length=50)] = "World",
) -> dict[str, str]:
    return {"message": f"Hello, {name}! Welcome to {app.title}", "docs": "/docs"}

빈 이름은 min_length=1 제약 조건을 어깁니다. 이때 FastAPI는 함수를 실행하기 전에 요청을 거부하고 422 Unprocessable Entity로 응답합니다. 응답 본문에는 문제가 발생한 위치(loc: 쿼리 매개변수 name)와 문제의 내용(msg)이 담겨 있습니다.

$ curl -s -i "http://127.0.0.1:8000/?name="
HTTP/1.1 422 Unprocessable Entity
...
{"detail":[{"type":"string_too_short","loc":["query","name"],"msg":"String should have at least 1 character","input":"","ctx":{"min_length":1}}]}

요청 본문과 상태 코드

인자의 타입이 pydantic 모델이면 FastAPI는 그 값을 요청의 JSON 본문에서 읽습니다. 반환 타입인 StoredItem은 응답 모델입니다. FastAPI는 반환된 객체를 응답 모델로 검사하고, 모델에 정의된 필드만 보내며, 이 모델을 /docs에 문서화합니다. status_code=status.HTTP_201_CREATED는 기본 상태 코드 200을 201 Created로 바꿉니다. 201은 요청으로 무언가를 새로 만들었을 때 흔히 쓰는 상태 코드입니다.

main.py
# `status_code` sets the status of a successful response: 201 Created.
# https://fastapi.tiangolo.com/tutorial/response-status-code/
@app.post("/items", status_code=status.HTTP_201_CREATED)
async def create_item(item: Item) -> StoredItem:
    stored = StoredItem(id=len(items) + 1, **item.model_dump())
    items[stored.id] = stored
    return stored
$ curl -s -i -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"name": "Hammer", "price": 9.5}'
HTTP/1.1 201 Created
...
{"name":"Hammer","price":9.5,"description":null,"id":1}

요청 본문에 description이 빠져 있으므로, 이 필드는 모델의 기본값인 null(Python의 None)이 됩니다. 가격이 음수이면 Field(gt=0)를 어기게 되고, 422 응답 본문은 요청 본문의 price를 문제의 위치로 가리킵니다.

$ curl -s -i -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"name": "Saw", "price": -1}'
HTTP/1.1 422 Unprocessable Entity
...
{"detail":[{"type":"greater_than","loc":["body","price"],"msg":"Input should be greater than 0","input":-1,"ctx":{"gt":0.0}}]}

{"name": "Hammer", "price": 9.5} 본문으로 POST /items를 실행한 뒤의 Swagger UI: curl 명령과, 새 아이템과 그 ID가 담긴 201 응답

가격을 -1로 지정해 POST /items를 실행한 뒤의 Swagger UI: 가격은 0보다 커야 한다는 detail이 담긴 422 응답

경로 매개변수와 오류

경로 매개변수는 경로 자체의 일부이며, 데코레이터에는 {item_id}처럼 적습니다. FastAPI는 이 값을 이름이 같은 함수 인자에 전달하면서 선언된 타입인 int로 변환합니다. 해당 ID를 가진 아이템이 없으면 함수는 HTTPException을 발생시킵니다. 그러면 FastAPI는 요청 처리를 그 자리에서 멈추고, 지정한 상태 코드와 detail로 응답합니다.

main.py
# `{item_id}` in the path arrives as an argument, converted to `int`.
# https://fastapi.tiangolo.com/tutorial/path-params/
@app.get("/items/{item_id}")
async def read_item(item_id: int) -> StoredItem:
    if item_id not in items:
        # HTTPException stops the request and answers with an error status.
        # https://fastapi.tiangolo.com/tutorial/handling-errors/
        raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Item not found")
    return items[item_id]
$ curl -s http://127.0.0.1:8000/items/1
{"name":"Hammer","price":9.5,"description":null,"id":1}
$ curl -s -i http://127.0.0.1:8000/items/99
HTTP/1.1 404 Not Found
...
{"detail":"Item not found"}
$ curl -s -i http://127.0.0.1:8000/items/abc
HTTP/1.1 422 Unprocessable Entity
...
{"detail":[{"type":"int_parsing","loc":["path","item_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"abc"}]}

abc는 정수가 아니므로 FastAPI는 read_item을 호출하지 않고 422로 응답합니다. 따라서 item_id를 직접 변환하거나 검사할 필요가 전혀 없습니다.

async def와 def

main.py의 엔드포인트는 모두 async def 함수입니다. async def 함수 안에서는 비동기 데이터베이스 드라이버나 HTTP 클라이언트 같은 다른 비동기 코드를 await할 수 있으며, 한 요청이 기다리는 동안 서버는 다른 요청을 처리합니다. 이 페이지의 엔드포인트는 딕셔너리를 읽고 쓰기만 하므로 기다리는 일이 없습니다. 엔드포인트가 블로킹 방식으로 동작하는 라이브러리(await를 쓰지 않는 라이브러리)를 호출한다면 평범한 def를 사용하세요. 그러면 FastAPI가 그 함수를 스레드 풀에서 실행하므로 다른 요청의 처리가 지연되지 않습니다.

FastAPI 문서

다음 단계

앱 확장하기에서는 /users 리소스를 추가합니다. 처음에는 직접 손으로 추가하고, 그다음에는 계층형 프로젝트에서 fastkit addroute로 추가합니다.