リクエストとレスポンスのモデル

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

Matt Eckerle

Software and Data Engineering Leader

APIにおけるリクエストとレスポンスの構造

リクエストの構造
  • クライアントからAPIへ送信されるデータ
  • 主な構成要素:
    • HTTPメソッド(GET、POSTなど)
    • ヘッダー
    • クエリパラメーター
    • リクエストボディ

http://localhost:8000/users/? [email protected]

  • :8000: ポート番号。FastAPIのデフォルトは8000。
  • /users/: アクセスするエンドポイントのパス。
  • ?: クエリパラメーターの開始を示す。
  • `[email protected]`: クエリパラメーター。ここではメールアドレスを渡している。
FastAPI を使った AI のプロダクション環境へのデプロイ

レスポンスの構造

  • APIからクライアントへ返されるデータ
    • ユーザー情報を含むJSONレスポンス
  • 主な構成要素:
    • ステータスコード(200 OK、404 Not Foundなど)
    • ヘッダー
    • レスポンスボディ(要求データまたは処理結果)
HTTP/1.1 200 OK
date: Fri, 18 Oct 2024 12:34:56 GMT
server: uvicorn
content-length: 76
content-type: application/json

{
  "username": "johndoe",
  "email": "[email protected]",
  "age": 30
}
FastAPI を使った AI のプロダクション環境へのデプロイ

Pydanticモデル

  • User の作成
  • Pydanticの使用
from pydantic import BaseModel
class User(BaseModel):
    username: str
    email: str
    age: int
  • BaseModelを継承
  • 型アノテーションで属性を定義
  • 型に基づく自動バリデーション
FastAPI を使った AI のプロダクション環境へのデプロイ

バリデーションエラー

from pydantic import ValidationError
try:
    invalid_user = User(username="john_doe", email="[email protected]", 
                        age="thirty")
    print("Invalid User:", invalid_user)
except ValidationError as e:
    print("Validation Error:", e)
Validation Error: 1 validation error for User age
Input should be a valid integer, unable to parse string as an integer 
[type=int_parsing, input_value='thirty', input_type=str]
FastAPI を使った AI のプロダクション環境へのデプロイ

FastAPIでのPydanticモデルの活用

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()

class User(BaseModel): username: str email: str age: int
@app.post("/users", response_model=User)
async def create_user(user: User): return user
  • response_model として使用
  • パラメーターの型ヒントとして使用
  • リクエストの自動バリデーション
  • リクエスト/レスポンスのシリアライズ
  • APIドキュメントの自動生成
FastAPI を使った AI のプロダクション環境へのデプロイ

リクエストとレスポンスの形式

curl -X 'POST' \
  'http://localhost:8000/users/' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "username": "john_doe",
  "email": "[email protected]",
  "age": 30
  }'

 

{
  "username": "john_doe",
  "email": "[email protected]",
  "age": 30
}
FastAPI を使った AI のプロダクション環境へのデプロイ

練習しましょう!

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

Preparing Video For Download...