오류 처리

FastAPI 입문

Matt Eckerle

Software and Data Leader

오류를 처리하는 두 가지 주요 이유

사용자 오류

  • 잘못되었거나 오래된 URI
  • 누락되었거나 잘못된 입력
@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # Return an error
    else:
        crud.delete_item(item)
        return {}

서버 오류

  • 기타 원인 발생
@app.delete("/items")
def delete_item(item: Item):
    try:
        crud.delete_item(item)
    except Exception:
        # Return an error
    return {}
FastAPI 입문

HTTP 상태 코드: "경고 수준"

  • 응답에서 상태를 제공하도록 API 활성화
    • 성공, 실패, 오류 등
  • HTTP 프로토콜에 정의된 특정 코드
  • 범위: 100 - 599
  • 첫 자리수로 분류 (1 -5)
  1. 정보 응답 (100 - 199)
  2. 성공 응답 (200 - 299)
  3. 리다이렉션 (300 - 399)
  4. 클라이언트 오류 (400 - 499)
  5. 서버 오류 (500 - 599)
1 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
FastAPI 입문

일반적인 HTTP 상태 코드

성공 (200 - 299)

  • 200 OK
    • 기본 성공 응답
  • 201 Created
    • POST 전용
  • 202 Accepted
    • 보류. "처리 중"
  • 204 No Content
    • 성공! 추가 내용 없음

기타 응답

  • 301 Moved Permantently
    • URI가 영구적으로 변경됨
  • 400 Bad Request
    • 클라이언트 오류
  • 404 Not Found
    • 요청한 리소스를 찾을 수 없음
  • 500 Internal Server Error
    • 서버가 처리 방법을 모르는 상황 발생
FastAPI 입문

상태 코드로 오류 처리

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # Send response with status 404 and specific error message
        raise HTTPException(status_code=404, detail="Item not found.")
    else:
        delete_item_in_database(item)
        return {}
FastAPI 입문

Vamos praticar!

FastAPI 입문

Preparing Video For Download...