AIのGETリクエストとPOSTリクエスト

FastAPI を使った AI のプロダクション環境へのデプロイ

Matt Eckerle

Software and Data Engineering Leader

インストラクター紹介

 

Matt Eckerle

 

 

Matt Eckerle

  • ソフトウェア・データエンジニアリングリーダー
  • Inari社 エンタープライズデータマネージャー
  • 2019年よりFastAPIをML用途で活用
FastAPI を使った AI のプロダクション環境へのデプロイ

コース概要

 

 

  • FastAPIの基礎
  • リクエスト処理と統合
  • 入力バリデーションとセキュリティ
  • 本番対応APIの作成と保守

 

 

FastAPIのロゴ

FastAPI を使った AI のプロダクション環境へのデプロイ

始める前に

✓ Pythonの基礎:関数、クラス、モジュール、データ構造

Pythonのロゴ

FastAPI を使った AI のプロダクション環境へのデプロイ

始める前に

✓ Pythonの基礎:関数、クラス、モジュール、データ構造

✓ HTTPとREST APIの概念

PythonとHTTPのロゴ

FastAPI を使った AI のプロダクション環境へのデプロイ

始める前に

✓ Pythonの基礎:関数、クラス、モジュール、データ構造

✓ HTTPとREST APIの概念

✓ FastAPIフレームワークの使用

  • GETリクエストとPOSTリクエストの処理
  • Pydanticモデルの使用

✓ 機械学習の基礎

Python、HTTP、FastAPIのロゴ

FastAPI を使った AI のプロダクション環境へのデプロイ

GETリクエストの解説

  • データの取得に使用
  • パスパラメータ - URLに含まれる情報
  • サーバーの状態を変更しない

メニュー

GET https://example.com/?item_id=1

GETリクエストを説明する図

FastAPI を使った AI のプロダクション環境へのデプロイ

パスパラメータを使ったGETの実装

from fastapi import FastAPI

app = FastAPI()

@app.get("/item/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
  • `@app.get` デコレータでエンドポイントを定義。
  • {item_id} はパスパラメータ。
  • 型ヒント(int)で自動バリデーション。
FastAPI を使った AI のプロダクション環境へのデプロイ

POSTリクエストの解説

  • サーバーへのデータ送信に使用
  • データはリクエストボディに含む(通常JSON)
  • サーバーの状態を変更できる

レストランの注文

POST https://example.com

POSTリクエストを説明する図

FastAPI を使った AI のプロダクション環境へのデプロイ

JSONデータを使ったPOSTの実装

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()
db = {}

class Item(BaseModel): name: str price: float
@app.post("/items", status_code=201)
def create_item(item: Item): db[item.name] = item.model_dump() return {"message": f"Created {item.name}"}

 

  • Pydanticモデルでデータ構造を定義
  • @app.post でPOSTエンドポイントを定義
  • JSONの自動解析とバリデーション
FastAPI を使った AI のプロダクション環境へのデプロイ

HTTPステータスコード

 

  • 200 OK: 成功時のデフォルト
  • 404 Not Found: リソースが見つからない
  • 201 Success: オブジェクト作成完了

リクエスト成功を示すHTTP 200ステータスコード

FastAPI を使った AI のプロダクション環境へのデプロイ

HTTP例外の発生

from fastapi import FastAPI, HTTPException
app = FastAPI()

@app.get("/item/{item_id}")
async def read_item(item_id: int):
    if item_id == 4242: #An invalid order number
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}

@app.post("/items") async def create_item(item: Item): # Simulating item creation return {"message": f"Created {item.name}"}, 201
FastAPI を使った AI のプロダクション環境へのデプロイ

では、練習しましょう!

FastAPI を使った AI のプロダクション環境へのデプロイ

Preparing Video For Download...