エラー処理

FastAPI入門

Matt Eckerle

Software and Data Leader

エラー処理が必要な2つの主な理由

ユーザー側のエラー

  • 無効または古い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ステータスコード:警告レベルの分類

  • レスポンスで状態を返せる
    • 成功、失敗、エラーなど
  • 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 a practicar!

FastAPI入門

Preparing Video For Download...